Приветствую всех любителей программирования! В этой статье я подготовил для вас подборку интересных задач, которые помогут вам отточить навыки работы с алгоритмами. Здесь вы найдете задания разного уровня сложности, позволяющие поддерживать форму и одновременно получать удовольствие от процесса.
Цель — не только развивать умение писать код, но и весело провести время, решая увлекательные головоломки.
Что было раньше:
В предыдущей части мы решили:
- Convert a string to an array (Преобразовать строку в массив)
- Count the Monkeys! (Посчитай обезьян!)
- Dropcaps (Откидные крышки)
- Homogenous arrays (Однородные массивы)
- Find the Lowest Common Ancestor (Найдите наименьшего общего предка)
- Constrained GCD (Ограниченный GCD)
Решение новых задач:
Задача 1
Платформа: CodeWars
Название задачи: Heads and Legs (Головы и ноги)
Ссылка на задачу: https://www.codewars.com/kata/574c5075d27783851800169e
Сложность: 8 (8 / 8) kyu
Оригинальное описание задачи:
Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes:
“A farm contains chickens and cows.
There are x heads and y legs.
How many chickens and cows are there?”
Where x <= 1000 and y <=1000
Task
Assuming there are no other types of animals, work out how many of each animal are there.
Return a tuple in Python - (chickens, cows)
or an array list - [chickens, cows]/{chickens, cows} in all other languages
If either the heads & legs is negative, the result of your calculation is negative or the calculation is a float return "No solutions" (no valid cases), or [-1, -1] in COBOL.
In the form:
(Heads, Legs) = (72, 200)
VALID - (72, 200) => (44 , 28)
(Chickens, Cows)
INVALID - (72, 201) => "No solutions"
However, if 0 heads and 0 legs are given always return [0, 0]
since zero heads must give zero animals.
There are many different ways to solve this, but they all give the same answer.
You will only be given integers types - however negative values (edge cases) will be given.
Happy coding!
Пояснение задачи:
Задача классическая: на ферме есть куры и коровы.
Известно количество голов (x) и ног (y).
Нужно определить, сколько кур и коров на ферме.
Правила: - У кур 2 ноги, у коров 4 ноги.
- Возвращаемый результат должен быть кортежем в Python или массивом в других языках: (количество кур, количество коров).
- Если значения голов или ног отрицательные, или результат вычислений отрицательный или дробный, вернуть "No solutions" или `[-1, -1]` в COBOL.
- Если даны 0 голов и 0 ног, вернуть `[0, 0]`.
Примеры:
- `(72, 200)` → `(44, 28)` (курицы и коровы соответственно).
- `(72, 201)` → "No solutions" (невозможно найти решение).
- `(0, 0)` → `[0, 0]`.
Задача 2
Платформа: CodeWars
Название задачи: Stringy Strings (Строчные строки)
Ссылка на задачу: https://www.codewars.com/kata/563b74ddd19a3ad462000054
Сложность: 8 (8 / 8) kyu
Оригинальное описание задачи:
write me a function stringy
that takes a size
and returns a string
of alternating 1
s and 0
s.
the string should start with a 1
.
a string with size
6 should return :'101010'
.
with size
4 should return : '1010'
.
with size
12 should return : '101010101010'
.
The size will always be positive and will only use whole numbers.
Strings
Binary
Algorithms
Пояснение задачи:
Задача заключается в написании функции `stringy`, которая принимает на вход число и возвращает строку, состоящую из чередующихся единиц и нулей. Строка должна начинаться с единицы.
Примеры:
- Размер 6: "101010"
- Размер 4: "1010"
- Размер 12: "101010101010"
Размер всегда положительный и является целым числом.
Задача 3
Платформа: CodeWars
Название задачи: Recurrence by Recursion (Повторение с помощью рекурсии)
Ссылка на задачу: https://www.codewars.com/kata/56f29b3b75e340627a0009d5
Сложность: 7 (7 / 8) kyu
Оригинальное описание задачи:
In mathematics, a recurrence formula is a formula that shows the relationship between each term and the next in a numerical sequence. For example, a sequence may be defined as follows:
n = t + 3, f = 1
... where n
is the next term, t
is the current term and f
is the first term in the sequence.
Recurrence in mathematics is very similar to recursion in computer programming in a lot of ways:
- In both recurrence and recursion, the main problem invokes a simpler problem of the same nature. For example, in recurrence formulae, calculation of the seventh term of the sequence requires the sixth term of the sequence, whose calculation then requires the fifth term of the sequence and so on.
- In both recurrence and recursion, there is always something called the base case which kind of acts like a floor - without it, the calculation (or invocation) process would never end and nothing would be solved! For example, the base case in recurrence formulae is the first term, which always has to be explicitly and separately defined for the whole sequence to work. In computer programming, it would be a special case where the function no longer invokes itself and instead just returns a value.
Going back to the formula above, our first term is 1 and each next term is the current term added by 3. Thus we have:
- First term: 1
- Second term: 1 + 3 = 4
- Third term: 4 + 3 = 7
- 7 + 3 = 10
- 13
... and so on.
Task
Your task is to create a function, recurrence(base, formula, term)
where base
is the base case or first term of the sequence, formula
is the recurrence formula given as a function/method and term
is the number of the term of the series which your function/method has to calculate. For example:
recurrence(1, n => n + 3, 4) === 10
recurrence(3, n => 2 * n, 5) === 48
Good luck :)
Пояснение задачи:
Задача заключается в создании функции `recurrence`, которая принимает три аргумента: базовое значение `base`, рекурсивную формулу `formula` и номер элемента последовательности `term`.
Функция должна рассчитывать указанный элемент последовательности, используя заданную формулу.
Пример:
- `recurrence(1, n => n + 3, 4)` возвращает 10, так как:
- Первый элемент: 1
- Второй элемент: 1 + 3 = 4
- Третий элемент: 4 + 3 = 7
- Четвертый элемент: 7 + 3 = 10
Другой пример:
- `recurrence(3, n => 2 * n, 5)` возвращает 48, так как:
- Первый элемент: 3
- Второй элемент: 3 * 2 = 6
- Третий элемент: 6 * 2 = 12
- Четвертый элемент: 12 * 2 = 24
- Пятый элемент: 24 * 2 = 48
Задача 4
Платформа: CodeWars
Название задачи: Power of 4 (Степень четырёх)
Ссылка на задачу: https://www.codewars.com/kata/544d114f84e41094a9000439
Сложность: 7 (7 / 8) kyu
Оригинальное описание задачи:
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well.
(In C# Integer means all integer Types like Int16,Int32,.....)
Examples
isPowerOf4 1024 #should return True
isPowerOf4 102 #should return False
isPowerOf4 64 #should return True
Пояснение задачи:
Задача заключается в написании метода, который проверяет, является ли данное число степенью четверки.
Метод должен возвращать `true`, если число является степенью четверки, и `false` в противном случае.
Если параметр не является целым числом (например, строка или массив), метод также должен возвращать `false`.
Примеры:
- `isPowerOf4 1024` → `True` (1024 = 4S10;)
- `isPowerOf4 102` → `False` (102 не является степенью четверки)
- `isPowerOf4 64` → `True` (64 = 4³)
Задача 5
Платформа: CodeWars
Название задачи: Best Stock Profit in Single Sale (Лучшая прибыль от продажи акций за одну продажу)
Ссылка на задачу: https://www.codewars.com/kata/58f174ed7e9b1f32b40000ec
Сложность: 6 (6 / 8) kyu
Оригинальное описание задачи:
You're a buyer/seller and your buisness is at stake... You need to make profit... Or at least, you need to lose the least amount of money!
Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you need to buy one item, then sell it later. Find the best profit you can do.
Example:
Given an array of prices [3, 10, 8, 4]
, the best profit you could make would be 7
because you buy at 3
first, then sell at 10
.
Input:
A list of prices (integers), of length 2 or more.
Output:
The result of the best buy/sell operation, as an integer.
Note:
Be aware you'll face lists with several thousands of elements, so think about performance.
Algorithms
Пояснение задачи:
Задача заключается в нахождении наилучшей возможной прибыли от покупки и последующей продажи товара.
У вас есть список цен, отражающий изменение стоимости товара со временем.
Сначала нужно купить товар, а затем продать его позже.
Найдите максимальную прибыль, которую можно получить.
Пример:
Для списка цен `[3, 10, 8, 4]`, лучшая возможная прибыль составит 7, потому что вы покупаете товар за 3, а продаёте за 10.
Входные данные:
Список цен (целые числа), содержащий 2 или более элементов.
Выходные данные: Результат лучшей операции купли-продажи в виде целого числа.
Примечание: Будьте внимательны, вам придется сталкиваться со списками, содержащими тысячи элементов, поэтому подумайте о производительности вашего решения.
Задача 6
Платформа: CodeWars
Название задачи: Arrays of cats and dogs (Массив кошек и собак)
Ссылка на задачу: https://www.codewars.com/kata/5a5f48f2880385daac00006c
Сложность: 6 (6 / 8) kyu
Оригинальное описание задачи:
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than n
elements away. Your task will be to return the maximum number of cats that can be caught.
For example:
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4.
solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4.
solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1.
solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught!
Do not modify the input array.
More examples in the test cases. Good luck!
Пояснение задачи:
Задача заключается в определении максимального количества кошек, которых могут поймать собаки.
Собака может поймать кошку, если кошка находится не дальше, чем на расстоянии n позиций от неё.
Кошка может быть поймана только одной собакой.
Примеры:
- `solve(['D','C','C','D','C'], 2)` → 2, потому что собака на индексе 0 ловит кошку на индексе 1, а собака на индексе 3 ловит кошку на индексе 4.
- `solve(['C','C','D','D','C','D'], 2)` → 3, потому что собака на индексе 2 ловит кошку на индексе 0, собака на индексе 3 ловит кошку на индексе 1, а собака на индексе 5 ловит кошку на индексе 4.
- `solve(['C','C','D','D','C','D'], 1)` → 2, потому что собака на индексе 2 ловит кошку на индексе 1, а собака на индексе 3 ловит кошку на индексе 4. Кошка на индексе 0 не может быть поймана, так как n = 1.
- `solve(['D','C','D','D','C'], 1)` → 2, так как слишком много собак, и все кошки оказываются пойманными.
Исходный массив изменять нельзя.
Задача 7
Платформа: CodeWars
Название задачи: Simple Fun #362: Who Is The Hero? II (Простая забава #362: Кто Герой? ii)
Ссылка на задачу: https://www.codewars.com/kata/59dc6a967905dfb7530000aa
Сложность: 5 (5 / 8) kyu
Оригинальное описание задачи:
Story
Ten mathematicians are flying on a balloon over the Pacific ocean. When they are crossing the equator they decide to celebrate this event and open a bottle of champagne. Unfortunately, the cork makes a hole in the balloon.
Hydrogen is leaking out and the balloon is descending now. Soon it will fall into the ocean and all the balloonists will be eaten by hungry sharks.
But not everything is lost yet. One of the balloonists can sacrifice himself jumping out, so that his friends would live a little longer.
Only one problem still exists: Who is the one to get out.
There is a fair way to solve this problem. First, each of them writes an integer ai not less than 1 and not more than 10000. Then they calculate the magic number N
that is the number of positive integer divisors of the product a
1*a
2*...*a
10. For example, the number of positive integer divisors of 6 is 4 (they are 1,2,3,6).
The hero (a mathematician who will be thrown out) is determined according to the last digit of N
. Can you find out who is the hero?
Task
Given an argument namesAndNumbers
. It's an object that contains 10 men's names and the numbers. Like this:
{John:1,Tom:2,...,Voile:1}
Your task is to calculate the last digit of the number of positive integer divisors of the product of 10 numbers, and return a string like this:
"Good-Bye, Hero <Hero's name here>! We'll take care of your children and your wife."
Still not understand the task? Look at the following example ;-)
Example
For namesAndNumbers =
{
John:1,
Tom:2,
Jerry:6,
Mike:1,
Abc:3,
Def:1,
Ghi:1,
Jkl:1,
Mno:1,
Voile:1
}
the output should be:
"Good-Bye, Hero Voile! We'll take care of your children and your wife."
Because:
The product of 10 numbers is:
1 x 2 x 6 x 1 x 3 x 1 x 1 x 1 x 1 x 1 = 36
The positive integer divisors of 36 are:
1,2,3,4,6,9,12,18,36 -> N = 9
The last digit of N is 9
So, the 9th(0-based) man Volie is the hero.
Note
-
namesAndNumbers
is always a valid object. It always contains 10 names and 10 numbers. All of the numbers is a positive integer less than or euqals to 10000.
-
Perhaps you can't work out the product of the 10 numbers directly, when these numbers are large enough.
-
In order to avoid timeout, be aware of the code's performance ;-)
-
If you think it's too hard to solve, please try Who Is The Hero? I
-
Happy Coding ^_^
Пояснение задачи:
Задача заключается в определении героя, который должен покинуть воздушный шар, чтобы спасти остальных.
Для этого каждый участник пишет число ai от 1 до 10000.
Затем вычисляют магическое число N — количество положительных делителей произведения всех чисел
a1 * a2 * ... * a10.
Герой определяется по последней цифре числа N.
Пример:
Пусть участники написали числа:
{ John: 1, Tom: 2, Jerry: 6, Mike: 1, Abc: 3, Def: 1, Ghi: 1, Jkl: 1, Mno: 1, Voile: 1 }
Тогда произведение чисел: 1 * 2 * 6 * 1 * 3 * 1 * 1 * 1 * 1 * 1 = 36
Количество положительных делителей числа 36: 1, 2, 3, 4, 6, 9, 12, 18, 36 -> N = 9
Последняя цифра N — 9, следовательно, героем становится девятый участник (считая с нуля) — Voile.
Необходимо вывести строку:
"Good-Bye, Hero Voile! We'll take care of your children and your wife."
Внимание: объект `namesAndNumbers` всегда содержит 10 имен и 10 чисел, каждое число — положительное целое, не превышающее 10000.
Задача 8
Платформа: CodeWars
Название задачи: A Scandal in Bohemia (Скандал в Богемии)
Ссылка на задачу: https://www.codewars.com/kata/5f2dcbbd1b69a9000f225940
Сложность: 5 (5 / 8) kyu
Оригинальное описание задачи:
Someone has used a simple substitution cipher to encrypt an extract from Conan Doyle's A Scandal in Bohemia. Your task is to find the key they used to encrypt it.
Specifications
The key will be random. The key will work the same for uppercase and lowercase but punctuation and spaces will be left alone. The extract will be large (c.85% of the whole text). Input is the encrypted extract as a string (which you can see with print(extract)
), output is the key as a string.
What is a Simple Substitution Cipher?
A simple substitution cipher is a type of substitution cipher that uses a key 26 characters long which acts as a map. Let's look at an example with key = 'qwertyuiopasdfghjklzxcvbnm':
alphabet: |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|
key1: |q|w|e|r|t|y|u|i|o|p|a|s|d|f|g|h|j|k|l|z|x|c|v|b|n|m|
Using the aformentioned key = 'qwertyuiopasdfghjklzxcvbnm', we can see that 'a' gets mapped to 'q', 'b' to 'w', 'c' to 'e', 'd' to 'r', 'e' to 't', 'f' to 'y' ... 'y' to 'n', and finally 'z' to 'm'. The key must contain all letters a-z exaclty once. Let's see one more example with key='zyxwvutsrqponmlkjihgfedcba':
alphabet: |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|
key2: |z|y|x|w|v|u|t|s|r|q|p|o|n|m|l|k|j|i|h|g|f|e|d|c|b|a|
Now that we have a map for our letters we simply translate letter for letter. A capital will be translated like its lowercase counterpart, but will stay in uppercase. Spaces and punctuation will stay as is. The opening to A Tale of Two Cities:
It was the best of times,
it was the worst of times,
it was the age of wisdom,
it was the age of foolishness,
it was the epoch of belief,
it was the epoch of incredulity,
it was the season of Light,
it was the season of Darkness,
it was the spring of hope,
it was the winter of despair.
becomes:
Ol vqz lit wtzl gy lodtz,
ol vqz lit vgkzl gy lodtz,
ol vqz lit qut gy vozrgd,
ol vqz lit qut gy yggsoziftzz,
ol vqz lit thgei gy wtsoty,
ol vqz lit thgei gy ofektrxsoln,
ol vqz lit ztqzgf gy Souil,
ol vqz lit ztqzgf gy Rqkaftzz,
ol vqz lit zhkofu gy ight,
ol vqz lit vofltk gy rtzhqok.
using key1 and:
Rh dzg hsv yvgh lu hrnvg,
rh dzg hsv dligh lu hrnvg,
rh dzg hsv ztv lu drgwln,
rh dzg hsv ztv lu ullorgsmvgg,
rh dzg hsv vklxs lu yvorvu,
rh dzg hsv vklxs lu rmxivwforhb,
rh dzg hsv gvzglm lu Ortsh,
rh dzg hsv gvzglm lu Wzipmvgg,
rh dzg hsv gkirmt lu slkv,
rh dzg hsv drmhvi lu wvgkzri.
in key2. In the tests, the text will have no new line characters '\n'; this was just for illustrative purposes.
The book is preloaded. It may be accessed as
a_scandal_in_bohemia
There are a set of brackets and an ampersand in the original text. They have been changed to commas and the word 'and' respectively to makes thing a little harder ;) You might want to have a go at this cipher first.
Пояснение задачи:
Задача заключается в раскрытии простого шифра подстановки, который использовался для зашифрования фрагмента текста из произведения Артура Конан Дойля "Скандал в Богемии".
Простая подстановочная шифровка заменяет каждую букву алфавита другой буквой.
Ключевая фраза содержит все буквы латинского алфавита в произвольном порядке.
Буквы сохраняются в верхнем или нижнем регистре, а знаки препинания и пробелы остаются без изменений.
Шифрование осуществляется следующим образом:
1. Создание ключа:
Создается строка длиной 26 символов, где каждая буква заменяется на другую букву в произвольном порядке.
2. Применение ключа:
Каждая буква текста заменяется соответствующей буквой из ключа.
Примеры:
1. Ключ: `qwertyuiopasdfghjklzxcvbnm`
- Буква `a` заменяется на `q`, `b` на `w`, `c` на `e` и так далее.
2. Ключ: `zyxwvutsrqponmlkjihgfedcba`
- Буква `a` заменяется на `z`, `b` на `y`, `c` на `x` и так далее.
Задача: Необходимо восстановить ключ, который использовался для шифрования текста.
Заключение:
Платформа: CodeWars
Название задачи: Heads and Legs (Головы и ноги)
Ссылка на задачу: https://www.codewars.com/kata/574c5075d27783851800169e
Сложность: 8 (8 / 8) kyu
Оригинальное описание задачи:
Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes:
“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?”
Where x <= 1000 and y <=1000
Task
Assuming there are no other types of animals, work out how many of each animal are there.
Return a tuple in Python - (chickens, cows) or an array list - [chickens, cows]/{chickens, cows} in all other languages
If either the heads & legs is negative, the result of your calculation is negative or the calculation is a float return "No solutions" (no valid cases), or [-1, -1] in COBOL.
In the form:
(Heads, Legs) = (72, 200) VALID - (72, 200) => (44 , 28) (Chickens, Cows) INVALID - (72, 201) => "No solutions"
However,
if 0 heads and 0 legs are given always return [0, 0]
since zero heads must give zero animals.There are many different ways to solve this, but they all give the same answer.
You will only be given integers types - however negative values (edge cases) will be given.
Happy coding!
Пояснение задачи:
Задача классическая: на ферме есть куры и коровы.
Известно количество голов (x) и ног (y).
Нужно определить, сколько кур и коров на ферме.
Правила: - У кур 2 ноги, у коров 4 ноги.
- Возвращаемый результат должен быть кортежем в Python или массивом в других языках: (количество кур, количество коров).
- Если значения голов или ног отрицательные, или результат вычислений отрицательный или дробный, вернуть "No solutions" или `[-1, -1]` в COBOL.
- Если даны 0 голов и 0 ног, вернуть `[0, 0]`.
Примеры:
- `(72, 200)` → `(44, 28)` (курицы и коровы соответственно).
- `(72, 201)` → "No solutions" (невозможно найти решение).
- `(0, 0)` → `[0, 0]`.
Платформа: CodeWars
Название задачи: Stringy Strings (Строчные строки)
Ссылка на задачу: https://www.codewars.com/kata/563b74ddd19a3ad462000054
Сложность: 8 (8 / 8) kyu
Оригинальное описание задачи:
write me a function
stringy
that takes asize
and returns astring
of alternating1
s and0
s.the string should start with a
1
.a string with
size
6 should return :'101010'
.with
size
4 should return :'1010'
.with
size
12 should return :'101010101010'
.The size will always be positive and will only use whole numbers.
StringsBinaryAlgorithms
Пояснение задачи:
Задача заключается в написании функции `stringy`, которая принимает на вход число и возвращает строку, состоящую из чередующихся единиц и нулей. Строка должна начинаться с единицы.
Примеры:
- Размер 6: "101010"
- Размер 4: "1010"
- Размер 12: "101010101010"
Размер всегда положительный и является целым числом.
Платформа: CodeWars
Название задачи: Recurrence by Recursion (Повторение с помощью рекурсии)
Ссылка на задачу: https://www.codewars.com/kata/56f29b3b75e340627a0009d5
Сложность: 7 (7 / 8) kyu
Оригинальное описание задачи:
In mathematics, a recurrence formula is a formula that shows the relationship between each term and the next in a numerical sequence. For example, a sequence may be defined as follows:
n = t + 3, f = 1
... where
n
is the next term,t
is the current term andf
is the first term in the sequence.Recurrence in mathematics is very similar to recursion in computer programming in a lot of ways:
- In both recurrence and recursion, the main problem invokes a simpler problem of the same nature. For example, in recurrence formulae, calculation of the seventh term of the sequence requires the sixth term of the sequence, whose calculation then requires the fifth term of the sequence and so on.
- In both recurrence and recursion, there is always something called the base case which kind of acts like a floor - without it, the calculation (or invocation) process would never end and nothing would be solved! For example, the base case in recurrence formulae is the first term, which always has to be explicitly and separately defined for the whole sequence to work. In computer programming, it would be a special case where the function no longer invokes itself and instead just returns a value.
Going back to the formula above, our first term is 1 and each next term is the current term added by 3. Thus we have:
- First term: 1
- Second term: 1 + 3 = 4
- Third term: 4 + 3 = 7
- 7 + 3 = 10
- 13
... and so on.
Task
Your task is to create a function,
recurrence(base, formula, term)
wherebase
is the base case or first term of the sequence,formula
is the recurrence formula given as a function/method andterm
is the number of the term of the series which your function/method has to calculate. For example:recurrence(1, n => n + 3, 4) === 10 recurrence(3, n => 2 * n, 5) === 48
Good luck :)
Пояснение задачи:
Задача заключается в создании функции `recurrence`, которая принимает три аргумента: базовое значение `base`, рекурсивную формулу `formula` и номер элемента последовательности `term`.
Функция должна рассчитывать указанный элемент последовательности, используя заданную формулу.
Пример:
- `recurrence(1, n => n + 3, 4)` возвращает 10, так как:
- Первый элемент: 1
- Второй элемент: 1 + 3 = 4
- Третий элемент: 4 + 3 = 7
- Четвертый элемент: 7 + 3 = 10
Другой пример:
- `recurrence(3, n => 2 * n, 5)` возвращает 48, так как:
- Первый элемент: 3
- Второй элемент: 3 * 2 = 6
- Третий элемент: 6 * 2 = 12
- Четвертый элемент: 12 * 2 = 24
- Пятый элемент: 24 * 2 = 48
Платформа: CodeWars
Название задачи: Power of 4 (Степень четырёх)
Ссылка на задачу: https://www.codewars.com/kata/544d114f84e41094a9000439
Сложность: 7 (7 / 8) kyu
Оригинальное описание задачи:
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well.
(In C# Integer means all integer Types like Int16,Int32,.....)
Examples
isPowerOf4 1024 #should return True isPowerOf4 102 #should return False isPowerOf4 64 #should return True
Пояснение задачи:
Задача заключается в написании метода, который проверяет, является ли данное число степенью четверки.
Метод должен возвращать `true`, если число является степенью четверки, и `false` в противном случае.
Если параметр не является целым числом (например, строка или массив), метод также должен возвращать `false`.
Примеры:
- `isPowerOf4 1024` → `True` (1024 = 4S10;)
- `isPowerOf4 102` → `False` (102 не является степенью четверки)
- `isPowerOf4 64` → `True` (64 = 4³)
Платформа: CodeWars
Название задачи: Best Stock Profit in Single Sale (Лучшая прибыль от продажи акций за одну продажу)
Ссылка на задачу: https://www.codewars.com/kata/58f174ed7e9b1f32b40000ec
Сложность: 6 (6 / 8) kyu
Оригинальное описание задачи:
You're a buyer/seller and your buisness is at stake... You need to make profit... Or at least, you need to lose the least amount of money!
Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you need to buy one item, then sell it later. Find the best profit you can do.Example:
Given an array of prices
[3, 10, 8, 4]
, the best profit you could make would be7
because you buy at3
first, then sell at10
.Input:
A list of prices (integers), of length 2 or more.
Output:
The result of the best buy/sell operation, as an integer.
Note:
Be aware you'll face lists with several thousands of elements, so think about performance.
Algorithms
Пояснение задачи:
Задача заключается в нахождении наилучшей возможной прибыли от покупки и последующей продажи товара.
У вас есть список цен, отражающий изменение стоимости товара со временем.
Сначала нужно купить товар, а затем продать его позже.
Найдите максимальную прибыль, которую можно получить.
Пример:
Для списка цен `[3, 10, 8, 4]`, лучшая возможная прибыль составит 7, потому что вы покупаете товар за 3, а продаёте за 10.
Входные данные:
Список цен (целые числа), содержащий 2 или более элементов.
Выходные данные: Результат лучшей операции купли-продажи в виде целого числа.
Примечание: Будьте внимательны, вам придется сталкиваться со списками, содержащими тысячи элементов, поэтому подумайте о производительности вашего решения.
Платформа: CodeWars
Название задачи: Arrays of cats and dogs (Массив кошек и собак)
Ссылка на задачу: https://www.codewars.com/kata/5a5f48f2880385daac00006c
Сложность: 6 (6 / 8) kyu
Оригинальное описание задачи:
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than
n
elements away. Your task will be to return the maximum number of cats that can be caught.For example:
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4. solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4. solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1. solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught!
Do not modify the input array.
More examples in the test cases. Good luck!
Пояснение задачи:
Задача заключается в определении максимального количества кошек, которых могут поймать собаки.
Собака может поймать кошку, если кошка находится не дальше, чем на расстоянии n позиций от неё.
Кошка может быть поймана только одной собакой.
Примеры:
- `solve(['D','C','C','D','C'], 2)` → 2, потому что собака на индексе 0 ловит кошку на индексе 1, а собака на индексе 3 ловит кошку на индексе 4.
- `solve(['C','C','D','D','C','D'], 2)` → 3, потому что собака на индексе 2 ловит кошку на индексе 0, собака на индексе 3 ловит кошку на индексе 1, а собака на индексе 5 ловит кошку на индексе 4.
- `solve(['C','C','D','D','C','D'], 1)` → 2, потому что собака на индексе 2 ловит кошку на индексе 1, а собака на индексе 3 ловит кошку на индексе 4. Кошка на индексе 0 не может быть поймана, так как n = 1.
- `solve(['D','C','D','D','C'], 1)` → 2, так как слишком много собак, и все кошки оказываются пойманными.
Исходный массив изменять нельзя.
Платформа: CodeWars
Название задачи: Simple Fun #362: Who Is The Hero? II (Простая забава #362: Кто Герой? ii)
Ссылка на задачу: https://www.codewars.com/kata/59dc6a967905dfb7530000aa
Сложность: 5 (5 / 8) kyu
Оригинальное описание задачи:
Story
Ten mathematicians are flying on a balloon over the Pacific ocean. When they are crossing the equator they decide to celebrate this event and open a bottle of champagne. Unfortunately, the cork makes a hole in the balloon.
Hydrogen is leaking out and the balloon is descending now. Soon it will fall into the ocean and all the balloonists will be eaten by hungry sharks.
But not everything is lost yet. One of the balloonists can sacrifice himself jumping out, so that his friends would live a little longer.
Only one problem still exists: Who is the one to get out.
There is a fair way to solve this problem. First, each of them writes an integer ai not less than 1 and not more than 10000. Then they calculate the magic number
N
that is the number of positive integer divisors of the producta
1*a
2*...*a
10. For example, the number of positive integer divisors of 6 is 4 (they are 1,2,3,6).The hero (a mathematician who will be thrown out) is determined according to the last digit of
N
. Can you find out who is the hero?Task
Given an argument
namesAndNumbers
. It's an object that contains 10 men's names and the numbers. Like this:{John:1,Tom:2,...,Voile:1}
Your task is to calculate the last digit of the number of positive integer divisors of the product of 10 numbers, and return a string like this:
"Good-Bye, Hero <Hero's name here>! We'll take care of your children and your wife."
Still not understand the task? Look at the following example ;-)
Example
For
namesAndNumbers =
{ John:1, Tom:2, Jerry:6, Mike:1, Abc:3, Def:1, Ghi:1, Jkl:1, Mno:1, Voile:1 }
the output should be:
"Good-Bye, Hero Voile! We'll take care of your children and your wife."
Because:
The product of 10 numbers is: 1 x 2 x 6 x 1 x 3 x 1 x 1 x 1 x 1 x 1 = 36 The positive integer divisors of 36 are: 1,2,3,4,6,9,12,18,36 -> N = 9 The last digit of N is 9 So, the 9th(0-based) man Volie is the hero.
Note
namesAndNumbers
is always a valid object. It always contains 10 names and 10 numbers. All of the numbers is a positive integer less than or euqals to 10000.Perhaps you can't work out the product of the 10 numbers directly, when these numbers are large enough.
In order to avoid timeout, be aware of the code's performance ;-)
If you think it's too hard to solve, please try Who Is The Hero? I
Happy Coding
^_^
Пояснение задачи:
Задача заключается в определении героя, который должен покинуть воздушный шар, чтобы спасти остальных.
Для этого каждый участник пишет число ai от 1 до 10000.
Затем вычисляют магическое число N — количество положительных делителей произведения всех чисел
a1 * a2 * ... * a10.
Герой определяется по последней цифре числа N.
Пример:
Пусть участники написали числа:
{ John: 1, Tom: 2, Jerry: 6, Mike: 1, Abc: 3, Def: 1, Ghi: 1, Jkl: 1, Mno: 1, Voile: 1 }
Тогда произведение чисел: 1 * 2 * 6 * 1 * 3 * 1 * 1 * 1 * 1 * 1 = 36
Количество положительных делителей числа 36: 1, 2, 3, 4, 6, 9, 12, 18, 36 -> N = 9
Последняя цифра N — 9, следовательно, героем становится девятый участник (считая с нуля) — Voile.
Необходимо вывести строку:
"Good-Bye, Hero Voile! We'll take care of your children and your wife."
Внимание: объект `namesAndNumbers` всегда содержит 10 имен и 10 чисел, каждое число — положительное целое, не превышающее 10000.
Платформа: CodeWars
Название задачи: A Scandal in Bohemia (Скандал в Богемии)
Ссылка на задачу: https://www.codewars.com/kata/5f2dcbbd1b69a9000f225940
Сложность: 5 (5 / 8) kyu
Оригинальное описание задачи:
Someone has used a simple substitution cipher to encrypt an extract from Conan Doyle's A Scandal in Bohemia. Your task is to find the key they used to encrypt it.
Specifications
The key will be random. The key will work the same for uppercase and lowercase but punctuation and spaces will be left alone. The extract will be large (c.85% of the whole text). Input is the encrypted extract as a string (which you can see with
print(extract)
), output is the key as a string.What is a Simple Substitution Cipher?
A simple substitution cipher is a type of substitution cipher that uses a key 26 characters long which acts as a map. Let's look at an example with key = 'qwertyuiopasdfghjklzxcvbnm':
alphabet: |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z| key1: |q|w|e|r|t|y|u|i|o|p|a|s|d|f|g|h|j|k|l|z|x|c|v|b|n|m|
Using the aformentioned key = 'qwertyuiopasdfghjklzxcvbnm', we can see that 'a' gets mapped to 'q', 'b' to 'w', 'c' to 'e', 'd' to 'r', 'e' to 't', 'f' to 'y' ... 'y' to 'n', and finally 'z' to 'm'. The key must contain all letters a-z exaclty once. Let's see one more example with key='zyxwvutsrqponmlkjihgfedcba':
alphabet: |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z| key2: |z|y|x|w|v|u|t|s|r|q|p|o|n|m|l|k|j|i|h|g|f|e|d|c|b|a|
Now that we have a map for our letters we simply translate letter for letter. A capital will be translated like its lowercase counterpart, but will stay in uppercase. Spaces and punctuation will stay as is. The opening to A Tale of Two Cities:
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair.
becomes:
Ol vqz lit wtzl gy lodtz, ol vqz lit vgkzl gy lodtz, ol vqz lit qut gy vozrgd, ol vqz lit qut gy yggsoziftzz, ol vqz lit thgei gy wtsoty, ol vqz lit thgei gy ofektrxsoln, ol vqz lit ztqzgf gy Souil, ol vqz lit ztqzgf gy Rqkaftzz, ol vqz lit zhkofu gy ight, ol vqz lit vofltk gy rtzhqok.
using key1 and:
Rh dzg hsv yvgh lu hrnvg, rh dzg hsv dligh lu hrnvg, rh dzg hsv ztv lu drgwln, rh dzg hsv ztv lu ullorgsmvgg, rh dzg hsv vklxs lu yvorvu, rh dzg hsv vklxs lu rmxivwforhb, rh dzg hsv gvzglm lu Ortsh, rh dzg hsv gvzglm lu Wzipmvgg, rh dzg hsv gkirmt lu slkv, rh dzg hsv drmhvi lu wvgkzri.
in key2. In the tests, the text will have no new line characters '\n'; this was just for illustrative purposes.
The book is preloaded. It may be accessed as
a_scandal_in_bohemia
There are a set of brackets and an ampersand in the original text. They have been changed to commas and the word 'and' respectively to makes thing a little harder ;) You might want to have a go at this cipher first.
Пояснение задачи:
Задача заключается в раскрытии простого шифра подстановки, который использовался для зашифрования фрагмента текста из произведения Артура Конан Дойля "Скандал в Богемии".
Простая подстановочная шифровка заменяет каждую букву алфавита другой буквой.
Ключевая фраза содержит все буквы латинского алфавита в произвольном порядке.
Буквы сохраняются в верхнем или нижнем регистре, а знаки препинания и пробелы остаются без изменений.
Шифрование осуществляется следующим образом:
1. Создание ключа:
Создается строка длиной 26 символов, где каждая буква заменяется на другую букву в произвольном порядке.
2. Применение ключа:
Каждая буква текста заменяется соответствующей буквой из ключа.
Примеры:
1. Ключ: `qwertyuiopasdfghjklzxcvbnm`
- Буква `a` заменяется на `q`, `b` на `w`, `c` на `e` и так далее.
2. Ключ: `zyxwvutsrqponmlkjihgfedcba`
- Буква `a` заменяется на `z`, `b` на `y`, `c` на `x` и так далее.
Задача: Необходимо восстановить ключ, который использовался для шифрования текста.
Надеюсь, эта статья принесла вам пользу и вдохновение для дальнейшего развития навыков программирования. Делитесь своими мыслями и решениями в комментариях, ведь обмен опытом делает нас сильнее. Спасибо за внимание, и до встречи в следующей статье, где нас ждут новые увлекательные задачи!