# Учебная практика 2021. Понедельник 5.07.2021. Федяева Евгения Игоревна.
Присутствовала на онлайн-лекции.
1. [Get Nth Even Number](https://www.codewars.com/kata/5933a1f8552bc2750a0000ed) 8kyu
Return the Nth Even Number
Верните n-ное четное число.
Решение на С++
```с++=
int nthEven(int n) { return (n-1)*2; }
```
Решение на Java
```java=
public class Num
{
public static int nthEven(int n)
{
return (n-1)*2;
}
}
```
2. [Invert values](https://www.codewars.com/kata/5899dc03bc95b1bf1b0000ad) 8kyu
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
Учитывая набор чисел, верните аддитивное обратное для каждого числа. Каждый позитив становится негативом, а негатив становится позитивом.
Решение на С++
```с++=
#include <vector>
std::vector<int> invert(std::vector<int> values)
{
int n = values.size();
std::vector<int> arr(n);
for(int i = 0; i < n; i++)
arr[i] = -values[i];
return arr;
}
```
Решение на Java
```java=
public class Kata
{
public static int[] invert(int[] array)
{
int n = array.length;
int[] val = new int[n];
for(int i = 0; i < n; i++)
val[i] = -array[i];
return val;
}
}
```
3. [Count of positives / sum of negatives](https://www.codewars.com/kata/576bb71bbbcf0951d5000044) 8kyu
Given an array of integers.
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array.
Дан массив целых чисел.
Вернуть массив, где первый элемент - это количество положительных чисел, а второй элемент - сумма отрицательных чисел.
Если входной массив пуст или равен нулю, вернуть пустой массив.
Решение на С++
```c++=
#include <vector>
std::vector<int>
countPositivesSumNegatives(std::vector<int> input)
{
if(input.size() == 0) return {};
std::vector<int> countSum = {0,0};
int n = input.size();
for(int i = 0; i < n; i++)
{
if(input[i] > 0) countSum[0]++;
if(input[i] < 0) countSum[1] += input[i];
}
return countSum;
}
```
Решение на Java
```java=
public class Kata
{
public static int[] countPositivesSumNegatives(int[] input)
{
if(input == null) return null;
int[] countSum = new int[2];
countSum[0] = 0;
countSum[1] = 0;
int n = input.length;
for(int i = 0; i < n; i++)
{
if(input[i] > 0) countSum[0]++;
if(input[i] < 0) countSum[1] += input[i];
}
return countSum;
}
}
```
4. [Find the stray num](https://www.codewars.com/kata/57f609022f4d534f05000024) 7kyu
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Вам дан массив целых чисел нечетной длины , в котором все они одинаковы, за исключением одного единственного числа.
Завершите метод, который принимает такой массив и возвращает это единственное другое число.
Входной массив всегда будет действительным! (нечетная длина> = 3)
Решение на С++
```c++=
int stray(std::vector<int> numbers)
{
int con;
if(numbers[0] == numbers[1] || numbers[0] == numbers[2]) con = numbers[0];
else if(numbers[1] == numbers[2]) con = numbers[1];
int n = numbers.size();
for(int i = 0; i < n; i++) if(numbers[i] != con) return numbers[i];
}
```
Решение на Java
```java=
class Solution
{
static int stray(int[] numbers)
{
int con = 0;
if(numbers[0] == numbers[1] || numbers[0] == numbers[2]) con = numbers[0];
else if(numbers[1] == numbers[2]) con = numbers[1];
int n = numbers.length;
for(int i = 0; i < n; i++)
{
if(numbers[i] != con) return numbers[i];
}
return 0;
}
}
```
5. [Count by X](https://www.codewars.com/kata/5513795bd3fafb56c200049e) 8kyu
Create a function with two arguments that will return an array of the first (n) multiples of (x).
Assume both the given number and the number of times to count will be positive numbers greater than 0.
Return the results as an array (or list in Python, Haskell or Elixir).
Создайте функцию с двумя аргументами, которая вернет массив первых (n) кратных (x).
Предположим, что и данное число, и количество раз, которое нужно подсчитать, будут положительными числами больше 0.
Возвращает результаты в виде массива (или списка в Python, Haskell или Elixir).
Решение на С++
```c++=
#include <vector>
std::vector<int> countBy(int x,int n)
{
std::vector<int> nums;
bool flag = true;
for(int i = x; flag; i++)
{
if(i%x == 0) nums.push_back(i);
if(nums.size() == n) flag = false;
}
return nums;
}
```
Решение на Java
```java=
import java.util.ArrayList;
ArrayList<Integer> countBy(Integer x,Integer n)
{
ArrayList<Integer> nums = new ArrayList<Integer>();
boolean flag = true;
for(Integer i = x; flag; i++)
{
if (i % x == 0) nums.add(i);
if(nums.size() == n) flag = false;
}
return nums;
}
```
6. [Sum of Triangle Numbers](https://www.codewars.com/kata/580878d5d27b84b64c000b51) 7kyu
Your task is to return the sum of Triangular Numbers up-to-and-including the nth Triangular Number.
Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc."
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
e.g. If 4 is given: 1 + 3 + 6 + 10 = 20.
Triangular Numbers cannot be negative so return 0 if a negative number is given.
Ваша задача - вернуть сумму Треугольных чисел до Треугольного числа включительно.
Треугольное число: «любая из серий чисел (1, 3, 6, 10, 15 и т. Д.), Полученных путем непрерывного суммирования натуральных чисел 1, 2, 3, 4, 5 и т. Д.»
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
например , если 4дано: 1 + 3 + 6 + 10 = 20.
Треугольные числа не могут быть отрицательными, поэтому верните 0, если задано отрицательное число.
Решение на С++
```с++=
int sumTriangularNumbers(int n)
{
int triangle = 0;
int sum = 0;
for(int i = 0; i < n+1; i++)
{
triangle += i;
sum += triangle;
}
return sum;
}
```
Решение на Java
```java=
public class Kata
{
public static int sumTriangularNumbers(int n)
{
int triangle = 0;
int sum = 0;
for(int i = 0; i < n+1; i++)
{
triangle += i;
sum += triangle;
}
return sum;
}
}
```
7. [Maximum Product](https://www.codewars.com/kata/5a4138acf28b82aa43000117) 7kyu
Given an array of integers , Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
Notes
Array/list size is at least 2.
Array/list numbers could be a mixture of positives, negatives also zeroes.
Учитывая массив целых чисел , найти максимальный продукт , полученный от умножения 2 смежных чисел в массиве.
Заметки
Размер массива / списка не менее 2.
Номера массивов / списков могут быть смесью положительных, отрицательных и нулей.
Решение на С++
```с++=
#include <vector>
using namespace std;
int adjacentElementsProduct(vector<int> inputArray)
{
int n = inputArray.size();
int max = inputArray[0]*inputArray[1];
for(int i = 1; i < n-1; i++)
{
if(inputArray[i]*inputArray[i + 1] > max)
max = inputArray[i]*inputArray[i + 1];
}
return max ;
}
```
Решение на Java
```java=
public class MaxProduct
{
public int adjacentElementsProduct(int[] array)
{
int n = array.length;
int max = array[0]*array[1];
for(int i = 1; i < n-1; i++)
{
if(array[i]*array[i + 1] > max)
max = array[i]*array[i + 1];
}
return max;
}
}
```
8. [Nth power rules them all!](https://www.codewars.com/kata/58aed2cafab8faca1d000e20) 7kyu
You are provided with an array of positive integers and an additional integer n (n > 1).
Calculate the sum of each value in the array to the nth power. Then subtract the sum of the original array.
Вам предоставляется массив положительных целых чисел и дополнительное целое число n( n > 1).
Вычислите сумму каждого значения в массиве в степени nth. Затем вычтите сумму исходного массива.
Решение на Java
```java=
public class Kata
{
public static int modifiedSum(int[] array, int power)
{
int sum1 = 0;
int sum2 = 0;
int n = array.length;
for(int i = 0; i < n; i++)
{
sum1 += Math.pow(array[i], power);
sum2 += array[i];
}
return sum1 - sum2;
}
}
```
Решение на С++
```c++=
#include <vector>
#include <cmath>
int modifiedSum(vector<int> array, int power)
{
int sum1 = 0;
int sum2 = 0;
int n = array.size();
for(int i = 0; i < n; i++)
{
sum1 += pow(array[i], power);
sum2 += array[i];
}
return sum1 - sum2;
}
```
9. [Evens times last](https://www.codewars.com/kata/5a1a9e5032b8b98477000004) 7kyu
Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index.
Indices in sequence start from 0.
If the sequence is empty, you should return 0.
Для данной последовательности целых чисел верните сумму всех целых чисел с четным индексом, умноженную на целое число в последнем индексе.
Индексы по порядку начинаются с 0.
Если последовательность пуста, вы должны вернуть 0.
Решение на С++
```c++=
#include <vector>
int even_last(std::vector<int> nums)
{
if(nums.size() == 0) return 0;
int sum = 0;
int n = nums.size();
for(int i = 0; i < n; i += 2)
sum += nums[i];
sum *= nums[n-1];
return sum;
}
```
Решение на Java
```java=
public class Kata
{
public static int even_last(int[] nums)
{
if(nums.length == 0) return 0;
int sum = 0;
int n = nums.length;
for(int i = 0; i < n; i += 2)
sum += nums[i];
sum *= nums[n-1];
return sum;
}
}
```
10. [Growth of a Population](https://www.codewars.com/kata/563b662a59afc2b5120000c6) 7kyu
In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?
At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants
At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)
At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213
It will need 3 entire years.
В небольшом городке на начало года население p0 = 1000. Население регулярно увеличивается на 2 процента в год, и более 50 новых жителей ежегодно приезжают в город. Сколько лет нужно городу, чтобы его население было больше или равно p = 1200 жителей?
В конце первого года будет:
1000 + 1000 * 0,02 + 50 => 1070 жителей
По окончании 2-го курса будут:
1070 + 1070 * 0,02 + 50 => 1141 житель (количество жителей является целым числом)
В конце 3-го курса будут:
1141 + 1141 * 0,02 + 50 => 1213
На это потребуется целых 3 года.
Решение на С++
```c++=
class Arge
{
public:
static int nbYear(int p0, double percent, int aug, int p)
{
int count = 0;
for(p0; p0 < p; p0 += p0*(percent/100) + aug)
count++;
return count;
};
};
```
Решение на Java
```java=
class Arge
{
public static int nbYear(int p0, double percent, int aug, int p)
{
int count = 0;
for(int curr = p0; curr < p; curr += curr*(percent/100) + aug)
count++;
return count;
}
}
```
11. [Greatest common divisor](https://www.codewars.com/kata/5500d54c2ebe0a8e8a0003fd) 7kyu
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.
The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.
Найдите наибольший общий делитель двух натуральных чисел. Целые числа могут быть большими, поэтому вам нужно найти умное решение.
Входные данные x и y всегда больше или равны 1, поэтому наибольший общий делитель всегда будет целым числом, которое также больше или равно 1.
Решение на С++
```c++=
long long mygcd(long long a, long long b)
{
if (b == 0)
return a;
else
return mygcd(b, a %b);
}
```
Решение на Java
```java=
public class GCD
{
public static int compute(int x, int y)
{
if (y == 0)
{
return x;
} else
{
return compute(y, x % y);
}
}
}
```
12. [Get the mean of an array](https://www.codewars.com/kata/563e320cee5dddcf77000158) 8kyu
It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.
Return the average of the given array rounded down to its nearest integer.
The array will never be empty
Конец учебного года, судьбоносный момент твоей школьной успеваемости. Средние должны быть рассчитаны. Все студенты подходят к вам и умоляют посчитать для них средний балл. Легкий ! Вам просто нужно написать сценарий.
Возвращает среднее значение данного массива, округленное до ближайшего целого числа.
Массив никогда не будет пустым.
Решение на С++
```c++=
#include <cmath>
int get_average(std::vector <int> marks)
{
int n = marks.size();
int sum = 0;
for(int i = 0; i < n; i++) sum += marks[i];
return round(sum/n);
}
```
Решение на Java
```java=
public class School
{
public static int getAverage(int[] marks)
{
int = marks.length;
int sum = 0;
for(int i = 0; i < n; i++) sum += marks[i];
return Math.round(sum/n);
}
}
```