Приветствую всех любителей программирования на новой статье с подборкой интересных задач для тренировки навыков решения алгоритмических задач. В этой части я собрал разнообразные задания из разных источников, чтобы каждый мог испытать свои силы в этой захватывающей области!
Цель статьи — не только усовершенствовать практику применения различных алгоритмов, но и поддерживать интерес к написанию кода, а также добавить немного веселья в процесс.
Что было раньше:
В предыдущей части мы решили:
- Heads and Legs (Головы и ноги)
- Stringy Strings (Строчные строки)
- Recurrence by Recursion (Повторение с помощью рекурсии)
- Power of 4 (Степень четырёх)
- Best Stock Profit in Single Sale (Лучшая прибыль от продажи акций за одну продажу)
- Arrays of cats and dogs (Массив кошек и собак)
- Simple Fun #362: Who Is The Hero? II (Простая забава #362: Кто Герой? ii)
- A Scandal in Bohemia (Скандал в Богемии)
Решение новых задач:
Задача 1
Платформа: CodeWars
Название задачи: !a == a ?! (! a == a?!)
Ссылка на задачу: https://www.codewars.com/kata/59f9796cffe75f9299000025
Сложность: 8 kyu
Уже решили (На момент написания статьи): 3028 из 12161
Тэги: Основы, языковые особенности
Оригинальное описание задачи:
You task to pass only this tests : * ``` a == false ``` * ``` !a == false ``` * ``` a == !a ```
Пояснение задачи:
Эти тесты проверяют логику значения переменной `a`. Первый тест проверяет, что `a` равно `false`, второй – что оно не равно `false`, а третий – что `a` равно `!a`, то есть инвертированному значению `a`.
Задача 2
Платформа: CodeWars
Название задачи: Counting Characters (Подсчет персонажей)
Ссылка на задачу: https://www.codewars.com/kata/55f1b763dd670651620000ce
Сложность: 8 kyu
Уже решили (На момент написания статьи): 1265 из 2330
Тэги: Строки, основы
Оригинальное описание задачи:
Define a method named `countCharOccurrences` or `count_char_occurrences` that accepts a string and a char as inputs and returns the number of times the char occurs in the string as an int.
Пояснение задачи:
Необходимо определить метод `countCharOccurrences` или `count_char_occurrences`, который принимает строку и символ в качестве аргументов и возвращает количество вхождений символа в строке в виде целого числа.
Задача 3
Платформа: CodeWars
Название задачи: New season, new league (Новый сезон, новая лига)
Ссылка на задачу: https://www.codewars.com/kata/58de08d376f875dbb40000f1
Сложность: 7 kyu
Уже решили (На момент написания статьи): 921 из 3057
Тэги: Алгоритмы
Оригинальное описание задачи:
The new football league season is coming and the Football Association need some help resetting the league standings.
Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up.
It has been decided that team who finished first last season will begin the next season in first place.
Regardless of what letter their club begins with. e.g. if Manchester City were in first place last year, they will begin the season in position one.
All other teams should be in alphabetical order.
The teams will be fed in as an object ({}).
The key will be will be their position from last season and the value is the club's name e.g. Arsenal.
The output should be an object ({}) with the key as the club's starting position for the new season and the value should be club's name e.g. Arsenal.
For example.
If in the previous season the standings were: 1:'Leeds United' 2:'Liverpool' 3:'Manchester City' 4:'Coventry' 5:'Arsenal'
Then the new season standings should 1:'Leeds United' (first last season) 2:'Arsenal' (alphabetical) 3:'Coventry' (alphabetical) 4:'Liverpool' (alphabetical) 5:'Manchester City' (alphabetical)
Пояснение задачи:
Задача состоит в том, чтобы создать функцию, которая поможет пересчитать таблицу лиги после нового футбольного сезона. Обычно начальные позиции в лиге определяются в алфавитном порядке от A до Z, но в этом году Футбольная ассоциация решила изменить порядок.
Команда, занявшая первое место в прошлом сезоне, начнёт новый сезон на первой позиции, независимо от буквы, с которой начинается название их клуба.
Остальные команды должны быть расставлены в алфавитном порядке.
В программе команды будут представлены в виде объекта {}.
Ключ будет представлять позицию команды в предыдущем сезоне, а значение — название клуба.
Например, если в прошлом сезоне таблица выглядела следующим образом:
1: 'Leeds United' 2: 'Liverpool' 3: 'Manchester City' 4: 'Coventry' 5: 'Arsenal'
Тогда новая таблица позиций должна выглядеть так: 1: 'Leeds United' (заняла первое место в прошлом сезоне) 2: 'Arsenal' (в алфавитном порядке) 3: 'Coventry' (в алфавитном порядке) 4: 'Liverpool' (в алфавитном порядке) 5: 'Manchester City' (в алфавитном порядке)
Задача 4
Платформа: CodeWars
Название задачи: Help the farmer to count rabbits, chickens and cows (Помогите фермеру посчитать кроликов, цыплят и коров)
Ссылка на задачу: https://www.codewars.com/kata/5a02037ac374cbab41000089
Сложность: 7 kyu
Уже решили (На момент написания статьи): 957 из 2295
Тэги: Основы, алгоритмы, математика
Оригинальное описание задачи:
Farmer Bob has a big farm where he grows chickens, rabbits, and cows.
It is very difficult to count the number of animals for each type manually, so he decided to buy a system to do it.
However, he bought a cheap system that can only count the total number of heads, legs, and horns of the animals on the farm.
Can you help Bob figure out how many chickens, rabbits, and cows he has?
All chickens have 2 legs, 1 head and no horns; all rabbits have 4 legs, 1 head and no horns; all cows have 4 legs, 1 head and 2 horns. Your task is to write a function "get_animals_count(legs_number, heads_number, horns_number)"
Parameters "legs_number, heads_number, horns_number" are integers, all tests have valid input.
Example:
get_animals_count(34, 11, 6); # Should return {"rabbits" : 3, "chickens" : 5, "cows" : 3}
get_animals_count(154, 42, 10); # Should return {"rabbits" : 30, "chickens" : 7, "cows" : 5}
Пояснение задачи:
Задача состоит в том, чтобы создать функцию, которая считывает количество ног, голов и рогов у животных на ферме Боба и определяет, сколько у него кур, кроликов и коров.
Функция принимает три параметра: количество ног, голов и рогов.
Эти параметры соответствуют количеству ног у кролика, головы у курицы и рогов у коровы.
Например, если на вход подаются следующие значения:
- Количество ног: 34 - Количество голов: 11 - Количество рогов: 6
То функция должна вернуть следующее: - Кур: 5 - Кроликов: 3 - Коров: 3
Основная цель — правильно интерпретировать данные о количестве ног, голов и рогов и преобразовать их в количество кур, кроликов и коров соответственно.
Задача 5
Платформа: CodeWars
Название задачи: Slay Achilles! (Убей Ахиллес!)
Ссылка на задачу: https://www.codewars.com/kata/5708c90cd531cdfecf00147c
Сложность: 6 kyu
Уже решили (На момент написания статьи): 79 из 752
Тэги: Основы
Оригинальное описание задачи:
A horde of Grecian warriors is storming towards you. Among them is Achilles. Pick him off and slay him. Your city depends on it. Your function will be passed an array of positive integers containing an Achilles number. An Achilles number is "powerful" but not a perfect power, meaning every term of its prime factorization is at least squared, but it cannot be represented as the power of a single number (i.e. it cannot be mk, but may be of the form mx · ny where `x!=y`, etc.).
For example:
- 99 = 32 · 11 (not powerful; not Achilles)
- 100 = 102 (perfect power; not Achilles)
- 108 = 2233 (Achilles!)
Remove Achilles from the array and return the array. Note: it's guaranteed that the army does not exceed 1000 numbers, and each number can't exceed 1010 as well.
Пояснение задачи:
Задача требует найти и удалить число, которое является "Ахиллесовым числом" из массива положительных целых чисел. Ахиллесово число — это число, которое не является совершенной степенью, но каждая его простая компонента возводится в квадрат.
Пример: - Число 99 не является Ахиллесовым, так как оно может быть представлено как 3²*11.
- Число 100 также не подходит, поскольку оно является совершенной степенью (10²).
- Число 108 является Ахиллесовым, так как его разложение на простые множители 2233 показывает, что каждый простой множитель возведен в квадрат.
Задача 6
Платформа: CodeWars
Название задачи: Multiples of 3 and 5 redux (Кратные 3 и 5 redux)
Ссылка на задачу: https://www.codewars.com/kata/54bb6ee72c4715684d0008f9
Сложность: 6 kyu
Уже решили (На момент написания статьи): 1760 из 11806
Тэги: Алгоритмы, математика
Оригинальное описание задачи:
The galactic games have begun! It's the galactic games!
Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one).
However, there's also the traditional marathon run.
Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track.
Committees being committees, they've come up with the following rule: > A sensor should be placed every 3 and 5 meters from the start, e.g. > at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m….
Since you're responsible for the track, you need to buy those sensors.
Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead.
Task
Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000).
Examples
solution (10) => 23 = 3 + 5 + 6 + 9
solution (20) => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
Пояснение задачи:
В данном случае нам нужно найти сумму всех чисел, которые делятся на 3 или на 5, но меньше определенного числа.
Это типичная задача для программистов, которая часто встречается в реальных проектах.
Для решения этой задачи необходимо пройти по каждому числу в диапазоне до указанного предела и проверить, делится ли оно на 3 или на 5 без остатка. Если да, то такое число нужно включить в итоговую сумму.
Задача 7
Платформа: CodeWars
Название задачи: Text message codec (Кодек текстовых сообщений)
Ссылка на задачу: https://www.codewars.com/kata/67a9f62277df928f6dbcf97d
Сложность: 5 kyu
Уже решили (На момент написания статьи): 25 из 101
Тэги: Алгоритмы
Оригинальное описание задачи:
With the advent of predictive text, it's surprising how few keypresses are needed to produce a short text message. In this kata we code a simple implementation of predictive text and use it to encode and decode text messages. For simplicity in this kata:
- All messages to be encoded contain only lower-case alphabetic characters and spaces (no digits, punctuation, line-feeds, etc.).
- Words are separated by single spaces.
Our predictive text algorithm uses a preloaded list, dictionary
, of approximately 1200 frequently used English words, all in lower case, no hyphens or apostrophes. It starts like this:
dictionary = ["the","a","is","of","and","to","in","you","that","it","he","for","was","on", ...]
The algorithm is described below by imagining how a user would press the phone keypad to enter their message:
- The user enters their message one word at a time.
- Words which are not in the dictionary must be keyed in full (including a final space character unless the end of the message has been reached).
- After each keypress, the algorithm offers the user a selection of up to three dictionary words, any of which may be selected by user keying
1
, 2
, or 3
.
- At the start of the message, or after a word has been completed, the selection of words is the first three words from the dictionary:
"the"
"a"
"is"
.
- At any other point during the encode/decode process, the selection of words is the first three words from the dictionary which match with the characters already entered in the current word.
- Whenever the user can see that the complete current word is displayed in the selection of words, the user selects the word by entering
1
, 2
or 3
. Otherwise the user continues entering the current word until it appears in the selection or until the word is completed by the user entering a space character.
Encode Example:
Encode the message "that was incredibly simple"
original message | word selection | encoded message
-----------------------------|---------------------------------------|-------------------------
"" | "the" "a" "is" | ""
"t" | "the" "to" "that" | "t"
SELECT THIRD WORD ---------------------------------^^^^
"that " | "the" "a" "is" | "t3"
"that w" | "was" "with" "what" | "t3w"
SELECT FIRST WORD -------^^^
"that was " | "the" "a" "is" | "t3w1"
"that was i" | "is" "in" "it" | "t3w1i"
"that was in" | "in" "into" "inside" | "t3w1in"
"that was inc" | "include" "inch" "increase" | "t3w1inc"
"that was incr" | "increase" "incredible" "" | "t3w1incr"
"that was incre" | "incredible" "" "" | "t3w1incre"
"that was incred" | "incredible" "" "" | "t3w1incred"
"that was incredi" | "incredible" "" "" | "t3w1incredi"
"that was incredib" | "incredible" "" "" | "t3w1incredib"
"that was incredibl" | "incredible" "" "" | "t3w1incredibl"
"that was incredibly" | "" "" "" | "t3w1incredibly"
"that was incredibly " | "the" "a" "is" | "t3w1incredibly "
"that was incredibly s" | "said" "she" "some" | "t3w1incredibly s"
"that was incredibly si" | "side" "since" "six" | "t3w1incredibly si"
"that was incredibly sim" | "simple" "similar" "" | "t3w1incredibly sim"
SELECT FIRST WORD -------^^^
"that was incredibly simple" | "the" "a" "is" | "t3w1incredibly sim1"
Encoded message: "t3w1incredibly sim1"
Decoding
The process for decoding a valid encoded message is almost the same as the encode process. Simply imagine the user entering the encoded message on their phone:
- As the user enters the characters of the encoded message, the characters are copied to the ddecoded message and the word selection is presented.
- Whenever the user enters
1
, 2
or 3
the current word of the decoded message is replaced by the selected word.
Decode Example:
Encode the message "t3w1simply incr2"
encoded message | word selection | decoded message
-------------------------|-------------------------------------|--------------------------------
"" | "the" "a" "is" | ""
"t" | "the" "to" "that" | "t"
"t3" | "the" "a" "is" | "that "
"t3w" | "was" "with" "what" | "that w"
"t3w1" | "the" "a" "is" | "that was "
"t3w1s" | "said" "she" "some" | "that was s"
"t3w1si" | "side" "since" "six" | "that was si"
"t3w1sim" | "simple" "similar" "" | "that was sim"
"t3w1simp" | "simple" "" "" | "that was simp"
"t3w1simpl" | "simple" "" "" | "that was simpl"
"t3w1simply" | "" "" "" | "that was simply"
"t3w1simply " | "the" "a" "is" | "that was simply "
"t3w1simply i" | "is" "in" "it" | "that was simply i"
"t3w1simply in" | "in" "into" "inside" | "that was simply in"
"t3w1simply inc" | "include" "inch" "increase" | "that was simply inc"
"t3w1simply incr" | "increase" "incredible" "" | "that was simply incr"
"t3w1simply incr2" | "the" "a" "is" | "that was simply incredible"
Decoded message: "that was simply incredible"
The task:
Write the functions encode
and decode
as follows:
encode
takes a lower-case string (of alphabetic words separated by spaces) and returns a lower-case string (including spaces and digits) encoded as described above.
decode
takes a lower-case string (of alphabetic characters, digits and spaces) and returns a lower-case string of lower-case alphabetic words, separated by spaces, decoded as described above.
All inputs will be valid.
Message size: between 2
and 50
words
Word size: between 1
and 20
characters
Пояснение задачи:
Задача заключается в реализации алгоритма предсказывающего текста, который позволяет кодировать и декодировать текстовые сообщения с использованием предварительно загруженного словаря из приблизительно 1200 наиболее употребляемых английских слов. Этот словарь всегда доступен и помогает ускорить ввод сообщений.
Принцип работы:
Пользователь вводит сообщение построчно.
Слова, отсутствующие в словаре, вводятся вручную (включая завершающий пробел, если это не конец сообщения).
После каждого нажатия клавиши алгоритм предлагает пользователю выбор из максимум трех слов из словаря, совпадающих с введенным фрагментом.
Пользователь может выбрать одно из предложенных слов, нажимая клавишу 1, 2 или 3.
В начале сообщения или после завершения предыдущего слова предлагаются первые три слова из словаря.
Если текущее слово совпадает с предложением, пользователь нажимает соответствующую клавишу (1, 2 или 3), и слово принимается.
Иначе ввод продолжается до появления полного совпадения или достижения конца слова.
Примеры кодирования и декодирования описаны выше
Задача 8
Платформа: CodeWars
Название задачи: Pick peaks (Выберите пики)
Ссылка на задачу: https://www.codewars.com/kata/5279f6fe5ab7f447890006a7
Сложность: 5 kyu
Уже решили (На момент написания статьи): 29161 из 243274
Тэги: Массивы, алгоритмы
Оригинальное описание задачи:
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
For example, the array arr = [0, 1, 2, 5, 1, 0]
has a peak at position 3
with a value of 5
(since arr[3]
equals 5
).
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}
.
Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])
should return {pos: [3, 7], peaks: [6, 3]}
(or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! [1, 2, 2, 2, 1]
has a peak while [1, 2, 2, 2, 3]
and [1, 2, 2, 2, 2]
do not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1])
returns {pos: [1], peaks: [2]}
(or equivalent in other languages)
Have fun!
Заключение:
Платформа: CodeWars
Название задачи: !a == a ?! (! a == a?!)
Ссылка на задачу: https://www.codewars.com/kata/59f9796cffe75f9299000025
Сложность: 8 kyu
Уже решили (На момент написания статьи): 3028 из 12161
Тэги: Основы, языковые особенности
Оригинальное описание задачи:
You task to pass only this tests : * ``` a == false ``` * ``` !a == false ``` * ``` a == !a ```
Пояснение задачи:
Эти тесты проверяют логику значения переменной `a`. Первый тест проверяет, что `a` равно `false`, второй – что оно не равно `false`, а третий – что `a` равно `!a`, то есть инвертированному значению `a`.
Платформа: CodeWars
Название задачи: Counting Characters (Подсчет персонажей)
Ссылка на задачу: https://www.codewars.com/kata/55f1b763dd670651620000ce
Сложность: 8 kyu
Уже решили (На момент написания статьи): 1265 из 2330
Тэги: Строки, основы
Оригинальное описание задачи:
Define a method named `countCharOccurrences` or `count_char_occurrences` that accepts a string and a char as inputs and returns the number of times the char occurs in the string as an int.
Пояснение задачи:
Необходимо определить метод `countCharOccurrences` или `count_char_occurrences`, который принимает строку и символ в качестве аргументов и возвращает количество вхождений символа в строке в виде целого числа.
Платформа: CodeWars
Название задачи: New season, new league (Новый сезон, новая лига)
Ссылка на задачу: https://www.codewars.com/kata/58de08d376f875dbb40000f1
Сложность: 7 kyu
Уже решили (На момент написания статьи): 921 из 3057
Тэги: Алгоритмы
Оригинальное описание задачи:
The new football league season is coming and the Football Association need some help resetting the league standings.
Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up.
It has been decided that team who finished first last season will begin the next season in first place.
Regardless of what letter their club begins with. e.g. if Manchester City were in first place last year, they will begin the season in position one.
All other teams should be in alphabetical order.
The teams will be fed in as an object ({}).
The key will be will be their position from last season and the value is the club's name e.g. Arsenal.
The output should be an object ({}) with the key as the club's starting position for the new season and the value should be club's name e.g. Arsenal.
For example.
If in the previous season the standings were: 1:'Leeds United' 2:'Liverpool' 3:'Manchester City' 4:'Coventry' 5:'Arsenal'
Then the new season standings should 1:'Leeds United' (first last season) 2:'Arsenal' (alphabetical) 3:'Coventry' (alphabetical) 4:'Liverpool' (alphabetical) 5:'Manchester City' (alphabetical)
Пояснение задачи:
Задача состоит в том, чтобы создать функцию, которая поможет пересчитать таблицу лиги после нового футбольного сезона. Обычно начальные позиции в лиге определяются в алфавитном порядке от A до Z, но в этом году Футбольная ассоциация решила изменить порядок.
Команда, занявшая первое место в прошлом сезоне, начнёт новый сезон на первой позиции, независимо от буквы, с которой начинается название их клуба.
Остальные команды должны быть расставлены в алфавитном порядке.
В программе команды будут представлены в виде объекта {}.
Ключ будет представлять позицию команды в предыдущем сезоне, а значение — название клуба.
Например, если в прошлом сезоне таблица выглядела следующим образом:
1: 'Leeds United' 2: 'Liverpool' 3: 'Manchester City' 4: 'Coventry' 5: 'Arsenal'
Тогда новая таблица позиций должна выглядеть так: 1: 'Leeds United' (заняла первое место в прошлом сезоне) 2: 'Arsenal' (в алфавитном порядке) 3: 'Coventry' (в алфавитном порядке) 4: 'Liverpool' (в алфавитном порядке) 5: 'Manchester City' (в алфавитном порядке)
Платформа: CodeWars
Название задачи: Help the farmer to count rabbits, chickens and cows (Помогите фермеру посчитать кроликов, цыплят и коров)
Ссылка на задачу: https://www.codewars.com/kata/5a02037ac374cbab41000089
Сложность: 7 kyu
Уже решили (На момент написания статьи): 957 из 2295
Тэги: Основы, алгоритмы, математика
Оригинальное описание задачи:
Farmer Bob has a big farm where he grows chickens, rabbits, and cows.
It is very difficult to count the number of animals for each type manually, so he decided to buy a system to do it.
However, he bought a cheap system that can only count the total number of heads, legs, and horns of the animals on the farm.
Can you help Bob figure out how many chickens, rabbits, and cows he has?
All chickens have 2 legs, 1 head and no horns; all rabbits have 4 legs, 1 head and no horns; all cows have 4 legs, 1 head and 2 horns. Your task is to write a function "get_animals_count(legs_number, heads_number, horns_number)"
Parameters "legs_number, heads_number, horns_number" are integers, all tests have valid input.
Example:
get_animals_count(34, 11, 6); # Should return {"rabbits" : 3, "chickens" : 5, "cows" : 3}
get_animals_count(154, 42, 10); # Should return {"rabbits" : 30, "chickens" : 7, "cows" : 5}
Пояснение задачи:
Задача состоит в том, чтобы создать функцию, которая считывает количество ног, голов и рогов у животных на ферме Боба и определяет, сколько у него кур, кроликов и коров.
Функция принимает три параметра: количество ног, голов и рогов.
Эти параметры соответствуют количеству ног у кролика, головы у курицы и рогов у коровы.
Например, если на вход подаются следующие значения:
- Количество ног: 34 - Количество голов: 11 - Количество рогов: 6
То функция должна вернуть следующее: - Кур: 5 - Кроликов: 3 - Коров: 3
Основная цель — правильно интерпретировать данные о количестве ног, голов и рогов и преобразовать их в количество кур, кроликов и коров соответственно.
Платформа: CodeWars
Название задачи: Slay Achilles! (Убей Ахиллес!)
Ссылка на задачу: https://www.codewars.com/kata/5708c90cd531cdfecf00147c
Сложность: 6 kyu
Уже решили (На момент написания статьи): 79 из 752
Тэги: Основы
Оригинальное описание задачи:
A horde of Grecian warriors is storming towards you. Among them is Achilles. Pick him off and slay him. Your city depends on it. Your function will be passed an array of positive integers containing an Achilles number. An Achilles number is "powerful" but not a perfect power, meaning every term of its prime factorization is at least squared, but it cannot be represented as the power of a single number (i.e. it cannot be mk, but may be of the form mx · ny where `x!=y`, etc.).
For example:Remove Achilles from the array and return the array. Note: it's guaranteed that the army does not exceed 1000 numbers, and each number can't exceed 1010 as well.
- 99 = 32 · 11 (not powerful; not Achilles)
- 100 = 102 (perfect power; not Achilles)
- 108 = 2233 (Achilles!)
Пояснение задачи:
Задача требует найти и удалить число, которое является "Ахиллесовым числом" из массива положительных целых чисел. Ахиллесово число — это число, которое не является совершенной степенью, но каждая его простая компонента возводится в квадрат.
Пример: - Число 99 не является Ахиллесовым, так как оно может быть представлено как 3²*11.
- Число 100 также не подходит, поскольку оно является совершенной степенью (10²).
- Число 108 является Ахиллесовым, так как его разложение на простые множители 2233 показывает, что каждый простой множитель возведен в квадрат.
Платформа: CodeWars
Название задачи: Multiples of 3 and 5 redux (Кратные 3 и 5 redux)
Ссылка на задачу: https://www.codewars.com/kata/54bb6ee72c4715684d0008f9
Сложность: 6 kyu
Уже решили (На момент написания статьи): 1760 из 11806
Тэги: Алгоритмы, математика
Оригинальное описание задачи:
The galactic games have begun! It's the galactic games!
Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one).
However, there's also the traditional marathon run.
Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track.
Committees being committees, they've come up with the following rule: > A sensor should be placed every 3 and 5 meters from the start, e.g. > at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m….
Since you're responsible for the track, you need to buy those sensors.
Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead.
Task
Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000).
Examples
solution (10) => 23 = 3 + 5 + 6 + 9
solution (20) => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
Пояснение задачи:
В данном случае нам нужно найти сумму всех чисел, которые делятся на 3 или на 5, но меньше определенного числа.
Это типичная задача для программистов, которая часто встречается в реальных проектах.
Для решения этой задачи необходимо пройти по каждому числу в диапазоне до указанного предела и проверить, делится ли оно на 3 или на 5 без остатка. Если да, то такое число нужно включить в итоговую сумму.
Платформа: CodeWars
Название задачи: Text message codec (Кодек текстовых сообщений)
Ссылка на задачу: https://www.codewars.com/kata/67a9f62277df928f6dbcf97d
Сложность: 5 kyu
Уже решили (На момент написания статьи): 25 из 101
Тэги: Алгоритмы
Оригинальное описание задачи:
With the advent of predictive text, it's surprising how few keypresses are needed to produce a short text message. In this kata we code a simple implementation of predictive text and use it to encode and decode text messages. For simplicity in this kata:
- All messages to be encoded contain only lower-case alphabetic characters and spaces (no digits, punctuation, line-feeds, etc.).
- Words are separated by single spaces.
Our predictive text algorithm uses a preloaded list,
dictionary
, of approximately 1200 frequently used English words, all in lower case, no hyphens or apostrophes. It starts like this:dictionary = ["the","a","is","of","and","to","in","you","that","it","he","for","was","on", ...]
The algorithm is described below by imagining how a user would press the phone keypad to enter their message:
- The user enters their message one word at a time.
- Words which are not in the dictionary must be keyed in full (including a final space character unless the end of the message has been reached).
- After each keypress, the algorithm offers the user a selection of up to three dictionary words, any of which may be selected by user keying
1
,2
, or3
.- At the start of the message, or after a word has been completed, the selection of words is the first three words from the dictionary:
"the"
"a"
"is"
.- At any other point during the encode/decode process, the selection of words is the first three words from the dictionary which match with the characters already entered in the current word.
- Whenever the user can see that the complete current word is displayed in the selection of words, the user selects the word by entering
1
,2
or3
. Otherwise the user continues entering the current word until it appears in the selection or until the word is completed by the user entering a space character.Encode Example:
Encode the message
"that was incredibly simple"
original message | word selection | encoded message -----------------------------|---------------------------------------|------------------------- "" | "the" "a" "is" | "" "t" | "the" "to" "that" | "t" SELECT THIRD WORD ---------------------------------^^^^ "that " | "the" "a" "is" | "t3" "that w" | "was" "with" "what" | "t3w" SELECT FIRST WORD -------^^^ "that was " | "the" "a" "is" | "t3w1" "that was i" | "is" "in" "it" | "t3w1i" "that was in" | "in" "into" "inside" | "t3w1in" "that was inc" | "include" "inch" "increase" | "t3w1inc" "that was incr" | "increase" "incredible" "" | "t3w1incr" "that was incre" | "incredible" "" "" | "t3w1incre" "that was incred" | "incredible" "" "" | "t3w1incred" "that was incredi" | "incredible" "" "" | "t3w1incredi" "that was incredib" | "incredible" "" "" | "t3w1incredib" "that was incredibl" | "incredible" "" "" | "t3w1incredibl" "that was incredibly" | "" "" "" | "t3w1incredibly" "that was incredibly " | "the" "a" "is" | "t3w1incredibly " "that was incredibly s" | "said" "she" "some" | "t3w1incredibly s" "that was incredibly si" | "side" "since" "six" | "t3w1incredibly si" "that was incredibly sim" | "simple" "similar" "" | "t3w1incredibly sim" SELECT FIRST WORD -------^^^ "that was incredibly simple" | "the" "a" "is" | "t3w1incredibly sim1"
Encoded message:
"t3w1incredibly sim1"
Decoding
The process for decoding a valid encoded message is almost the same as the encode process. Simply imagine the user entering the encoded message on their phone:
- As the user enters the characters of the encoded message, the characters are copied to the ddecoded message and the word selection is presented.
- Whenever the user enters
1
,2
or3
the current word of the decoded message is replaced by the selected word.Decode Example:
Encode the message
"t3w1simply incr2"
encoded message | word selection | decoded message -------------------------|-------------------------------------|-------------------------------- "" | "the" "a" "is" | "" "t" | "the" "to" "that" | "t" "t3" | "the" "a" "is" | "that " "t3w" | "was" "with" "what" | "that w" "t3w1" | "the" "a" "is" | "that was " "t3w1s" | "said" "she" "some" | "that was s" "t3w1si" | "side" "since" "six" | "that was si" "t3w1sim" | "simple" "similar" "" | "that was sim" "t3w1simp" | "simple" "" "" | "that was simp" "t3w1simpl" | "simple" "" "" | "that was simpl" "t3w1simply" | "" "" "" | "that was simply" "t3w1simply " | "the" "a" "is" | "that was simply " "t3w1simply i" | "is" "in" "it" | "that was simply i" "t3w1simply in" | "in" "into" "inside" | "that was simply in" "t3w1simply inc" | "include" "inch" "increase" | "that was simply inc" "t3w1simply incr" | "increase" "incredible" "" | "that was simply incr" "t3w1simply incr2" | "the" "a" "is" | "that was simply incredible"
Decoded message:
"that was simply incredible"
The task:
Write the functions
encode
anddecode
as follows:
encode
takes a lower-case string (of alphabetic words separated by spaces) and returns a lower-case string (including spaces and digits) encoded as described above.
decode
takes a lower-case string (of alphabetic characters, digits and spaces) and returns a lower-case string of lower-case alphabetic words, separated by spaces, decoded as described above.All inputs will be valid.
Message size: between
2
and50
wordsWord size: between
1
and20
characters
Пояснение задачи:
Задача заключается в реализации алгоритма предсказывающего текста, который позволяет кодировать и декодировать текстовые сообщения с использованием предварительно загруженного словаря из приблизительно 1200 наиболее употребляемых английских слов. Этот словарь всегда доступен и помогает ускорить ввод сообщений.
Принцип работы:Пользователь вводит сообщение построчно.
Слова, отсутствующие в словаре, вводятся вручную (включая завершающий пробел, если это не конец сообщения).
После каждого нажатия клавиши алгоритм предлагает пользователю выбор из максимум трех слов из словаря, совпадающих с введенным фрагментом.
Пользователь может выбрать одно из предложенных слов, нажимая клавишу 1, 2 или 3.
В начале сообщения или после завершения предыдущего слова предлагаются первые три слова из словаря.
Если текущее слово совпадает с предложением, пользователь нажимает соответствующую клавишу (1, 2 или 3), и слово принимается.
Иначе ввод продолжается до появления полного совпадения или достижения конца слова.
Примеры кодирования и декодирования описаны выше
Платформа: CodeWars
Название задачи: Pick peaks (Выберите пики)
Ссылка на задачу: https://www.codewars.com/kata/5279f6fe5ab7f447890006a7
Сложность: 5 kyu
Уже решили (На момент написания статьи): 29161 из 243274
Тэги: Массивы, алгоритмы
Оригинальное описание задачи:
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
For example, the array
arr = [0, 1, 2, 5, 1, 0]
has a peak at position3
with a value of5
(sincearr[3]
equals5
).The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be
{pos: [], peaks: []}
.Example:
pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])
should return{pos: [3, 7], peaks: [6, 3]}
(or equivalent in other languages)All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!!
[1, 2, 2, 2, 1]
has a peak while[1, 2, 2, 2, 3]
and[1, 2, 2, 2, 2]
do not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example:pickPeaks([1, 2, 2, 2, 1])
returns{pos: [1], peaks: [2]}
(or equivalent in other languages)Have fun!
Заключение:
На этом наша встреча с миром алгоритмических задач подошла к концу. Надеюсь, вы нашли здесь что-то полезное и интересное для себя. Продолжайте практиковаться, ведь именно регулярные тренировки ведут к совершенству. До новых встреч и успехов в программировании!