# Учебная практика. Вторник 06.07.2021. Чачко Натан Леонидович ## 1. Задача [Miles per gallon to kilometers per liter](https://www.codewars.com/kata/555bfd6f9f9f52680f0000c5/train/java), сложность 8 kyu Sometimes, I want to quickly be able to convert miles per imperial gallon into kilometers per liter. Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input). Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5. Some useful associations relevant to this kata: 1 Imperial Gallon = 4.54609188 litres 1 Mile = 1.609344 kilometres. Иногда мне нужно быстро преобразовать мили на британский галлон в километры на литр. Создайте приложение, которое будет отображать количество километров на литр (вывод) на основе количества миль на британский галлон (ввод). Обязательно округлите результат до двух десятичных знаков. Если ответ заканчивается на 0, его следует округлить без 0. Таким образом, вместо 5,50 мы должны получить 5,5. Некоторые полезные ассоциации, относящиеся к этому ката: 1 британский галлон = 4,54609188 литров 1 миля = 1,609344 километра. ### Решение на языке **С++**. ```c= #include <math.h> double converter(int mpg) { const double imperial_gallon_to_litre = 4.54609188; const double mile_to_km = 1.609344; double result = mpg * mile_to_km / imperial_gallon_to_litre; return round(result*100) / 100.00; } ``` ### Решение на языке **Java**. ```java= public class Converter { public static float mpgToKPM(final float mpg) { float imperial_gallon_to_litre = 4.54609188f; float mile_to_km = 1.609344f; float result = mpg * mile_to_km / imperial_gallon_to_litre; return Math.round(result*100) / 100.00f; } } ``` ## 2. Задача [Do I get a bonus?](https://www.codewars.com/kata/56f6ad906b88de513f000d96), сложность 8 kyu It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money? Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean. If bonus is true, the salary should be multiplied by 10. If bonus is false, the fatcat did not make enough money and must receive only his stated salary. Return the total figure the individual will receive as a string prefixed with "£" (= `"\u00A3"`, JS, Go, Java and Julia), "$" (C#, C++, Ruby, Clojure, Elixir, PHP, Python, Haskell and Lua) or "¥" (Rust). Бонусное время в большом городе! Толстяки в нетерпении потирают лапы... но кто заработает больше всего? Создайте функцию, которая принимает два аргумента (зарплата, бонус). Зарплата будет целым числом, а бонус - логическим. Если бонус верен, зарплату следует умножить на 10. Если бонус неверен, толстый кот не заработал достаточно денег и должен получать только свою заявленную зарплату. Возвращает общую цифру, которую получит человек, в виде строки с префиксом «£» (= `"\u00A3"`, JS, Go, Java и Julia), «$» (C #, C ++, Ruby, Clojure, Elixir, PHP, Python, Haskell и Lua) или «¥» (Rust). ### Решение на языке **С++**. ```c= #include<string> using namespace std; string bonus_time(int salary, bool bonus){ return "$" + to_string(salary * (bonus ? 10 : 1)); } ``` ### Решение на языке **Java**. ```java= public class Kata{ public static String bonusTime(final int salary, final boolean bonus) { return "\u00A3" + String.valueOf(salary * (bonus ? 10 : 1)); } } ``` ## 3. Задача [Total amount of points](https://www.codewars.com/kata/5bb904724c47249b10000131), сложность 8 kyu Our football team finished the championship. The result of each match look like "x:y". Results of all matches are recorded in the collection. For example: `["3:1", "2:2", "0:1", ...]` Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match: * if x>y --- 3 points * if x<y --- 0 point * if x=y --- 1 point Notes: * there are 10 matches in the championship * 0 <= x <= 4 * 0 <= y <= 4 Наша футбольная команда завершила чемпионат. Результат каждого совпадения выглядит как «x: y». Результаты всех матчей заносятся в сборник. Например: `[« 3: 1 »,« 2: 2 »,« 0: 1 », ...]` Напишите функцию, которая берет такой сбор и подсчитывает очки нашей команды в чемпионате. Правила подсчета очков за каждый матч: * если x> y --- 3 балла * если x <y --- 0 баллов * если x = y --- 1 балл Заметки: * в чемпионате 10 матчей * 0 <= х <= 4 * 0 <= у <= 4 ### Решение на языке **С++**. ```c= int points(const std::array<std::string, 10>& games) { int sum = 0; for (const std::string& a : games) sum += a[0] > a[2] ? 3 : a[0] == a[2] ? 1 : 0; return sum; } ``` ### Решение на языке **Java**. ```java= public class TotalPoints { public static int points(String[] games) { int sum = 0; for(String s:games) sum += s.charAt(0) > s.charAt(2) ? 3 : s.charAt(0) == s.charAt(2) ? 1 : 0; return sum; } } ``` ## 4. Задача [Create palindrome](https://www.codewars.com/kata/5b7bd90ef643c4df7400015d), сложность 7 kyu Consider the string ```"adfa"``` and the following rules: >a) each character MUST be changed either to the one before or the one after in alphabet. b) "a" can only be changed to "b" and "z" to "y". From our string, we get: > "adfa" -> ["begb","beeb","bcgb","bceb"] > >Here is another example: "bd" -> ["ae","ac","ce","cc"] > > --We see that in each example, one of the outcomes is a palindrome. That is, "beeb" and "cc". You will be given a lowercase string and your task is to return `True` if at least one of the outcomes is a palindrome or `False` otherwise. Обратите внимание на строку `adfa` и следующие правила: > а) каждый символ ДОЛЖЕН быть изменен либо на предыдущий, либо на следующий в алфавите. б) «a» можно заменить только на «b», а «z» - на «y». Из нашей строки мы получаем: > "adfa" -> ["Beeb", "beeb", "bcgb", "bceb"] > > Вот еще один пример: "bd" -> ["ae", "ac", "ce", "cc"] > > --- Мы видим, что в каждом примере одним из результатов является палиндром. То есть «beeb» и «сс». Вам будет предоставлена строка в нижнем регистре, и ваша задача - вернуть `True`, если хотя бы один из результатов является палиндромом, или `False` в противном случае. ### Решение на языке **С++**. ```c= bool solve(std::string s) { int x = int(s.size()); for (int i = 0; i < x / 2; i++) { if (s[i] < s[x - i - 1] && s[i] + 1 != s[x - i - 1] - 1) return false; if (s[i] > s[x - i - 1] && s[i] - 1 != s[x - i - 1] + 1) return false; } return true; } ``` ### Решение на языке **Java**. ```java= class Solution{ public static boolean solve(String st) { System.out.println(st); for (int i = 0, j = st.length() - 1; i < j; i++, j--) { if (st.charAt(i) == st.charAt(j) || Math.abs(st.charAt(i) - st.charAt(j)) == 2) continue; return false; } return true; } } ``` ## 5. Задача [Numbers in strings](https://www.codewars.com/kata/59dd2c38f703c4ae5e000014), сложность 7 kyu In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings. В этом Ката вам будет дана строка, состоящая из строчных букв и цифр. Ваша задача --- сравнить группы чисел и вернуть наибольшее число. У чисел не будет ведущих нулей. Например, `resolve (" gh12cdy695m1 ") = 695`, потому что это наибольшая из всех групп чисел. ### Решение на языке **С++**. ```c= int solve(std::string s){ int r = 0; int t = 0; for (auto c:s) { if (isdigit(c)) t = t * 10 + c - 48; else { if (t > r) r = t; t = 0; } } return std::max(r,t); } ``` ### Решение на языке **Java**. ```java= import java.util.*; class Solution{ public static int solve(String s){ return Arrays .stream(s.replaceAll("[a-zA-Z]+", " ").trim().split(" ")) .mapToInt(x -> Integer.parseInt(x)) .max() .getAsInt(); } } ``` Решение на **Jav'e** получилось более кратким за счет удобных функций **Stream Api**, которые позволили быстро замений все буквы в строке на пробелы, разделить строку на числа по этим пробелам и выбрать среди всех чисел наибольшее. На **С++** я проверял каждый символ строки на то, является ли он цифрой. Если да, то шел дальше и из последовательности цифр составлял число (цикл пока не встретится буква) и потом сравнивал полученные числа между собой. ## 6. Задача [The Speed of Letters](https://www.codewars.com/kata/5fc7caa854783c002196f2cb), сложность 7 kyu Given a string as input, return a new string with each letter pushed to the right by its respective index in the alphabet. We all know that `A` is a slow and `Z` is a fast letter. This means that `Z` gets shifted to the right by 25 spaces, A doesn't get shifted at all, and B gets shifted by 1 space. You can assume the following things about your input: It will only contain uppercase letters from `A` to `Z`, no whitespaces or punctuation; Input strings will not exceed 100 characters (although your output string might!) Note that if 2 or more letters fall onto the same space after shifting, the latest character will be used. For example: `"BA" -> "A"`. ### **Examples** ``` "AZ" --> "A Z" "ABC" --> "A B C" "ACE" --> "A C E" "CBA" --> " A" "HELLOWORLD" --> " E H DLL OLO R W" ``` Учитывая строку в качестве входных данных, верните новую строку с каждой буквой, сдвинутой вправо по соответствующему индексу в алфавите. Все мы знаем, что `А` - это медленная, а `Z` - быстрая буква. Это означает, что `Z` сдвигается вправо на 25 пробелов, `A` вообще не сдвигается, а `B` сдвигается на 1 пробел. Вы можете предположить следующее о вашем вводе: Он будет содержать только прописные буквы от `A` до `Z`, без пробелов и знаков препинания; Строки ввода не будут превышать 100 символов (хотя ваша строка вывода может!) Обратите внимание, что если 2 или более букв попадают на одно и то же место после сдвига, будет использоваться последний символ. Например: `"BА" -> "А"`. ### **Примеры** ``` "AZ" --> "A Z" "ABC" --> "A B C" "ACE" --> "A C E" "CBA" --> " A" "HELLOWORLD" --> " E H DLL OLO R W" ``` ### Решение на языке **С++**. ```c= std::string speedify(const std::string& input) { std::string res; for(size_t i = 0; i < input.size(); ++i) { const char& c = input.at(i); const size_t idx = c - 'A' + i; if(res.size() < idx + 1) res += std::string(idx + 1 - res.size(), ' '); res[idx] = c; } return res; } ``` ### Решение на языке **Java**. ```java= import java.util.Arrays; public class Kata { public static String speedify(final String input) { char[] c = input.toCharArray(); int max = -1; for(int i=0; i<c.length; i++) { max = Math.max(max, i+c[i]-'A'); } char[] result = new char[max+1]; Arrays.fill(result, ' '); for(int i=0; i<c.length; i++) { result[i+c[i]-'A'] = c[i]; } return new String(result); } } ``` ## 7. Задача [ORing arrays](https://www.codewars.com/kata/5ac5e9aa3853da25d9000102), сложность 7 kyu It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary OR each matching element of two given arrays (or lists, if you do it in Python; vectors in C++) of integers and give the resulting ORed array [starts to sound like a tonguetwister, doesn't it?]. If one array is shorter than the other, use the optional third parameter (defaulted to `0`) to `OR` the unmatched elements. ### **For example**: ```orArrays([1,2,3],[1,2,3]) == [1,2,3] orArrays([1,2,3],[4,5,6]) == [5,7,7] orArrays([1,2,3],[1,2]) == [1,2,3] orArrays([1,2],[1,2,3]) == [1,2,3] orArrays([1,2,3],[1,2,3],3) == [1,2,3] ``` Все началось с обсуждения с другом, который не совсем понял какой-либо способ установки значений по умолчанию, но я подумал, что идея была достаточно крутой для начинающего ката: двоичное ИЛИ каждого совпадающего элемента двух заданных массивов (или списков, если вы это делаете это в Python; векторы в C++) целых чисел и дать результирующий массив, объединенный *ИЛИмассив* [начинает звучать как скороговорка, не так ли?]. Если один массив короче другого, используйте необязательный третий параметр (по умолчанию `0`) для `OR` несопоставленных элементов. ### **Пример**: ```orArrays([1,2,3],[1,2,3]) == [1,2,3] orArrays([1,2,3],[4,5,6]) == [5,7,7] orArrays([1,2,3],[1,2]) == [1,2,3] orArrays([1,2],[1,2,3]) == [1,2,3] orArrays([1,2,3],[1,2,3],3) == [1,2,3] ``` ### Решение на языке **С++**. ```c= #include <vector> std::vector<int> orArrays(const std::vector<int>& arr1, const std::vector<int>& arr2, int def = 0){ std::vector<int> out; for(size_t i = 0; i < arr1.size() || i < arr2.size(); i++) { int num1 = i < arr1.size() ? arr1[i] : def; int num2 = i < arr2.size() ? arr2[i] : def; out.push_back(num1 | num2); } return out; } ``` *001 = 1 010 = 2 011 = 3 100 = 4 100 + 001 = 101 = 5 011 + 110 = 111* ### Решение на языке **Java**. ```java= public class OrArrays { public static int[] orArrays(int[] arr1, int[] arr2) { return orArrays(arr1, arr2, 0); } public static int[] orArrays(int[] arr1, int[] arr2, int defaultValue) { int length = Math.max(arr1.length, arr2.length); int[] r = new int[length]; for (int i = 0; i < length; i++) { int v1 = i < arr1.length ? arr1[i] : defaultValue; int v2 = i < arr2.length ? arr2[i] : defaultValue; r[i] = v1 | v2; } return r; } } ``` К сожалению, в языке **Java** нельзя использовать параметр со значением по умолчанию прямо в конструкторе, в отличие от **С++**, поэтому я использовал перегрузку метода `orArrays()` для имитации параметров по умолчанию: ```java=2 public static int[] orArrays(int[] arr1, int[] arr2) { return orArrays(arr1, arr2, 0); } public static int[] orArrays(int[] arr1, int[] arr2, int defaultValue) { ``` ## 8. Задача [Floating-point Approximation (I)](https://www.codewars.com/kata/58184387d14fc32f2b0012b2), сложность 6 kyu Consider the function `f: x -> sqrt(1 + x) - 1 at x = 1e-15.` We get: `f(x) = 4.44089209850062616e-16` or something around that, depending on the language. This function involves the subtraction of a pair of similar numbers when x is near 0 and the results are significantly erroneous in this region. Using `pow` instead of `sqrt` doesn't give better results. A "good" answer is `4.99999999999999875... * 1e-16`. Can you modify f(x) to give a good approximation of f(x) in the neighborhood of 0? Рассмотрим функцию `f: x -> sqrt (1 + x) - 1 при x = 1e-15.` Мы получаем:` f (x) = 4.44089209850062616e-16` или что-то вроде этого, в зависимости от языка. Эта функция включает вычитание пары одинаковых чисел, когда x близко к 0, и результаты в этой области значительно ошибочны. Использование pow вместо sqrt не дает лучших результатов. "Хороший" ответ - `4.99999999999999875 ... * 1e-16`. Можете ли вы изменить f(x), чтобы получить хорошее приближение к f(x) в окрестности 0? ### Решение на языке **С++**. ```c= #include <cmath> namespace App { double f(double x) { return std::expm1(std::log1p(x) / 2); } } ``` ### Решение на языке **Java**. ```java= interface ApproxFloat { static double f(double x) { return Math.expm1(Math.log1p(x) / 2); } } ``` Если преобразовать формулу из условия, то получим следующее: $\sqrt{x + 1} - 1 = e^{ln(1 + x) \over 2}-1$ Использовал функции **std::expm1()** и **Math.expm1()** соответсвенно, так как они вычисляют значение $e^x -1$ в окрестности 0 намного лучше функции **exp(x)**, и функцию **log1p()** для вычисления $ln(1 + x)$. Ссылки на документацию [по Java](https://www.tutorialspoint.com/java/lang/math_expm1.htm) и [по С++](https://en.cppreference.com/w/cpp/numeric/math/expm1). ## 9. Задача [Sums of Parts](https://www.codewars.com/kata/5ce399e0047a45001c853c2b/java), сложность 6 kyu Let us consider this example (array written in general format): `ls = [0, 1, 3, 6, 10]` Its following parts: ``` ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = [] ``` The corresponding sums are (put together in a list): `[20, 20, 19, 16, 10, 0]` The function `parts_sum`s (or its variants in other languages) will take as parameter a list `ls` and return a list of the sums of its parts as defined above. ### Other Examples: ``` ls = [1, 2, 3, 4, 5, 6] parts_sums(ls) -> [21, 20, 18, 15, 11, 6, 0] ls = [744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358] parts_sums(ls) -> [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0] ``` Рассмотрим этот пример (массив, записанный в общем формате): `ls = [0, 1, 3, 6, 10]` Его следующие части: ``` ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = [] ``` Соответствующие суммы (объединяются в список): `[20, 20, 19, 16, 10, 0]` Функция `parts_sums` (или ее варианты на других языках) примет в качестве параметра список` ls` и вернет список сумм своих частей, как определено выше. ### Другие примеры: ``` ls = [1, 2, 3, 4, 5, 6] parts_sums(ls) -> [21, 20, 18, 15, 11, 6, 0] ls = [744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358] parts_sums(ls) -> [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0] ``` ### Решение на языке **С++**. ```c= #include<vector> std::vector<unsigned long long> partsSum(const std::vector<unsigned long long>& ls){ size_t n = ls.size(); std::vector<unsigned long long> sums(n + 1, 0); unsigned long long m = 0; while (n--){ m += ls[n]; sums[n] = m; } return sums; } ``` ### Решение на языке **Java**. ```java= class SumParts { public static int[] sumParts(int[] ls) { int n = ls.length; int[] sums = new int[n+1]; int m = 0; while (n>0){ n--; m += ls[n]; sums[n] = m; } return sums; } } ``` ## 10. Задача [Who likes it?](https://www.codewars.com/kata/5266876b8f4bf2da9b000362), сложность 6 kyu You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a `function likes :: [String] -> String`, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples: ``` likes {} // must be "no one likes this" likes {"Peter"} // must be "Peter likes this" likes {"Jacob", "Alex"} // must be "Jacob and Alex like this" likes {"Max", "John", "Mark"} // must be "Max, John and Mark like this" likes {"Alex", "Jacob", "Mark", "Max"} // must be "Alex, Jacob and 2 others like this" ``` Вы, наверное, знаете систему «лайков» по Facebook и другим страницам. Люди могут "лайкать" сообщения в блогах, изображения или другие предметы. Мы хотим создать текст, который должен отображаться рядом с таким элементом. Реализуйте функцию `likes :: [String] -> String`, которая должна принимать входной массив, содержащий имена людей, которым нравится элемент. Он должен возвращать отображаемый текст, как показано в примерах: ``` likes {} // должно быть "no one likes this" likes {"Peter"} // должно быть"Peter likes this" likes {"Jacob", "Alex"} // должно быть "Jacob and Alex like this" likes {"Max", "John", "Mark"} // должно быть"Max, John and Mark like this" likes {"Alex", "Jacob", "Mark", "Max"} // должно быть "Alex, Jacob and 2 others like this" ``` ### Решение на языке **С++**. ```c= std::string likes(const std::vector<std::string> &names){ if(names.size() == 0) return "no one likes this"; if(names.size() == 1) return names[0] + " likes this"; if(names.size() == 2) return names[0] + " and " + names[1] + " like this"; if(names.size() == 3) return names[0] + ", " + names[1] + " and " + names[2] + " like this"; return names[0] + ", " + names[1] + " and " + std::to_string(names.size()-2) + " others like this"; } ``` ### Решение на языке **Java**. ```java= class Solution { public static String whoLikesIt(String... names) { if(names.length == 0) return "no one likes this"; if(names.length == 1) return names[0] + " likes this"; if(names.length == 2) return names[0] + " and " + names[1] + " like this"; if(names.length == 3) return names[0] + ", " + names[1] + " and " + names[2] + " like this"; return names[0] + ", " + names[1] + " and " + (names.length-2) + " others like this"; } } ``` ## 11. Задача [Decode the Morse code](https://www.codewars.com/kata/54b724efac3d5402db00065e/train/cpp), сложность 6 kyu In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superseded by voice and digital data communication channels, it still has its use in some applications around the world. The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter `A` is coded as `·−`, letter `Q` is coded as `−−·−`, and digit 1 is coded as `·−−−−`. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message `HEY JUDE` in Morse code is `···· · −·−− ·−−− ··− −·· ·`. NOTE: Extra spaces before or after the code have no meaning and should be ignored. In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as `···−−−···`. These special codes are treated as single special characters, and usually are transmitted as separate words. Your task is to implement a function that would take the morse code as input and return a decoded human-readable string. ### For example: ``` decodeMorse('.... . -.-- .--- ..- -.. .') //should return "HEY JUDE" ``` NOTE: For coding purposes you have to use ASCII characters `.` and `-`, not Unicode characters. The Morse code table is preloaded for you as a dictionary, feel free to use it: C++: `MORSE_CODE['.--']` Java: `MorseCode.get(".--")` В этом ката вы должны написать простой декодер кода Морзе. Хотя код Морзе в настоящее время в основном вытеснен каналами передачи голоса и цифровых данных, он все еще используется в некоторых приложениях по всему миру. Код Морзе кодирует каждый символ как последовательность «точек» и «тире». Например, буква `A` кодируется как `· −`, буква `Q` кодируется как `−− · −`, а цифра 1 кодируется как `· −−−−`. В азбуке Морзе регистр не учитывается, традиционно используются заглавные буквы. Когда сообщение написано азбукой Морзе, для разделения кодов символов используется один пробел, а для разделения слов используются 3 пробела. Например, сообщение `HEY JUDE` в азбуке Морзе - это `···· · - · −− · −−− ·· - - ·· ·`. ПРИМЕЧАНИЕ. Лишние пробелы до или после кода не имеют значения, и их следует игнорировать. Помимо букв, цифр и некоторых знаков препинания, есть несколько специальных служебных кодов, наиболее известным из которых является международный сигнал бедствия SOS (который впервые был выпущен компанией Titanic), который кодируется как `··· −−− ··· · `. Эти специальные коды рассматриваются как отдельные специальные символы и обычно передаются как отдельные слова. Ваша задача - реализовать функцию, которая будет принимать код Морзе в качестве входных данных и возвращать декодированную удобочитаемую строку. ### Например: ``` decodeMorse ('..... -.-- .--- ..- - ...') //должно вернуть "HEY JUDE" ``` ### Решение на языке **С++**. ```c= #include <algorithm> #include <cctype> #include <QStringList> //????? file not found #include <locale> std::string decodeMorse(std::string morseCode) { trim(morseCode); std::string decoded = ""; QStringList list1 = morseCode.split(" "); for( auto p : list1.split(" +")){ //????? decoded += MORSE_CODE[ p ]; } decoded += ' '; return trim(decoded); } ``` ### Решение на языке **Java**. ```java= public class MorseCodeDecoder { public static String decode(String morseCode) { String result = ""; for(String word : morseCode.trim().split(" ")) { for(String letter : word.split("\\s+")) { result += MorseCode.get(letter); } result += ' '; } return result.trim(); } } ``` На **Jav'e**, в принципе, решение очевидное. Функции `trim()` и `split()` позволяют быстро разделить строку по пробелам на отдельные слова и символы. Регулярное выражение `\\s+` — соответствует последовательности из одного или нескольких символов пробела. В языке **С++** я, к сожалению, не нашел похожей функции среди стандартных. Но наткнулся на библиотеку [QString](https://doc.qt.io/qt-5/qstring.html#split), которая в теории должна помочь в решении данной задачи. Но почему-то компилятор выдает ошибку. Подозреваю, что нужно локально устанавливать фреймворк ***Qt*** для работы с этими функциями. > **Заключение:** В целом продуктивный день. За время занятия успел решить и защитить 7 задач. > Обратил внимание на то, что, переписывая код с одного языка программирования на другой, начал замечать, в каких местах можно улучшить сам алгоритм, в каких местах сделать код короче и/или более читаемым. Считаю, что это несомненный плюс. > Легкие задачки все поразбирали, пришлось поднимать уровень. Это тоже неплохо, заставляет немного поднапрячься, но ведь для этого мы и практикуемся :) > Тяжело в учении — легко в бою.