Приветствую всех любителей программирования на новой статье с подборкой интересных задач для тренировки навыков решения алгоритмических проблем. В этом материале я собрал разнообразные задания из разных источников, чтобы каждый мог проверить свои силы в этой захватывающей области! Цель статьи — не только улучшить практическое владение алгоритмами, но и поддерживать интерес к написанию кода, а также добавить немного веселья в процесс.
Что было раньше:
В предыдущей части мы решили:
- !a == a ?! (! a == a?!)
- Counting Characters (Подсчет персонажей)
- New season, new league (Новый сезон, новая лига)
- Help the farmer to count rabbits, chickens and cows (Помогите фермеру посчитать кроликов, цыплят и коров)
- Slay Achilles! (Убей Ахиллес!)
- Multiples of 3 and 5 redux (Кратные 3 и 5 redux)
- Text message codec (Кодек текстовых сообщений)
- Pick peaks (Выберите пики)
Решение новых задач:
Задача 1
Платформа: CodeWars
Название задачи: Learning TypeScript. Basic Types (Обучающий типа. Основные типы)
Ссылка на задачу: https://www.codewars.com/kata/5914c6ee51f1d39b5600001c
Сложность: 8 kyu
Уже решили (На момент написания статьи): 1 619 из 6 027
Тэги: Основы, учебные пособия
Оригинальное описание задачи:
Learning TypeScript. Basic Types
Overview
In this kata you'll get familiar with TypeScript's basic types.
If you have problems solving this kata please refer to this article: https://www.typescriptlang.org/docs/handbook/basic-types.html
Task
Boolean
- Export
var1Boolean
variable of boolean type with value true
.
Number
- Export
var2Decimal
variable of numeric type with decimal value 13
.
- Export
var3Hex
variable of numeric type with hex value f00d
.
- Export
var4Binary
variable of numeric type with binary value 111111
.
- Export
var5Octal
variable of numeric type with octal value 744
.
String
- Export
var6String
variable of string type with value Hello, world!
.
Array
- Export
var7Array
variable of array type with value [1, 'test', {a: 3}, 4, 5]
.
- Export
var8NumericArray
variable of numeric generic array type with value [1, 2, 3, 4, 5]
.
Tuple
Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.
- Export
var9Tuple
variable of tuple type with value ['key', 12345]
- i.e. it should represent a value as a pair of a string and a number.
Enums
- Export
var10Enum
variable with value Color.Blue
from enum export enum Color {Red = 1, Green = 2, Blue = 4}
.
Any
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any
type.
- Export
var11ArrayOfAny
variable of Array<any>
type with value [1, 'test', {a: 3}, 4, 5]
.
Void
- Export
var12VoidFunction
function that returns void
.
Null and Undefined
- Export
var13Null
variable with type and value null
.
- Export
var14Undefined
variable with type and value undefined
.
Never
- Export
var15NeverFunction
function that returns never
value.
P.S. Solved this kata? Take a look at other katas in "Learning TypeScript" collection.
Пояснение задачи:
В этой задаче мы познакомимся с основными типами данных в TypeScript.
Булевый тип (Boolean)
- Экспортируйте переменную `var1Boolean` булевого типа со значением `true`.
Числовой тип (Number)
- Экспортируйте переменную `var2Decimal` числового типа с десятичным значением `13`.
- Экспортируйте переменную `var3Hex` числового типа с шестнадцатеричным значением `f00d`.
- Экспортируйте переменную `var4Binary` числового типа с двоичным значением `111111`.
- Экспортируйте переменную `var5Octal` числового типа с восьмеричным значением `744`.
Строковый тип (String) - Экспортируйте переменную `var6String` строкового типа со значением `"Hello, world!"`. Массив (Array) - Экспортируйте переменную `var7Array` массива типа с элементами `[1, "test", {a: 3}, 4, 5]`. -Экспортируйте переменную `var8NumericArray` массива числового типа с элементами `[1, 2, 3, 4, 5]`.
Кортеж (Tuple) Кортежи позволяют нам выразить массив, где тип фиксированного числа элементов известен, но не обязательно одинаков.
- Экспортируйте переменную `var9Tuple` кортежа типа с элементами `['key', 12345]` — т.е. она должна представлять пару строки и числа.
Перечисления (Enum)
- Экспортируйте переменную `var10Enum` с значением `Color.Blue` из перечисления `enum Color { Red = 1, Green = 2, Blue = 4 }`.
Любой тип (Any) Иногда требуется описать тип переменной, который мы не знаем на этапе написания программы. Эти значения могут поступать из динамического содержимого, например, от пользователя или сторонней библиотеки.
Задача 2
Платформа: CodeWars
Название задачи: Are there any arrows left? (Остались стрелы?)
Ссылка на задачу: https://www.codewars.com/kata/559f860f8c0d6c7784000119
Сложность: 8 kyu
Уже решили (На момент написания статьи): 6 572 из 26 049
Тэги: Основы
Оригинальное описание задачи:
Check your arrows
You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow.
You need to verify that you have some good ones left, in order to prepare for battle:
anyArrows([{'range': 5}, {'range': 10, 'damaged': True}, {'damaged': True}])
If an arrow in the quiver does not have a damaged status, it means it's new.
The expected result is a boolean, indicating whether you have any good arrows left.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Пояснение задачи:
Задача состоит в том, чтобы проверить, есть ли у вас достаточно хороших стрел для предстоящей битвы.
Для этого нужно проанализировать арбалеты в колчане, где каждый предмет представляет собой стрелу с информацией о её дальности стрельбы.
Если стрела имеет статус "damaged", значит она повреждена и не может быть использована.
Здесь функция `anyArrows` принимает массив объектов, каждый из которых описывает стрелу.
Если хотя бы одна стрела в массиве не помечена как поврежденная (`damaged`), функция должна вернуть `true`, что означает наличие годных стрел.
В противном случае возвращается `false`.
Задача 3
Платформа: CodeWars
Название задачи: Invert The Triangle (Инвертировать треугольник)
Ссылка на задачу: https://www.codewars.com/kata/5a224a15ee1aaef6e100005a
Сложность: 7 kyu
Уже решили (На момент написания статьи): 362 из 1 115
Тэги: Головоломки, основы
Оригинальное описание задачи:
Each time the function is called it should invert the passed triangle. Make upside down the given triangle and invert the chars in the triangle.
if a char = " ", make it = "#"
if a char = "#", make it = " "
#
###
#####
#######
######### // normal
// inverted
# #
## ##
### ###
#### ####
#### ####
### ###
## ##
# #
// normal
######### // inverted
#######
#####
###
#
maketri() is at your disposal.
Пояснение задачи:
Задача состоит в том, чтобы создать функцию `maketri()`, которая каждый раз при вызове переворачивает переданный ей треугольник и инвертирует его содержимое.
Это означает, что если символ в треугольнике — это пробел (` ' '`), он должен стать символом '#' (и наоборот).
Функция должна обрабатывать такие треугольники и возвращать их инвертированные версии.
Задача 4
Платформа: CodeWars
Название задачи: The dropWhile Function (Функция Dropwhile)
Ссылка на задачу: https://www.codewars.com/kata/54f9c37106098647f400080a
Сложность: 7 kyu
Уже решили (На момент написания статьи): 3 459 из 11 598
Тэги: Функциональное программирование, массивы, алгоритмы
Оригинальное описание задачи:
Yet another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to remove the longest prefix of elements such that the predicate is true for each element. We'll call this the dropWhile function. It accepts two arguments. The first is the sequence of values, and the second is the predicate function. The function does not change the value of the original sequence.
def isEven(num):
return num % 2 == 0
arr = [2,4,6,8,1,2,5,4,3,2]
dropWhile(arr, isEven) == [1,2,5,4,3,2] # True
Your task is to implement the dropWhile function. If you've got a span function lying around, this is a one-liner! Alternatively, if you have a takeWhile function on your hands, then combined with the dropWhile function, you can implement the span function in one line. This is the beauty of functional programming: there are a whole host of useful functions, many of which can be implemented in terms of each other.
Пояснение задачи:
Задача заключается в реализации функции `dropWhile`, которая удаляет самую длинную последовательность элементов из начала списка, пока предикат возвращает истинное значение для каждого элемента.
Функция принимает два аргумента: список значений и предикат.
Важно, чтобы функция не изменяла исходный список.
Этот функционал полезен для функционального программирования, где часто используются подобные операции для работы с последовательностями данных.
Задача 5
Платформа: CodeWars
Название задачи: The Enigma Machine - Part 1: The Plugboard (Машина Enigma - Часть 1: Плзард)
Ссылка на задачу: https://www.codewars.com/kata/5523b97ac8f5025c45000900
Сложность: 6 kyu
Уже решили (На момент написания статьи): 2 620 из 43 027
Тэги: Основы, алгоритмы, объектно-ориентированное программирование
Оригинальное описание задачи:
In this series of Kata, we will be implementing a software version of the Enigma Machine.
The Enigma Machine was a message enciphering/deciphering machine used during the Second World War for disguising the content of military communications. Alan Turing - the father of computing - formulated and developed concepts that are the basis of all computers in use today, he did this in response to the vital need to break those military communications. Turing and his colleagues at Bletchley Park are generally recognised as being responsible for shortening WWII by two years and saving an estimated 22 Million lives.
The Enigma Machine consisted of a number of parts: Keyboard for input, rotors and plugboard for enciphering, and lampboard for output.
We will simulate input and output with strings, and build the rotors, plugboard and mechanism that used them in software. As we progress the code will become more complex, so you are advised to attempt them in order.
Step 1: The plugboard
In this Kata, you must implement the plugboard.
Physical Description
The plugboard crosswired the 26 letters of the latin alphabet togther, so that an input into one letter could generate output as another letter. If a wire was not present, then the input letter was unchanged. Each plugboard came with a maximum of 10 wires, so at least six letters were not cross-wired.
For example:
-
If a wire connects A
to B
, then an A
input will generate a B
output and a B
input will generate an A
output.
-
If no wire connects to C
, then only a C
input will generate a C
output.
Note
In the actual usage of the original Enigma Machine, punctuation was encoded as words transmitted in the stream, in our code, anything that is not in the range A-Z will be returned unchanged.
Kata
The Plugboard
class you will implement, will:
- Take a list of wire pairs at construction in the form of a string, with a default behaviour of no wires configured. E.g.
"ABCD"
would wire A
<-> B
and C
<-> D
.
- Validate that the wire pairings are legitimate. Raise an exception if not.
- Implement the
process
method to translate a single character input into an output.
Examples
plugboard = Plugboard("ABCDEFGHIJKLMNOPQRST")
plugboard.process("A") ==> "B"
plugboard.process("B") ==> "A"
plugboard.process("X") ==> "X"
plugboard.process(".") ==> "."
Пояснение задачи:
Задача состоит в реализации программной версии "машины Enigma", которая использовалась во время Второй мировой войны для шифрования военных сообщений.
Машина представляла собой устройство, которое преобразовывало текст, используя набор роторов и плату подключения (plugboard), что делало его сложным для расшифровки.
В этой части мы будем реализовывать "плату подключения" (plugboard).
Плата подключения позволяет связывать пары символов, так что при вводе одного символа может быть получен другой символ.
Если пара не установлена, то символ остается неизменным.
Важно отметить, что в реальной машине, символы, которые не входят в алфавит, такие как знаки пунктуации, остаются без изменений.
Наша реализация должна создать объект `Plugboard`, который будет принимать список пар символов на этапе создания и затем использовать их для преобразования входного символа в выходной.
Таким образом, задача требует от нас реализации класса `Plugboard`, который будет обрабатывать ввод символов через метод `process`, учитывая установленные связи между символами на плате подключения.
Задача 6
Платформа: CodeWars
Название задачи: Canal Management (Управление каналом)
Ссылка на задачу: https://www.codewars.com/kata/61c1ffd793863e002c1e42b5
Сложность: 6 kyu
Уже решили (На момент написания статьи): 294 из 831
Тэги: Алгоритмы
Оригинальное описание задачи:
You work at a lock situated on a very busy canal. Boats have queued up at both sides of the lock and your managers are asking for an update on how long it's going to take for all the boats to go through the lock.
Boats are queuing in order and they must go into the lock in that order. Multiple boats can go into the lock at the same time, however they must not exceed the length of the lock. The lock starts empty, and the timer should finish when the lock is down at empty, and all the boats are through. A boat takes its length in minutes to both enter and exit the lock, e.g. a boat of length 4
will take 4
minutes to enter and 4
minutes to leave the lock.
Notes
- The lock takes
2
minutes to fill and empty each time
- The lock should start and finish at the low end
- No boat will ever be longer than the lock
- The time should be returned in minutes
Example:
low queue = [2, 3, 6, 1]
high queue = [1, 2]
max length = 7
- Starting at low end
- Boats
2
and 3
can fit inside the lock - total time is 5
minutes
- The lock fills up - total time is
7
minutes
- Boats
2
and 3
leave the lock - total time is 12
minutes
- Starting at high end
- Boats
1
and 2
enter the lock - total time is 15
minutes
- The lock empties - total time is
17
minutes
- Boats
1
and 2
leave the lock - total time is 20
minutes
- Starting at low end
- Boats
6
and 1
enter the lock - total time is 27
minutes
- The lock fills up - total time is
29
minutes
- Boats
6
and 1
leave the lock - total time is 36
minutes
- Starting at high end
- The lock empties as it must finish empty - total time is
38
minutes
Пояснение задачи:
Ты работаешь на шлюзе, расположенном на очень загруженном канале.
Лодки выстроились в очередь с обеих сторон шлюза, и твои менеджеры просят тебя предоставить обновление о том, сколько времени потребуется, чтобы все лодки прошли через шлюз.
Лодки стоят в очереди в порядке поступления, и они должны проходить через шлюз в этом порядке.
Несколько лодок могут одновременно находиться в шлюзе, но они не должны превышать его длину.
Шлюз начинается пустым, а таймер должен остановиться, когда шлюз опустеет, и все лодки пройдут через него. Лодка занимает время своей длины как для входа, так и для выхода из шлюза, например, лодка длиной `4` займет `4` минуты для входа и `4` минуты для выхода из шлюза.
Примечания:
Шлюз заполняется и опорожняется за `2` минуты каждый раз
Шлюз должен начинаться и заканчиваться у низкого конца
Ни одна лодка никогда не будет длиннее шлюза
Время должно быть возвращено в минутах
Задача 7
Платформа: CodeWars
Название задачи: Simple Fun #272: Throwing Dice (Простое веселье)
Ссылка на задачу: https://www.codewars.com/kata/591575f6d64db0431c000009
Сложность: 5 kyu
Уже решили (На момент написания статьи): 127 из 658
Тэги: Основы
Оригинальное описание задачи:
Task
Given a fair dice that you can throw an unlimited number of times and a number n
, find the number of ways to throw the dice so that the sum of the dots on its upper surface equals n
.
Input/Output
[input]
integer n
The sum of dots, 1 ≤ n ≤ 50
.
[output]
an integer
The number of ways to throw the dice.
Example
For n = 2
, the output should be 2
.
There are two ways to throw the dice:
1, 1;
2.
For n = 4
, the output should be 8
.
The ways to throw the dice are:
1, 1, 1, 1;
1, 1, 2;
1, 2, 1;
2, 1, 1;
2, 2;
1, 3;
3, 1;
4.
Пояснение задачи:
Эта задача требует найти количество способов сложить сумму `n` с помощью броска справедливого кубика. Поскольку кубик имеет 6 граней, каждая грань соответствует числу от 1 до 6. Сумма, которую нужно получить, равна `n`. Например, если `n = 2`, то возможные комбинации будут: - 1 + 1 - 2 Если `n = 4`, то возможные комбинации: - 1 + 1 + 1 + 1 - 1 + 1 + 2 - 1 + 2 + 1 - 2 + 1 + 1 - 2 + 2 - 1 + 3 - 3 + 1 - 4 Таким образом, общее количество способов равно количеству способов сложить `n` из чисел от 1 до 6.
Задача 8
Платформа: CodeWars
Название задачи: Where did my Ether go? (Куда ушел мой эфир?)
Ссылка на задачу: https://www.codewars.com/kata/59b98874460387687a0000af
Сложность: 5 kyu
Уже решили (На момент написания статьи): 14 из 521
Тэги: Web3, Основы
Оригинальное описание задачи:
Let's bring the Ethereum blockchain to Codewars! There's a simpler Kata available, Retrieve Ether Balance, that you should try first before attempting this one. I suspect this Kata will be a difficult challenge to start from.
This Kata makes use of the JavaScript Ethereum API web3.js, specifically the 1.0 version with documentation found here.
Where did my Ether go?
I've been making many Ether transactions lately, but I forgot to write down all the addresses I've sent Ether to! I could really use a function that I could call to find all the addresses I've sent Ether to.
Let's create this function findMyEther
. It should take in a hexidecimal Ethereum address
and return a promise which will resolve to an array of addresses that the address has sent ether to.
Пояснение задачи:
Задача состоит в создании функции `findMyEther`, которая принимает адрес Ethereum в виде шестнадцатеричной строки и возвращает обещание (promise), разрешающееся в массив адресов, которые этот адрес отправлял Ether. Для выполнения этой задачи мы будем использовать библиотеку `web3.js`, а именно версию 1.0, предоставляющую необходимые методы для взаимодействия с блокчейном Ethereum.
Заключение:
Платформа: CodeWars
Название задачи: Learning TypeScript. Basic Types (Обучающий типа. Основные типы)
Ссылка на задачу: https://www.codewars.com/kata/5914c6ee51f1d39b5600001c
Сложность: 8 kyu
Уже решили (На момент написания статьи): 1 619 из 6 027
Тэги: Основы, учебные пособия
Оригинальное описание задачи:
Learning TypeScript. Basic Types
Overview
In this kata you'll get familiar with TypeScript's basic types.
If you have problems solving this kata please refer to this article: https://www.typescriptlang.org/docs/handbook/basic-types.htmlTask
Boolean
- Export
var1Boolean
variable of boolean type with valuetrue
.Number
- Export
var2Decimal
variable of numeric type with decimal value13
.- Export
var3Hex
variable of numeric type with hex valuef00d
.- Export
var4Binary
variable of numeric type with binary value111111
.- Export
var5Octal
variable of numeric type with octal value744
.String
- Export
var6String
variable of string type with valueHello, world!
.Array
- Export
var7Array
variable of array type with value[1, 'test', {a: 3}, 4, 5]
.- Export
var8NumericArray
variable of numeric generic array type with value[1, 2, 3, 4, 5]
.Tuple
Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.
- Export
var9Tuple
variable of tuple type with value['key', 12345]
- i.e. it should represent a value as a pair of a string and a number.Enums
- Export
var10Enum
variable with valueColor.Blue
from enumexport enum Color {Red = 1, Green = 2, Blue = 4}
.Any
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the
any
type.
- Export
var11ArrayOfAny
variable ofArray<any>
type with value[1, 'test', {a: 3}, 4, 5]
.Void
- Export
var12VoidFunction
function that returnsvoid
.Null and Undefined
- Export
var13Null
variable with type and valuenull
.- Export
var14Undefined
variable with type and valueundefined
.Never
- Export
var15NeverFunction
function that returnsnever
value.P.S. Solved this kata? Take a look at other katas in "Learning TypeScript" collection.
Пояснение задачи:
В этой задаче мы познакомимся с основными типами данных в TypeScript.
Булевый тип (Boolean)
- Экспортируйте переменную `var1Boolean` булевого типа со значением `true`.
Числовой тип (Number)
- Экспортируйте переменную `var2Decimal` числового типа с десятичным значением `13`.
- Экспортируйте переменную `var3Hex` числового типа с шестнадцатеричным значением `f00d`.
- Экспортируйте переменную `var4Binary` числового типа с двоичным значением `111111`.
- Экспортируйте переменную `var5Octal` числового типа с восьмеричным значением `744`.
Строковый тип (String) - Экспортируйте переменную `var6String` строкового типа со значением `"Hello, world!"`. Массив (Array) - Экспортируйте переменную `var7Array` массива типа с элементами `[1, "test", {a: 3}, 4, 5]`. -Экспортируйте переменную `var8NumericArray` массива числового типа с элементами `[1, 2, 3, 4, 5]`.
Кортеж (Tuple) Кортежи позволяют нам выразить массив, где тип фиксированного числа элементов известен, но не обязательно одинаков.
- Экспортируйте переменную `var9Tuple` кортежа типа с элементами `['key', 12345]` — т.е. она должна представлять пару строки и числа.
Перечисления (Enum)
- Экспортируйте переменную `var10Enum` с значением `Color.Blue` из перечисления `enum Color { Red = 1, Green = 2, Blue = 4 }`.
Любой тип (Any) Иногда требуется описать тип переменной, который мы не знаем на этапе написания программы. Эти значения могут поступать из динамического содержимого, например, от пользователя или сторонней библиотеки.
Платформа: CodeWars
Название задачи: Are there any arrows left? (Остались стрелы?)
Ссылка на задачу: https://www.codewars.com/kata/559f860f8c0d6c7784000119
Сложность: 8 kyu
Уже решили (На момент написания статьи): 6 572 из 26 049
Тэги: Основы
Оригинальное описание задачи:
Check your arrows
You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow.You need to verify that you have some good ones left, in order to prepare for battle:
anyArrows([{'range': 5}, {'range': 10, 'damaged': True}, {'damaged': True}])
If an arrow in the quiver does not have a damaged status, it means it's new.
The expected result is a boolean, indicating whether you have any good arrows left.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Пояснение задачи:
Задача состоит в том, чтобы проверить, есть ли у вас достаточно хороших стрел для предстоящей битвы.
Для этого нужно проанализировать арбалеты в колчане, где каждый предмет представляет собой стрелу с информацией о её дальности стрельбы.
Если стрела имеет статус "damaged", значит она повреждена и не может быть использована.
Здесь функция `anyArrows` принимает массив объектов, каждый из которых описывает стрелу.
Если хотя бы одна стрела в массиве не помечена как поврежденная (`damaged`), функция должна вернуть `true`, что означает наличие годных стрел.
В противном случае возвращается `false`.
Платформа: CodeWars
Название задачи: Invert The Triangle (Инвертировать треугольник)
Ссылка на задачу: https://www.codewars.com/kata/5a224a15ee1aaef6e100005a
Сложность: 7 kyu
Уже решили (На момент написания статьи): 362 из 1 115
Тэги: Головоломки, основы
Оригинальное описание задачи:
Each time the function is called it should invert the passed triangle. Make upside down the given triangle and invert the chars in the triangle.
if a char = " ", make it = "#" if a char = "#", make it = " "
# ### ##### ####### ######### // normal // inverted # # ## ## ### ### #### #### #### #### ### ### ## ## # # // normal ######### // inverted ####### ##### ### #
maketri() is at your disposal.
Пояснение задачи:
Задача состоит в том, чтобы создать функцию `maketri()`, которая каждый раз при вызове переворачивает переданный ей треугольник и инвертирует его содержимое.
Это означает, что если символ в треугольнике — это пробел (` ' '`), он должен стать символом '#' (и наоборот).
Функция должна обрабатывать такие треугольники и возвращать их инвертированные версии.
Платформа: CodeWars
Название задачи: The dropWhile Function (Функция Dropwhile)
Ссылка на задачу: https://www.codewars.com/kata/54f9c37106098647f400080a
Сложность: 7 kyu
Уже решили (На момент написания статьи): 3 459 из 11 598
Тэги: Функциональное программирование, массивы, алгоритмы
Оригинальное описание задачи:
Yet another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to remove the longest prefix of elements such that the predicate is true for each element. We'll call this the dropWhile function. It accepts two arguments. The first is the sequence of values, and the second is the predicate function. The function does not change the value of the original sequence.
def isEven(num): return num % 2 == 0 arr = [2,4,6,8,1,2,5,4,3,2] dropWhile(arr, isEven) == [1,2,5,4,3,2] # True
Your task is to implement the dropWhile function. If you've got a span function lying around, this is a one-liner! Alternatively, if you have a takeWhile function on your hands, then combined with the dropWhile function, you can implement the span function in one line. This is the beauty of functional programming: there are a whole host of useful functions, many of which can be implemented in terms of each other.
Пояснение задачи:
Задача заключается в реализации функции `dropWhile`, которая удаляет самую длинную последовательность элементов из начала списка, пока предикат возвращает истинное значение для каждого элемента.
Функция принимает два аргумента: список значений и предикат.
Важно, чтобы функция не изменяла исходный список.
Этот функционал полезен для функционального программирования, где часто используются подобные операции для работы с последовательностями данных.
Платформа: CodeWars
Название задачи: The Enigma Machine - Part 1: The Plugboard (Машина Enigma - Часть 1: Плзард)
Ссылка на задачу: https://www.codewars.com/kata/5523b97ac8f5025c45000900
Сложность: 6 kyu
Уже решили (На момент написания статьи): 2 620 из 43 027
Тэги: Основы, алгоритмы, объектно-ориентированное программирование
Оригинальное описание задачи:
In this series of Kata, we will be implementing a software version of the Enigma Machine.
The Enigma Machine was a message enciphering/deciphering machine used during the Second World War for disguising the content of military communications. Alan Turing - the father of computing - formulated and developed concepts that are the basis of all computers in use today, he did this in response to the vital need to break those military communications. Turing and his colleagues at Bletchley Park are generally recognised as being responsible for shortening WWII by two years and saving an estimated 22 Million lives.
The Enigma Machine consisted of a number of parts: Keyboard for input, rotors and plugboard for enciphering, and lampboard for output.
We will simulate input and output with strings, and build the rotors, plugboard and mechanism that used them in software. As we progress the code will become more complex, so you are advised to attempt them in order.
Step 1: The plugboard
In this Kata, you must implement the plugboard.
Physical Description
The plugboard crosswired the 26 letters of the latin alphabet togther, so that an input into one letter could generate output as another letter. If a wire was not present, then the input letter was unchanged. Each plugboard came with a maximum of 10 wires, so at least six letters were not cross-wired.
For example:
If a wire connects
A
toB
, then anA
input will generate aB
output and aB
input will generate anA
output.If no wire connects to
C
, then only aC
input will generate aC
output.Note
In the actual usage of the original Enigma Machine, punctuation was encoded as words transmitted in the stream, in our code, anything that is not in the range A-Z will be returned unchanged.
Kata
The
Plugboard
class you will implement, will:
- Take a list of wire pairs at construction in the form of a string, with a default behaviour of no wires configured. E.g.
"ABCD"
would wireA
<->B
andC
<->D
.- Validate that the wire pairings are legitimate. Raise an exception if not.
- Implement the
process
method to translate a single character input into an output.
Examples
plugboard = Plugboard("ABCDEFGHIJKLMNOPQRST") plugboard.process("A") ==> "B" plugboard.process("B") ==> "A" plugboard.process("X") ==> "X" plugboard.process(".") ==> "."
Пояснение задачи:
Задача состоит в реализации программной версии "машины Enigma", которая использовалась во время Второй мировой войны для шифрования военных сообщений.
Машина представляла собой устройство, которое преобразовывало текст, используя набор роторов и плату подключения (plugboard), что делало его сложным для расшифровки.
В этой части мы будем реализовывать "плату подключения" (plugboard).
Плата подключения позволяет связывать пары символов, так что при вводе одного символа может быть получен другой символ.
Если пара не установлена, то символ остается неизменным.
Важно отметить, что в реальной машине, символы, которые не входят в алфавит, такие как знаки пунктуации, остаются без изменений.
Наша реализация должна создать объект `Plugboard`, который будет принимать список пар символов на этапе создания и затем использовать их для преобразования входного символа в выходной.
Таким образом, задача требует от нас реализации класса `Plugboard`, который будет обрабатывать ввод символов через метод `process`, учитывая установленные связи между символами на плате подключения.
Платформа: CodeWars
Название задачи: Canal Management (Управление каналом)
Ссылка на задачу: https://www.codewars.com/kata/61c1ffd793863e002c1e42b5
Сложность: 6 kyu
Уже решили (На момент написания статьи): 294 из 831
Тэги: Алгоритмы
Оригинальное описание задачи:
You work at a lock situated on a very busy canal. Boats have queued up at both sides of the lock and your managers are asking for an update on how long it's going to take for all the boats to go through the lock.
Boats are queuing in order and they must go into the lock in that order. Multiple boats can go into the lock at the same time, however they must not exceed the length of the lock. The lock starts empty, and the timer should finish when the lock is down at empty, and all the boats are through. A boat takes its length in minutes to both enter and exit the lock, e.g. a boat of length
4
will take4
minutes to enter and4
minutes to leave the lock.Notes
- The lock takes
2
minutes to fill and empty each time- The lock should start and finish at the low end
- No boat will ever be longer than the lock
- The time should be returned in minutes
Example:
low queue = [2, 3, 6, 1] high queue = [1, 2] max length = 7
- Starting at low end
- Boats
2
and3
can fit inside the lock - total time is5
minutes- The lock fills up - total time is
7
minutes- Boats
2
and3
leave the lock - total time is12
minutes- Starting at high end
- Boats
1
and2
enter the lock - total time is15
minutes- The lock empties - total time is
17
minutes- Boats
1
and2
leave the lock - total time is20
minutes- Starting at low end
- Boats
6
and1
enter the lock - total time is27
minutes- The lock fills up - total time is
29
minutes- Boats
6
and1
leave the lock - total time is36
minutes- Starting at high end
- The lock empties as it must finish empty - total time is
38
minutes
Пояснение задачи:
Ты работаешь на шлюзе, расположенном на очень загруженном канале.
Лодки выстроились в очередь с обеих сторон шлюза, и твои менеджеры просят тебя предоставить обновление о том, сколько времени потребуется, чтобы все лодки прошли через шлюз.
Лодки стоят в очереди в порядке поступления, и они должны проходить через шлюз в этом порядке.
Несколько лодок могут одновременно находиться в шлюзе, но они не должны превышать его длину.
Шлюз начинается пустым, а таймер должен остановиться, когда шлюз опустеет, и все лодки пройдут через него. Лодка занимает время своей длины как для входа, так и для выхода из шлюза, например, лодка длиной `4` займет `4` минуты для входа и `4` минуты для выхода из шлюза.
Примечания:
Шлюз заполняется и опорожняется за `2` минуты каждый раз
Шлюз должен начинаться и заканчиваться у низкого конца
Ни одна лодка никогда не будет длиннее шлюза
Время должно быть возвращено в минутах
Платформа: CodeWars
Название задачи: Simple Fun #272: Throwing Dice (Простое веселье)
Ссылка на задачу: https://www.codewars.com/kata/591575f6d64db0431c000009
Сложность: 5 kyu
Уже решили (На момент написания статьи): 127 из 658
Тэги: Основы
Оригинальное описание задачи:
Task
Given a fair dice that you can throw an unlimited number of times and a number
n
, find the number of ways to throw the dice so that the sum of the dots on its upper surface equalsn
.Input/Output
[input]
integern
The sum of dots,
1 ≤ n ≤ 50
.
[output]
an integerThe number of ways to throw the dice.
Example
For
n = 2
, the output should be2
.There are two ways to throw the dice:
1, 1; 2.
For
n = 4
, the output should be8
.The ways to throw the dice are:
1, 1, 1, 1; 1, 1, 2; 1, 2, 1; 2, 1, 1; 2, 2; 1, 3; 3, 1; 4.
Пояснение задачи:
Эта задача требует найти количество способов сложить сумму `n` с помощью броска справедливого кубика. Поскольку кубик имеет 6 граней, каждая грань соответствует числу от 1 до 6. Сумма, которую нужно получить, равна `n`. Например, если `n = 2`, то возможные комбинации будут: - 1 + 1 - 2 Если `n = 4`, то возможные комбинации: - 1 + 1 + 1 + 1 - 1 + 1 + 2 - 1 + 2 + 1 - 2 + 1 + 1 - 2 + 2 - 1 + 3 - 3 + 1 - 4 Таким образом, общее количество способов равно количеству способов сложить `n` из чисел от 1 до 6.
Платформа: CodeWars
Название задачи: Where did my Ether go? (Куда ушел мой эфир?)
Ссылка на задачу: https://www.codewars.com/kata/59b98874460387687a0000af
Сложность: 5 kyu
Уже решили (На момент написания статьи): 14 из 521
Тэги: Web3, Основы
Оригинальное описание задачи:
Let's bring the Ethereum blockchain to Codewars! There's a simpler Kata available, Retrieve Ether Balance, that you should try first before attempting this one. I suspect this Kata will be a difficult challenge to start from.
This Kata makes use of the JavaScript Ethereum API web3.js, specifically the 1.0 version with documentation found here.
Where did my Ether go?
I've been making many Ether transactions lately, but I forgot to write down all the addresses I've sent Ether to! I could really use a function that I could call to find all the addresses I've sent Ether to.
Let's create this function
findMyEther
. It should take in a hexidecimal Ethereumaddress
and return a promise which will resolve to an array of addresses that the address has sent ether to.
Пояснение задачи:
Задача состоит в создании функции `findMyEther`, которая принимает адрес Ethereum в виде шестнадцатеричной строки и возвращает обещание (promise), разрешающееся в массив адресов, которые этот адрес отправлял Ether. Для выполнения этой задачи мы будем использовать библиотеку `web3.js`, а именно версию 1.0, предоставляющую необходимые методы для взаимодействия с блокчейном Ethereum.
На этом я заканчиваю. Надеюсь, вам было интересно. Спасибо за уделенное время. Если у вас есть вопросы или пожелания, не стесняйтесь задавать их в комментариях. До новых встреч в следующих статьях, где мы продолжим решать интересные задачи!