# 06/07/21 Евчук Даяна Во время пары: ## 1. Задача 1 [An English Twist on a Japanese Classic](https://www.codewars.com/kata/5b04be641839f1a0ab000151) **7kyu** Background: In Japan, a game called Shiritori is played. The rules are simple, a group of people take turns calling out a word whose beginning syllable is the same as the previous player's ending syllable. For example, the first person would say the word ねこ, and the second player must make a word that starts with こ, like こむぎ. This repeats until a player can not think of a word fast enough or makes a word that ends in ん, because there are no words that begin with ん in the Japanese language. English Shiritori has the same principle, with the first and last letters of words. That being said the lose condition is saying a word that doesn't start with the previous word's last letter or not saying a word quick enough. `For example: apple -> eggs -> salmon -> nut -> turkey ...` Your Task: You will be given a list of strings, a transcript of an English Shiritori match. Your task is to find out if the game ended early, and return a list that contains every valid string until the mistake. If a list is empty return an empty list. If one of the elements is an empty string, that is invalid and should be handled. *Перевод* Задний план: В Японии играют в игру под названием Сиритори. Правила просты: группа людей по очереди выкрикивает слово, начальный слог которого совпадает с конечным слогом предыдущего игрока. Например, первый человек скажет слово ね こ, а второй игрок должен составить слово, которое начинается с こ, например こ む ぎ. Это повторяется до тех пор, пока игрок не сможет придумать слово достаточно быстро или составит слово, оканчивающееся на ん, потому что в японском языке нет слов, начинающихся на ん. Английский Shiritori имеет тот же принцип, с первой и последней буквами слов. При этом условие проигрыша означает произнесение слова, которое не начинается с последней буквы предыдущего слова, или произнесение слова недостаточно быстро. `Например: яблоко -> окрошка -> арбуз -> зелёнка -> ...` Твое задание: Вам будет предоставлен список строк, стенограмма матча английского сиритори. Ваша задача - выяснить, не закончилась ли игра раньше, и вернуть список, содержащий все допустимые строки до ошибки. Если список пуст, верните пустой список. Если один из элементов является пустой строкой, это недопустимо и должно быть обработано. ### **Решение** ### Java ``` import java.util.*; import java.util.stream.*; public class Shiritori { public static List<String> theGame(List<String> words) { if (words.isEmpty() || words.get(0).isEmpty()) return new ArrayList<String>(); int x = IntStream.range(1, words.size()) .filter( i -> words.get(i).isEmpty() || words.get(i-1).charAt(words.get(i-1).length()-1) != words.get(i).charAt(0) ) .findFirst() .orElse(words.size()); return words.subList(0,x); } } ``` ### JS ``` function shiritori(words) { if (!words.length || words[0] === '') return []; for (let i = 1; i < words.length; i++) if (words[i - 1].slice(-1) !== words[i][0]) return words.slice(0, i); return words; } ``` ## Задание 2 [Decimal to Factorial and Back](https://www.codewars.com/kata/54e320dcebe1e583250008fd) **5kyu** Coding decimal numbers with factorials is a way of writing out numbers in a base system that depends on factorials, rather than powers of numbers. In this system, the last digit is always 0 and is in base 0!. The digit before that is either 0 or 1 and is in base 1!. The digit before that is either 0, 1, or 2 and is in base 2!, etc. More generally, the nth-to-last digit is always 0, 1, 2, ..., n and is in base n!. Read more about it at: http://en.wikipedia.org/wiki/Factorial_number_system Example The decimal number 463 is encoded as "341010", because: `463 = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!` If we are limited to digits 0..9, the biggest number we can encode is 10!-1 (= 3628799). So we extend 0..9 with letters A..Z. With these 36 digits we can now encode numbers up to 36!-1 (= 3.72 × 1041) Task We will need two functions. The first one will receive a decimal number and return a string with the factorial representation. Note: the input number is at most a long. The second one will receive a string with a factorial representation and produce the decimal representation. Given numbers will always be positive. *Перевод* Кодирование десятичных чисел с помощью факториалов - это способ записи чисел в базовой системе, которая зависит от факториалов, а не от степеней чисел. В этой системе последняя цифра всегда 0 и имеет основание 0!. Цифра перед ним равна 0 или 1 и находится в базе 1!. Цифра перед ней равна 0, 1 или 2 и находится в базе 2!, и т. Д. В более общем случае, предпоследняя цифра всегда равна 0, 1, 2, ..., n и находится в базе n! . Подробнее об этом: http://en.wikipedia.org/wiki/Factorial_number_system. Пример Десятичное число 463 кодируется как «341010», потому что: ``` 463 = 3 × 5! + 4 × 4! + 1 × 3! + 0 × 2! + 1 × 1! + 0 × 0! ``` Если мы ограничены цифрами 0..9, наибольшее число, которое мы можем закодировать, будет 10! -1 (= 3628799). Итак, мы расширяем 0..9 буквами A..Z. С помощью этих 36 цифр мы теперь можем кодировать числа до 36! -1 (= 3,72 × 1041) Задача Нам потребуются две функции. Первый получит десятичное число и вернет строку с факториальным представлением. Примечание: входной номер не более длинный. Второй получит строку с факториальным представлением и произведет десятичное представление. Данные числа всегда будут положительными. ### **Решение** ### Java ``` public class Dec2Fact { public static String dec2FactString(long nb) { String res = ""; String retRes = ""; int previous = 36; while (previous != 1){ previous--; long fact = findFact(previous); int coeff = (int)Math.floor(1.0 *nb / fact); if (coeff <= 0 && res == "") continue; res += coeff + "x" + previous + "!+"; if (coeff>9){ char letter = (char)(coeff - 10 + 65);; retRes += letter; } else{ retRes += coeff; } nb -= coeff * fact; } return retRes+"0"; } public static long factString2Dec(String str) { long sumRes = 0; for (int i = str.length()-1; i >= 0; i--){ long currFact = findFact(str.length() - i - 1); sumRes += Character.getNumericValue(str.charAt(i)) * currFact; } return sumRes; } public static long findFact(long x){ long res = 1; for (int i = 1; i <= x; i++){ res*=i; } return res; } } ``` ### C++ ``` #include <string> #include <algorithm> #include <numeric> #include <cassert> class Dec2Fact { public: static std::string dec2FactString(long long nb); static long long factString2Dec(const std::string &str); }; char toBase36(int value) { assert((value >= 0) && (value < 36)); static char encoding[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; return encoding[value]; } int toBase10(char value) { assert(value >= '0'); if (value <= '9') return (value - '0'); assert((value >= 'A') && (value <= 'Z')); return value - 'A'; } std::string Dec2Fact::dec2FactString(long long nb) { using namespace std; string result; result.reserve(14); int factor = 1; // this assembles the result in reverse do { result += toBase36(nb % factor); nb /= factor; ++factor; } while (nb != 0); // reverse to correct the buildup reverse(begin(result), end(result)); return result; } long long Dec2Fact::factString2Dec(const std::string& str) { using namespace std; long long result = 0; string reversed(str); reverse(begin(reversed), end(reversed)); long long factor = 1; int i = 1; for (auto c : reversed) { result += factor * toBase10(c); factor *= i; ++i; } return result; } ``` ## 3. Защитила задачи вчерашнего дня