# 08/07/21 Евчук Даяна Во время пары: ## 1. Задача 1 [Boiled eggs](https://www.codewars.com/kata/52b5247074ea613a09000164) **7 kyu** You are the greatest chef on earth. No one boils eggs like you! Your restaurant is always full of guests, who love your boiled eggs. But when there is a greater order of boiled eggs, you need some time, because you have only one pot for your job. How much time do you need? Your Task Implement a function, which takes a non-negative integer, representing the number of eggs to boil. It must return the time in minutes (integer), which it takes to have all the eggs boiled. Rules you can put at most 8 eggs into the pot at once it takes 5 minutes to boil an egg we assume, that the water is boiling all the time (no time to heat up) for simplicity we also don't consider the time it takes to put eggs into the pot or get them out of it ``` Example (Input --> Output) 0 --> 0 5 --> 5 10 --> 10 ``` Вы величайший повар на земле. Никто не варит яйца так, как ты! Ваш ресторан всегда полон гостей, которым нравятся ваши вареные яйца. Но когда есть больший заказ вареных яиц, вам нужно время, потому что у вас есть только одна кастрюля для работы. Сколько времени вам нужно? Твое задание Реализуйте функцию, которая принимает неотрицательное целое число, представляющее количество яиц, которые нужно сварить. Он должен возвращать время в минутах (целое число), необходимое для варки всех яиц. Правила в кастрюлю можно положить не более 8 яиц за раз нужно 5 минут, чтобы сварить яйцо мы предполагаем, что вода все время кипит (не успевает нагреться) для простоты мы также не учитываем время, необходимое для того, чтобы положить яйца в кастрюлю или достать их из нее. ``` Пример (ввод -> вывод) 0 -> 0 5 -> 5 10 -> 10 ``` ### **Solution** ### C++ ``` int cookingTime(int eggs) { unsigned int minutes=0; if (eggs==0) return 0; while(eggs>=8) { eggs-=8; minutes+=5; } if (eggs>0) minutes+=5; return minutes; } ``` ### JS ``` function cookingTime(eggs) { if(eggs === 0) return 0; if(eggs <= 8) return 5; return Math.ceil(eggs / 8) * 5; } ``` ## 2. Задача 2 [ Number of Rectangles in a Grid]([https:](https://www.codewars.com/kata/556cebcf7c58da564a000045)) **7 kyu** Given a grid of size m x n, calculate the total number of rectangles contained in this rectangle. All integer sizes and positions are counted. ``` Examples: numberOfRectangles(3, 2) == 18 numberOfRectangles(4, 4) == 100 ``` Here is how the 3x2 grid works (Thanks to GiacomoSorbi for the idea): 1 rectangle of size 3x2: ``` [][][] [][][] ``` 2 rectangles of size 3x1: ``` [][][] ``` 4 rectangles of size 2x1: ``` [][] ``` 2 rectangles of size 2x2 ``` [][] [][] ``` 3 rectangles of size 1x2: ``` [] [] ``` 6 rectangles of size 1x1: ``` [] ``` As you can see (1 + 2 + 4 + 2 + 3 + 6) = 18, and is the solution for the 3x2 grid. There is a very simple solution to this! *Перевод* Учитывая размер сетки m x n, вычислите общее количество прямоугольников, содержащихся в этом прямоугольнике. Подсчитываются все целые размеры и позиции. ``` Examples: numberOfRectangles(3, 2) == 18 numberOfRectangles(4, 4) == 100 ``` Вот как работает сетка 3x2 (спасибо GiacomoSorbi за идею): 1 прямоугольник размером 3х2: ``` [][][] [][][] ``` 2 прямоугольника размером 3х1: ``` [][][] ``` 4 прямоугольника размером 2х1: ``` [][] ``` 2 прямоугольника размером 2х2 ``` [][] [][] ``` 3 прямоугольника размером 1x2: ``` [] [] ``` 6 прямоугольников размером 1x1: ``` [] ``` Как видите, (1 + 2 + 4 + 2 + 3 + 6) = 18, и это решение для сетки 3x2. Есть очень простое решение! ### Java ``` public class Solution { public static int numberOfRectangles(int m, int n) { int answer = ( (m * (m + 1) ) * ( n * (n + 1) ) ) / 4; return answer; } } ``` ### JS ``` function numberOfRectangles(m, n) { let answer = ( (m * (m + 1) ) * ( n * (n + 1) ) ) / 4; return answer; } ``` ## 3. Задача 3 [Triangle number check ](https://www.codewars.com/kata/557e8a141ca1f4caa70000a6 ) **6 kyu** A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle: ``` 1 2 3 4 5 6 ``` 8 is not a triangle number because 8 objects do not form an equilateral triangle: ``` 1 2 3 4 5 6 7 8 ``` In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n. Your task: Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers, including non-number types, are not triangle numbers). You are encouraged to develop an effective algorithm: test cases include really big numbers. Assumptions: You may assume that the given input, if it is a number, is always positive. Notes: 0 and 1 are triangle numbers. *Перевод* Число треугольника - это число, в котором n объектов образуют равносторонний треугольник (это немного сложно объяснить). Например, 6 - это число треугольника, потому что вы можете расположить 6 объектов в равносторонний треугольник: ``` 1 2 3 4 5 6 ``` 8 не является числом треугольника, потому что 8 объектов не образуют равносторонний треугольник: ``` 1 2 3 4 5 6 7 8 ``` Другими словами, n-е число треугольника равно сумме n натуральных чисел от 1 до n. Твое задание: Проверьте, является ли данный ввод допустимым числом треугольника. Верните true, если это так, и false, если это не так (обратите внимание, что любые нецелые числа, включая нечисловые типы, не являются числами треугольника). Вам предлагается разработать эффективный алгоритм: тестовые примеры включают действительно большие числа. Предположения: Вы можете предположить, что данный ввод, если это число, всегда положительный. Заметки: 0 и 1 - числа треугольника. ### **Solution** ### JS ``` function isTriangleNumber(number) { var n = (Math.sqrt(8 * number+1) - 1) / 2 return Math.ceil(n) === n } ``` ### Java ``` public class TriangleNumbers { public static Boolean isTriangleNumber(long number) { double n = ( Math.sqrt (8 * number+1) - 1) / 2; return Math.ceil(n) == n; } } ``` ## 4. Задача 4 [Presents]( https://www.codewars.com/kata/598d6fd5b383eda05c000046) **7 kyu** Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited N his friends there. If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to N. Petya remembered that a friend number i gave a gift to a friend number j. He also remembered that each of his friends received exactly one gift. Now Petya wants to know for each friend i the number of a friend who has given him a gift. Input Input contains array with N integers: the i-th number is the number of the friend who was given a present by friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves. Output Return array with N integers: the i-th number should equal the number of the friend who gave a gift to friend number i. Examples ``` [2, 3, 4, 1] => [4, 1, 2, 3] [1, 3, 2] => [1, 3, 2] [1, 2] => [1, 2] ``` First example step-by-step explanation (note: the explanation uses 1-based indexing to make the correspondence with friend-numbering clearer): The friend 1 gave gift to the friend 2 (a[1] == 2) - this means that in the output array number 1 is at position 2 : [_, 1, _, _]. The friend 2 gave gift to the friend 3 (a[2] == 3) - this means that in the output array number 2 is at position 3 : [_, 1, 2, _]. The friend 3 gave gift to the friend 4 (a[3] == 4) - this means that in the output array number 3 is at position 4 : [_, 1, 2, 3]. The friend 4 gave gift to the friend 1 (a[4] == 1) - this means that in the output array number 4 is at position 1 : [4, 1, 2, 3]. Маленький Петя очень любит подарки. Недавно мама подарила ему новый ноутбук на Новый год. Он сразу решил подарить это кому-нибудь, как что может быть приятнее, чем дарить кому-то подарки. И по этому поводу он устроил у себя новогоднюю вечеринку и пригласил N своих друзей. Если есть что-то, что Пете больше нравится, чем получение подарков, так это то, как другие дарят подарки кому-то другому. Таким образом, он благополучно спрятал ноутбук до следующего Нового года и решил посмотреть, как его друзья обмениваются подарками, пока он не участвует в процессе. Он пронумеровал всех своих друзей целыми числами от 1 до N. Петя вспомнил, что друг номер i подарил другу номер j. Он также вспомнил, что каждый из его друзей получил ровно по одному подарку. Теперь Петя хочет узнать для каждого друга i номер друга, сделавшего ему подарок. Вход Вход содержит массив из N целых чисел: i-е число - это номер друга, которому подарил подарок друг номер i. Гарантируется, что каждый друг получил ровно один подарок. Возможно, некоторые друзья не разделяют идеи Пети дарить кому-то подарки. Эти друзья подарили себе подарки. Выход Возвращает массив с N целыми числами: i-е число должно равняться номеру друга, сделавшего подарок другу номер i. Примеры ``` [2, 3, 4, 1] => [4, 1, 2, 3] [1, 3, 2] => [1, 3, 2] [1, 2] => [1, 2] ``` Первый пример пошагового объяснения (примечание: в объяснении используется индексирование на основе 1, чтобы сделать переписку с нумерацией друзей более понятной): Друг 1 сделал подарок другу 2 (a [1] == 2) - это означает, что в выходном массиве номер 1 находится на позиции 2: [_, 1, _, _]. Друг 2 сделал подарок другу 3 (a [2] == 3) - это означает, что в выходном массиве номер 2 находится на позиции 3: [_, 1, 2, _]. Друг 3 сделал подарок другу 4 (a [3] == 4) - это означает, что в выходном массиве номер 3 находится на позиции 4: [_, 1, 2, 3]. Друг 4 подарил другу 1 подарок (a [4] == 1) - это означает, что в выходном массиве номер 4 находится на позиции 1: [4, 1, 2, 3] ### **Solution** ### JS ``` function presents(a){ R = []; for (var i=0; i<a.length; i++) R.push(1+a.indexOf(i+1)); // Метод indexOf() возвращает первый индекс, по которому данный элемент может быть найден в массиве или -1, если такого индекса нет. return R; } ``` ### Java ``` public class Solution { public static int function(int a) { int R[]; for (int i=0; i<a.length; i++) R.push(1+a.indexOf(i+1)); return R; } } ```