# Учебная практика 2021. Вторник 6.07.2021. Федяева Евгения Игоревна.
Присутствовала на онлайн-лекции, 6 задач защитила на практике.
1. [Find the next perfect square]() 7kyu
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is non-negative.
Возможно, вы знаете несколько довольно больших идеальных квадратов. А как насчет СЛЕДУЮЩЕГО?
Завершите метод findNextSquare, который находит следующий целочисленный полный квадрат после переданного в качестве параметра. Напомним, что полный квадрат - это целое число n такое, что sqrt (n) также является целым числом.
Если параметр сам по себе не является точным квадратом, следует вернуть -1. Вы можете предположить, что параметр неотрицательный.
Решение на С++
```c++=
#include <cmath>
long int findNextSquare(long int sq)
{
if(sq == floor(sqrt(sq))*floor(sqrt(sq)))
{
double r = sqrt(sq);
return (r+1)*(r+1);
} else return -1;
}
```
Решение на Java
```java=
public class NumberFun
{
public static long findNextSquare(long sq)
{
if(sq == Math.floor(Math.sqrt(sq))*Math.floor(Math.sqrt(sq)))
{
double r = Math.sqrt(sq);
return (long)(r+1)*(long)(r+1);
} else return -1;
}
}
```
2. [Century from Year](https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097/solutions/cpp) 8kyu
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.
Task :
Given a year, return the century it is in.
Первый век охватывает период с 1 года до 100 года включительно, второй - с 101 года по 200 год включительно и т. Д.
Задача :
Учитывая год, верните век, в котором он находится.
Решение на С++
```c++=
int centuryFromYear(int year)
{
if(year%100 == 0)
return year/100 ;
else
return year/100 + 1;
}
```
Решение на Java
```java=
public class Solution
{
public static int century(int number)
{
if(number%100 == 0)
return number/100 ;
else
return number/100 + 1;
}
}
```
3. [Expressions Matter](https://www.codewars.com/kata/5ae62fcf252e66d44d00008e) 8kyu
Given three integers a ,b ,c, return the largest number obtained after inserting the following operators and brackets: +, *, ()
In other words , try every combination of a,b,c with * + () , and return the Maximum Obtained
Даны три целых числа a, b, c, вернуть наибольшее число, полученное после вставки следующих операторов и скобок: +, *, ()
Другими словами, попробуйте каждую комбинацию a, b, c с * + () и верните максимальное полученное значение.
Решение на С++
```c++=
unsigned short int expressionsMatter (unsigned short int a , unsigned short int b , unsigned short int c)
{
int max = ((a+b+c) > (a*b*c) ? (a+b+c) : (a*b*c));
max = (max > (a+b*c) ? max : (a+b*c));
max = (max > (a*b+c) ? max : (a*b+c));
max = (max > ((a+b)*c) ? max : ((a+b)*c));
max = (max > (a*(b+c)) ? max : (a*(b+c)));
return max ;
}
```
Решение на Java
```java=
public class Kata
{
public static int expressionsMatter(int a, int b, int c)
{
int max = ((a+b+c) > (a*b*c) ? (a+b+c) : (a*b*c));
max = (max > (a+b*c) ? max : (a+b*c));
max = (max > (a*b+c) ? max : (a*b+c));
max = (max > ((a+b)*c) ? max : ((a+b)*c));
max = (max > (a*(b+c)) ? max : (a*(b+c)));
return max ;
}
}
```
4. [Count the Monkeys](https://www.codewars.com/kata/56f69d9f9400f508fb000ba7) 8kyu
You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.
As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero.
Вы ведете сына в лес, чтобы увидеть обезьян. Вы знаете, что там есть определенное число (n), но ваш сын слишком молод, чтобы просто оценить полное число, он должен начать считать их с 1.
Как хороший родитель, вы будете сидеть и считать вместе с ним. Учитывая число (n), заполните массив всеми числами до этого числа включительно, но исключая ноль.
Решение на С++
```c++=
#include <vector>
std::vector<int> MonkeyCount(int n)
{
std::vector<int> monkeys(n);
for(int i = 0; i < n; i++)
monkeys[i] = i+1;
return monkeys;
}
```
Решение на Java
```java=
public class MonkeyCounter
{
public static int[] monkeyCount(final int n)
{
int[] monkeys = new int[n];
for(int i = 0; i < n; i++)
monkeys[i] = i+1;
return monkeys;
}
}
```
5. [Form the Largest](https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e) 7kyu
Given a number , Return _The Maximum number _ could be formed from the digits of the number given .
Notes
Only Natural numbers passed to the function , numbers Contain digits [0:9] inclusive
Digit Duplications could occur , So also consider it when forming the Largest
Для данного числа вернуть _Максимальное число _ может быть образовано из цифр данного числа.
Заметки
В функцию передаются только натуральные числа, числа содержат цифры [0:9] включительно
Могут произойти дублирования цифр, поэтому также учитывайте это при формировании наибольшего
Решение на С++
```c++=
using namespace std;
long long int maxNumber (long long int number)
{
int digits[10] = {0};
int tmp = number;
while(tmp > 0)
{
digits[tmp%10]++;
tmp /= 10;
}
long long int result = 0; int coef = 1;
for(int i = 0; i < 10; i++)
{
while (digits[i] > 0)
{
result += (i*coef);
digits[i]--;
coef = coef*10;
}
}
return result;
}
```
Решение на Java
```java=
public class Solution
{
public static long maxNumber(long n)
{
int[] digits = new int[10];
for(int i = 0; i < 10; i++) digits[i] = 0;
long tmp = n;
while(tmp > 0)
{
digits[(int)tmp%10]++;
tmp /= 10;
}
long result = 0; int coef = 1;
for(int i = 0; i < 10; i++)
{
while (digits[i] > 0)
{
result += (long)(i*coef);
digits[i]--;
coef = coef*10;
}
}
return result;
}
}
```
6. [Split by Value](https://www.codewars.com/kata/5a433c7a8f27f23bb00000dc) 7kyu
For an integer k rearrange all the elements of the given array in such way, that:
all elements that are less than k are placed before elements that are not less than k;
all elements that are less than k remain in the same order with respect to each other;
all elements that are not less than k remain in the same order with respect to each other.
Для целого числа k переставить все элементы данного массива так, чтобы:
все элементы меньше k помещаются перед элементами не меньше k;
все элементы меньше k остаются в том же порядке относительно друг друга;
все элементы, которые не меньше k, остаются в том же порядке относительно друг друга.
Решение на С++
```c++=
std::vector<int> split_by_value(int k, std::vector<int> elements)
{
int n = elements.size();
std::vector<int> new_el;
for(int i = 0; i < n; i++)
if(elements[i] < k) new_el.push_back(elements[i]);
for(int i = 0; i < n; i++)
if(elements[i] >= k) new_el.push_back(elements[i]);
return new_el;
}
```
Решение на Java
```java=
public class Solution
{
int[] splitByValue(int k, int[] elements)
{
int n = elements.length;
int[] new_el = new int[n];
int count = 0;
for(int i = 0; i < n; i++)
if(elements[i] < k)
new_el[count++] = elements[i];
for(int i = 0; i < n; i++)
if(elements[i] >= k) new_el[count++] = elements[i];
return new_el;
}
}
```
7. [Simple fibonacci strings](https://www.codewars.com/kata/5aa39ba75084d7cf45000008) 7kyu
Given that
f0 = '0'
f1 = '01'
f2 = '010' = f1 + f0
f3 = '01001' = f2 + f1
You will be given a number and your task is to return the nth fibonacci string. For example:
solve(2) = '010'
solve(3) = '01001'
Учитывая, что
f0 = '0'
f1 = '01'
f2 = '010' = f1 + f0
f3 = '01001' = f2 + f1
Вам дадут номер, и ваша задача - вернуть n-ю строку фибоначчи. Например:
решить (2) = '010'
решить (3) = '01001'
Решение на С++
```c++=
std::string solve(int n)
{
std::string prev = "0", curr = "01", next;
if(n == 0) return prev;
if(n == 1) return curr;
for(int i = 2; i <= n; i++)
{
next = curr + prev;
prev = curr;
curr = next;
}
return next;
}
```
Решение на Java
```java=
class Solution
{
public static String solve(int n)
{
String prev = "0", curr = "01", next = "";
if(n == 0) return prev;
if(n == 1) return curr;
for(int i = 2; i <= n; i++)
{
next = curr + prev;
prev = curr;
curr = next;
}
return next;
}
}
```
8. [Points in segments](https://www.codewars.com/kata/5baa25f3246d071df90002b7) 7kyu
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 0 and m inclusive.
Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers li and ri — coordinates of the left and of the right endpoints.
Consider all integer points between 0 and m inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment [l;r] if and only if l ≤ x ≤ r.
Input:
m — the upper bound for coordinates;
array of coordinates li and ri 0 ≤ li ≤ ri ≤ m — the endpoints of the i-th segment. Segments may intersect, overlap or even coincide with each other.
Output:
All points from 0 to m that don't belong to any segment.
Вам дан набор из n сегментов на оси Ox, каждый сегмент имеет целые конечные точки от 0 до m включительно.
Сегменты могут пересекаться, перекрываться или даже совпадать друг с другом. Каждый сегмент характеризуется двумя целыми числами li и ri - координатами левого и правого концов.
Рассмотрим все целые точки от 0 до m включительно. Ваша задача - распечатать все такие точки, не принадлежащие ни одному сегменту. Точка x принадлежит отрезку [l; r] тогда и только тогда, когда l ≤ x ≤ r.
Вход:
m - верхняя граница координат;
массив координат li и ri 0 ≤ li ≤ ri ≤ m - конечные точки i-го отрезка. Сегменты могут пересекаться, перекрываться или даже совпадать друг с другом.
Выход:
Все точки от 0 до m, не принадлежащие ни одному сегменту.
Решение на С++
```c++=
#include <utility>
#include <vector>
std::vector<int> segments(int m, const std::vector<std::pair<int,int>> &arr)
{
std::vector<int> result = {};
int n = arr.size();
bool flag = true;
for(int i = 0; i <= m; i++)
{
for(int j = 0; j < n && flag; j++)
{
if(i >= arr[j].first && i <= arr[j].second) flag = false;
}
if(flag) result.push_back(i);
flag = true;
}
return result;
}
```
Решение на Java
```java=
public class PointsInSegments
{
public static int[] segments(final int m, final int[][] arr)
{
int n = arr.length;
int count = 0;
int[] result = new int[count];
boolean flag = true;
for(int i = 0; i <= m; i++)
{
for(int j = 0; j < n && flag; j++)
{
if(i >= arr[j][0] && i <= arr[j][1]) flag = false;
}
if(flag)
{
int[] tmp = result;
result = new int[count + 1];
for(int j = 0; j < tmp.length; j++)
{
result[j] = tmp[j];
}
result[count++] = i;
}
flag = true;
}
return result;
}
}
```
9. [Don't give me five!](https://www.codewars.com/kata/5813d19765d81c592200001a) 7kyu
In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!
Examples:
1,9 -> 1,2,3,4,6,7,8,9 -> Result 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12
В этом ката вы получаете начальный и конечный номера региона и должны возвращать количество всех чисел, кроме чисел с 5 в нем. Начальное и конечное числа включены!
Примеры:
1,9 -> 1,2,3,4,6,7,8,9 -> Результат 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Результат 12
Решение на С++
```c++=
#include <string>
int dontGiveMeFive(int start, int end)
{
int amount = 0;
for(int i = start; i <= end; i++)
{
std::string tmp = std::to_string(i);
if(tmp.find("5") == std::string::npos) amount++;
}
return amount;
}
```
Решение на Java
```java=
public class Kata
{
public static int dontGiveMeFive(int start, int end)
{
int amount = 0;
for(int i = start; i <= end; i++)
{
String tmp = Integer.toString(i);
if(tmp.indexOf("5") == -1) amount++;
}
return amount;
}
}
```