files;
+}
\ No newline at end of file
diff --git a/src/module9/File.java b/src/module9/File.java
new file mode 100644
index 0000000..43e3283
--- /dev/null
+++ b/src/module9/File.java
@@ -0,0 +1,17 @@
+package module9;
+
+abstract public class File {
+ protected String typeOfFile;
+
+ public File() {
+ this.typeOfFile = this.getClass().getSimpleName();
+ }
+
+ public String getTypeOfFile() {
+ return typeOfFile;
+ }
+}
+
+
+
+
diff --git a/src/module9/TextFile.java b/src/module9/TextFile.java
new file mode 100644
index 0000000..ae97a3d
--- /dev/null
+++ b/src/module9/TextFile.java
@@ -0,0 +1,20 @@
+package module9;
+
+public class TextFile extends File {
+
+ private String typeOfFile;
+
+ public TextFile(String typeOfFile) {
+ this.typeOfFile = typeOfFile;
+ }
+
+ public String getTypeOfFile() {
+ return typeOfFile;
+ }
+
+ @Override
+ public String toString() {
+ return typeOfFile;
+ }
+
+}
\ No newline at end of file
diff --git a/src/practice_five/BSTSearch.java b/src/practice_five/BSTSearch.java
new file mode 100644
index 0000000..4aa9eca
--- /dev/null
+++ b/src/practice_five/BSTSearch.java
@@ -0,0 +1,31 @@
+package practice_five;
+
+/**
+ * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false.
+ */
+public class BSTSearch {
+ public boolean exist(TreeNode root, int target) {
+ boolean result = false;
+ if(root != null){
+ if(root.value == target){
+ result = true;
+ } else if(root.value > target){
+ result = exist(root.left, target);
+ } else {
+ result = exist(root.right, target);
+ }
+ }
+ return result;
+ }
+}
+
+class TreeNode {
+ int value;
+ TreeNode left, right;
+
+ public TreeNode(int value, TreeNode left, TreeNode right) {
+ this.value = value;
+ this.left = left;
+ this.right = right;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_five/KmpSmallestPeriod.java b/src/practice_five/KmpSmallestPeriod.java
new file mode 100644
index 0000000..2453d08
--- /dev/null
+++ b/src/practice_five/KmpSmallestPeriod.java
@@ -0,0 +1,29 @@
+package practice_five;
+
+/**
+ Найменший Період
+
+ A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k.
+ For example, the string "abcabcabcabc" has period 3, since it is formed by 4 repetitions of the string "abc".
+ It also has periods 6 (two repetitions of "abcabc") and 12 (one repetition of "abcabcabcabc").
+ Write a program to read a character string and determine its smallest period
+ Return (String) substring;
+ */
+public class KmpSmallestPeriod {
+ public String findSmalletstPeriod(String input) {
+ String result;
+ int start = 0;
+ int end = 1;
+
+ while (true){
+ result = input.substring(start, end);
+ String stringToCompare = input.substring(end, end + result.length());
+ if(result.equals(stringToCompare)){
+ break;
+ } else {
+ end++;
+ }
+ }
+ return result;
+ }
+}
diff --git a/src/practice_five/KmpSubMove.java b/src/practice_five/KmpSubMove.java
new file mode 100644
index 0000000..447b86d
--- /dev/null
+++ b/src/practice_five/KmpSubMove.java
@@ -0,0 +1,40 @@
+package practice_five;
+
+/**
+ Циклічний Зсув
+
+ Дается строка в которой делается несколько циклических сдвигов
+ (под циклическим сдвигом понимается перенос последней буквы в начало)
+ Дается также получившаяся строка
+ нужно вернуть минимальное количество сдвигов(int) которым можно получить из 1-й строки итоговую
+ если строку получить циклическим сдвигом нельзя то вывести -1
+
+ Например
+ Дано:
+ abcd
+ cdab
+
+ ответ: 2
+ */
+public class KmpSubMove {
+ public int subMoveQuantity(String inputStr, String resultStr) {
+ int count = 0;
+
+ StringBuilder str = new StringBuilder(inputStr);
+
+ while (count < inputStr.length()){
+ if(inputStr.equals(resultStr)){
+ return count;
+ } else {
+ str.delete(0, str.length());
+ str.append(inputStr.substring(inputStr.length()-1));
+ str.append(inputStr.substring(0, inputStr.length() - 1));
+
+ inputStr = str.toString();
+ count++;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/src/practice_four/ColorChain.java b/src/practice_four/ColorChain.java
new file mode 100644
index 0000000..ddcc03d
--- /dev/null
+++ b/src/practice_four/ColorChain.java
@@ -0,0 +1,24 @@
+package practice_four;
+
+/*
+Условие:
+Дано цепи трёх цветов: белого длиной 1 м, желтого - 2 м и красного - 3 м. Каким количеством способов можно собрать из них цепь длиной N.
+Количество цепей каждого цвета считать бесконечным.
+Результат задачи: ссылка на задачу, которая успешно прошла все тесты в системе Codegym, загружена как ответ на это задание.
+ */
+public class ColorChain {
+ public int count(int N) {
+ int[] results = new int[N + 1];
+ results[0] = 1;
+ if (N >= 1) results[1] = 1;
+ if (N >= 2) results[2] = 2;
+ if (N >= 3) results[3] = 4;
+ if (N >= 4) results[4] = 7;
+ if (N >= 5) {
+ for (int i = 5; i <= N; i++) {
+ results[i] = results[i - 1] + results[i - 2] + results[i - 3];
+ }
+ }
+ return results[N];
+ }
+}
\ No newline at end of file
diff --git a/src/practice_four/JoinCharacters.java b/src/practice_four/JoinCharacters.java
new file mode 100644
index 0000000..b8f2e00
--- /dev/null
+++ b/src/practice_four/JoinCharacters.java
@@ -0,0 +1,14 @@
+package practice_four;
+
+/**
+ * Злиття Цифр
+ * З'єднати масив символів в число.
+ * Приклад:
+ * Для [ '1', '2', '3'] повернути 123
+ */
+public class JoinCharacters {
+ public int join(char[] input) {
+ String s = new String(input);
+ return Integer.parseInt(s);
+ }
+}
\ No newline at end of file
diff --git a/src/practice_four/WordNumber.java b/src/practice_four/WordNumber.java
new file mode 100644
index 0000000..fa33c28
--- /dev/null
+++ b/src/practice_four/WordNumber.java
@@ -0,0 +1,32 @@
+package practice_four;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Злічити Слова
+ *
+ * Дано рядок. Порахувати кількість слів.
+ * Словом вважається послідовність символів англійського алфавіту [a-zA-Z].
+ *
+ * Алгоритм повинен працювати за O(N) часу, тому RegExp використовувати не можна.
+ */
+public class WordNumber {
+ public int count(String input) {
+ input = input.toLowerCase();
+ System.out.println(input);
+ char[] inputsChar = input.toCharArray();
+ int res = 0;
+ boolean word = false;
+ for (char c : inputsChar) {
+ if (c >= 'a' && c <= 'z') {
+ word = true;
+ } else if (word) {
+ word = false;
+ res++;
+ }
+ }
+ if (word) res++;
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_one/FindMaxNumber.java b/src/practice_one/FindMaxNumber.java
new file mode 100644
index 0000000..3cb49d5
--- /dev/null
+++ b/src/practice_one/FindMaxNumber.java
@@ -0,0 +1,18 @@
+package practice_one;
+
+/**
+ * Знайти максимальне число в масиві.
+ * Гарантується, що масив завжди не пустий.
+ */
+public class FindMaxNumber {
+ public int max(int[] input) {
+
+ int maxNumber = input[0];
+ for (int i = 0; i < input.length; i++) {
+ if (maxNumber < input[i]) {
+ maxNumber = input[i];
+ }
+ }
+ return maxNumber;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_one/FirstOddNumber.java b/src/practice_one/FirstOddNumber.java
new file mode 100644
index 0000000..71c25d9
--- /dev/null
+++ b/src/practice_one/FirstOddNumber.java
@@ -0,0 +1,18 @@
+package practice_one;
+
+/**
+ * Знайти перше непарне число і повернути його індекс.
+ * Якщо такого немає, повернути -1
+ */
+public class FirstOddNumber {
+ public int find(int[] input) {
+ int result = -1;
+ for (int i = 0; i < input.length; i++) {
+ if (input[i] % 2!= 0) {
+ result = i;
+ break;
+ }
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_one/JoinCharacters.java b/src/practice_one/JoinCharacters.java
new file mode 100644
index 0000000..1c313d6
--- /dev/null
+++ b/src/practice_one/JoinCharacters.java
@@ -0,0 +1,13 @@
+package practice_one;
+
+
+public class JoinCharacters {
+ public int join(char[] input) {
+ int result = 0;
+ for (int i = 0; i < input.length; i++) {
+ result = result * 10 + (input[i] - '0');
+ }
+ return result;
+ }
+}
+
diff --git a/src/practice_one/MatrixSnakeTraversal.java b/src/practice_one/MatrixSnakeTraversal.java
new file mode 100644
index 0000000..3a04017
--- /dev/null
+++ b/src/practice_one/MatrixSnakeTraversal.java
@@ -0,0 +1,31 @@
+package practice_one;
+
+/**
+ * Обійти матрицю "змійкою" і повернути всі числа в одномірному масиві.
+ * Наприклад:
+ * Для
+ * [[ 1, 2, 3 ],
+ * [ 4, 5, 6 ],
+ * [ 7, 8, 9 ]]
+ * повернути
+ * [1, 4, 7, 8, 5, 2, 3, 6, 9]
+ */
+public class MatrixSnakeTraversal {
+ public int[] print(int[][] input) {
+ if (input.length == 0) return new int[]{};
+ int[] simpleArr = new int[input.length * input[0].length];
+ int index = 0;
+ int i = 0;
+ int n = 1;
+ for (int j = 0; j < input[0].length; j++) {
+ while (i >= 0 && i < input.length) {
+ simpleArr[index] = input[i][j];
+ index++;
+ i += n;
+ }
+ n = -1 * n;
+ i += n;
+ }
+ return simpleArr;
+ }
+}
diff --git a/src/practice_one/MatrixTraversal.java b/src/practice_one/MatrixTraversal.java
new file mode 100644
index 0000000..afa838c
--- /dev/null
+++ b/src/practice_one/MatrixTraversal.java
@@ -0,0 +1,59 @@
+package practice_one;
+
+/*Обійти матрицю по спіралі і записати всі числа в одмірний масив.
+ Для матриці
+ [[1, 2, 3, 4],
+ [5, 6, 7, 8]
+ [9, 10, 11, 12]
+ [13, 14, 15, 16]]
+ вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
+*/
+public class MatrixTraversal {
+ public int[] print(int[][] input) {
+
+ int m = input.length;
+ int n = input[0].length;
+ int[] matrix = new int[m * n];
+ int x = 0;
+ int y = 0;
+ int index = 0;
+ while (m > 0 && n > 0) {
+ if (m == 1) {
+ for (int i = 0; i < n; i++) {
+ matrix[index] = input[x][y++];
+ index++;
+ }
+ break;
+ } else if (n == 1) {
+ for (int i = 0; i < m; i++) {
+ matrix[index] = input[x++][y];
+ index++;
+ }
+ break;
+ }
+ for (int i = 0; i < n - 1; i++) {
+ matrix[index] = input[x][y++];
+ index++;
+ }
+ for (int i = 0; i < m - 1; i++) {
+ matrix[index] = input[x++][y];
+ index++;
+ }
+ for (int i = 0; i < n - 1; i++) {
+ matrix[index] = input[x][y--];
+ index++;
+ }
+ for (int i = 0; i < m - 1; i++) {
+ matrix[index] = input[x--][y];
+ index++;
+ }
+ x++;
+ y++;
+ m = m - 2;
+ n = n - 2;
+ }
+ return matrix;
+ }
+
+}
+
diff --git a/src/practice_one/SumDigits.java b/src/practice_one/SumDigits.java
new file mode 100644
index 0000000..7a068a9
--- /dev/null
+++ b/src/practice_one/SumDigits.java
@@ -0,0 +1,21 @@
+package practice_one;
+
+/*Обчислити суму цифр числа.
+ Наприклад сума цифр числа 123 дорівнює 6.
+*/
+public class SumDigits {
+ public int sum(int number) {
+ int n;
+ int sum = 0;
+ if (number >= 0) {
+ for (n = number; n != 0; n /= 10) {
+ sum = sum + (n % 10);
+ }
+ } else {
+ for (n = number; n != 0; n /= 10) {
+ sum = sum - (n % 10);
+ }
+ }
+ return sum;
+ }
+}
diff --git a/src/practice_three/LongestStabilityPeriod.java b/src/practice_three/LongestStabilityPeriod.java
new file mode 100644
index 0000000..5a680eb
--- /dev/null
+++ b/src/practice_three/LongestStabilityPeriod.java
@@ -0,0 +1,42 @@
+package practice_three;
+
+/**
+ * Найдовший Період Стабільності
+ *
+ * Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США.
+ * Необхідно знайти найдовший період стабільності.
+ * Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1.
+ * Повернути кількість місяців.
+ */
+public class LongestStabilityPeriod {
+ public int count(int[] gdp) {
+ if (gdp.length == 0) return 0;
+ if (gdp.length == 1) return 1;
+
+ int max = 0;
+
+ for (int i = 0; i < gdp.length; i++) {
+ int countA = goWithDiff(gdp, i, 1);
+ int countB = goWithDiff(gdp, i, -1);
+ int count = countA > countB ? countA + 1 : countB + 1;
+ if (count > max) max = count;
+ }
+
+ return max;
+ }
+
+ private int goWithDiff(int[] gdp, int i, int diff) {
+ int j;
+ int countB = 0;
+ j = i + diff;
+ int inc = 0;
+ while (j >= 0 && j < gdp.length) {
+ if (Math.abs(gdp[j] - gdp[i]) > 1) break;
+ if (inc == 0) inc = gdp[j] - gdp[i];
+ else if (gdp[j] - gdp[i] == -1 * inc) break;
+ countB++;
+ j += diff;
+ }
+ return countB;
+ }
+}
diff --git a/src/practice_three/RPN.java b/src/practice_three/RPN.java
new file mode 100644
index 0000000..affe88d
--- /dev/null
+++ b/src/practice_three/RPN.java
@@ -0,0 +1,57 @@
+package practice_three;
+import java.util.LinkedList;
+
+public class RPN{
+ public static void evalRPN(String expr){
+ String cleanExpr = cleanExpr(expr);
+ LinkedList stack = new LinkedList();
+ System.out.println("Input\tOperation\tStack after");
+ for(String token:cleanExpr.split("\\s")){
+ System.out.print(token+"\t");
+ Double tokenNum = null;
+ try{
+ tokenNum = Double.parseDouble(token);
+ }catch(NumberFormatException e){}
+ if(tokenNum != null){
+ System.out.print("Push\t\t");
+ stack.push(Double.parseDouble(token+""));
+ }else if(token.equals("*")){
+ System.out.print("Operate\t\t");
+ double secondOperand = stack.pop();
+ double firstOperand = stack.pop();
+ stack.push(firstOperand * secondOperand);
+ }else if(token.equals("/")){
+ System.out.print("Operate\t\t");
+ double secondOperand = stack.pop();
+ double firstOperand = stack.pop();
+ stack.push(firstOperand / secondOperand);
+ }else if(token.equals("-")){
+ System.out.print("Operate\t\t");
+ double secondOperand = stack.pop();
+ double firstOperand = stack.pop();
+ stack.push(firstOperand - secondOperand);
+ }else if(token.equals("+")){
+ System.out.print("Operate\t\t");
+ double secondOperand = stack.pop();
+ double firstOperand = stack.pop();
+ stack.push(firstOperand + secondOperand);
+ }else if(token.equals("^")){
+ System.out.print("Operate\t\t");
+ double secondOperand = stack.pop();
+ double firstOperand = stack.pop();
+ stack.push(Math.pow(firstOperand, secondOperand));
+ }else{//just in case
+ System.out.println("Error");
+ return;
+ }
+ System.out.println(stack);
+ }
+ System.out.println("Final answer: " + stack.pop());
+ }
+
+ private static String cleanExpr(String expr){
+ //remove all non-operators, non-whitespace, and non digit chars
+ return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", "");
+ }
+
+}
\ No newline at end of file
diff --git a/src/practice_three/ReversePolishNotation.java b/src/practice_three/ReversePolishNotation.java
new file mode 100644
index 0000000..b9d916f
--- /dev/null
+++ b/src/practice_three/ReversePolishNotation.java
@@ -0,0 +1,66 @@
+package practice_three;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.Stack;
+import java.util.function.BiFunction;
+
+/**
+ * Дано арифметичний вираз у вигляді Польського Інверсного запису.
+ * Необхідно обчислити значення виразу і повернути його.
+ * Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число.
+ */
+public class ReversePolishNotation {
+ public int evaluate(String expression) {
+ String cleanExpr = cleanExpr(expression);
+ LinkedList stack = new LinkedList();
+ System.out.println("Input\tOperation\tStack after");
+ for(String token:cleanExpr.split("\\s")){
+ System.out.print(token+"\t");
+ Integer tokenNum = null;
+ try{
+ tokenNum = Integer.parseInt(token);
+ }catch(NumberFormatException e){}
+ if(tokenNum != null){
+ System.out.print("Push\t\t");
+ stack.push(Integer.parseInt(token+""));
+ }else if(token.equals("*")){
+ System.out.print("Operate\t\t");
+ int secondOperand = stack.pop();
+ int firstOperand = stack.pop();
+ stack.push(firstOperand * secondOperand);
+ }else if(token.equals("/")){
+ System.out.print("Operate\t\t");
+ int secondOperand = stack.pop();
+ int firstOperand = stack.pop();
+ stack.push(firstOperand / secondOperand);
+ }else if(token.equals("-")){
+ System.out.print("Operate\t\t");
+ int secondOperand = stack.pop();
+ int firstOperand = stack.pop();
+ stack.push(firstOperand - secondOperand);
+ }else if(token.equals("+")){
+ System.out.print("Operate\t\t");
+ int secondOperand = stack.pop();
+ int firstOperand = stack.pop();
+ stack.push(firstOperand + secondOperand);
+ }else if(token.equals("^")){
+ System.out.print("Operate\t\t");
+ int secondOperand = stack.pop();
+ int firstOperand = stack.pop();
+ stack.push((int) Math.pow(firstOperand, secondOperand));
+ }else{//just in case
+ System.out.println("Error");
+ return 0;
+ }
+ System.out.println(stack);
+ }
+ System.out.println("Final answer: " + stack.pop());
+ return Integer.valueOf(stack.pop());
+ }
+
+ private static String cleanExpr(String expr){
+ //remove all non-operators, non-whitespace, and non digit chars
+ return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", "");
+ }
+}
\ No newline at end of file
diff --git a/src/practice_three/UnixPath.java b/src/practice_three/UnixPath.java
new file mode 100644
index 0000000..951f7c4
--- /dev/null
+++ b/src/practice_three/UnixPath.java
@@ -0,0 +1,33 @@
+package practice_three;
+
+import java.util.LinkedList;
+
+/**
+ * Дано повний шлях до файла в Unix системі.
+ * Наприклад /home/../var/./lib//file.txt
+ * Необхідно повернути спрощений варіант. (/var/lib/file.txt)
+ */
+public class UnixPath {
+ public String simplify(String input) {
+ if (input == null || input.length() == 0) return "/";
+
+ LinkedList list = new LinkedList<>();
+ String[] splits = input.trim().trim().split("/");
+ for (String s : splits) {
+ if (s == null || s.length() == 0 || s.equals(".")) continue;
+ else if (s.equals("..")) {
+ if (list.size() > 0) list.pop();
+ } else {
+ list.push(s);
+ }
+ }
+ if (list.isEmpty()) return "/";
+ StringBuffer stringBuffer = new StringBuffer();
+ while (!list.isEmpty()) {
+ stringBuffer.insert(0, list.pop());
+ stringBuffer.insert(0, "/");
+ }
+ return stringBuffer.toString();
+ }
+}
+
diff --git a/src/practice_two/AbcNumber.java b/src/practice_two/AbcNumber.java
new file mode 100644
index 0000000..f44318a
--- /dev/null
+++ b/src/practice_two/AbcNumber.java
@@ -0,0 +1,21 @@
+package practice_two;
+
+/**
+ * Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j.
+ * Необхідно повернути початкове число маючи конвертований рядок.
+ * Наприклад:
+ * Для "bcd" повернути 123
+ */
+public class AbcNumber {
+ public int convert(String num) {
+ String[] alphab = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
+ String[] codes = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"};
+
+ String strOut = num;
+ for (int i = 0; i < alphab.length; i++) {
+ strOut = strOut.replaceAll(alphab[i], codes[i]);
+ }
+ int finalResult = Integer.parseInt(strOut);
+ return finalResult;
+ }
+}
diff --git a/src/practice_two/AddBinary.java b/src/practice_two/AddBinary.java
new file mode 100644
index 0000000..b4b7174
--- /dev/null
+++ b/src/practice_two/AddBinary.java
@@ -0,0 +1,38 @@
+package practice_two;
+
+/**
+ * Додайте два беззнакових числа, що передаються як рядки.
+ * "101" + "100" = "1001"
+ */
+public class AddBinary {
+ public String add(String a, String b) {
+ if (a == null || b == null) return "";
+ int first = a.length() - 1;
+ int second = b.length() - 1;
+ StringBuilder sb = new StringBuilder();
+ int carry = 0;
+ while (first >= 0 || second >= 0) {
+ int sum = carry;
+ if (first >= 0) {
+ sum += a.charAt(first) - '0';
+ first--;
+ }
+ if (second >= 0) {
+ sum += b.charAt(second) - '0';
+ second--;
+ }
+ carry = sum >> 1;
+ sum = sum & 1;
+ sb.append(sum == 0 ? '0' : '1');
+ }
+ if (carry > 0)
+ sb.append('1');
+
+ sb.reverse();
+ return String.valueOf(sb);
+ }
+}
+ // Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
+
+
+
diff --git a/src/practice_two/AddNumberBase36.java b/src/practice_two/AddNumberBase36.java
new file mode 100644
index 0000000..8d16784
--- /dev/null
+++ b/src/practice_two/AddNumberBase36.java
@@ -0,0 +1,121 @@
+package practice_two;
+
+import java.util.ArrayList;
+
+/**
+ * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z].
+ * Повернути суму чисел, також в системі 36.
+ * Наприклад:
+ * "9" + "1" = "a"
+ * "z" + "1" = "10"
+ */
+public class AddNumberBase36 {
+ public final static int base = 36;
+
+ public String add(String a, String b) {
+
+ return intToBase36(base36ToInt(a) + base36ToInt(b));
+ }
+
+ public static int base36ToInt(String str) {
+
+
+ str = str.toUpperCase();
+
+ int result = 0;
+ double frontVal = 0;
+ double lastVal = 0;
+ int size = str.length();
+ boolean started = false;
+
+
+ frontVal = char36ToInt(str.charAt(0));
+ for (int i = 0; i < size; i++) {
+
+ if (i + 1 < size && (started || frontVal > 0.0)) {
+ lastVal = char36ToInt(str.charAt(i + 1));
+ frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base);
+ } else if (!started) {
+ if (frontVal == 0.0 && i + 1 < size) {
+ lastVal = char36ToInt(str.charAt(i + 1));
+ if (lastVal > 0.0) {
+ frontVal = lastVal;
+ started = true;
+ }
+
+ }
+ }
+
+ }
+ result = (int) Math.round(frontVal);
+ return result;
+ }
+
+ public static String intToBase36(int n) {
+ String result = "";
+ ArrayList list = new ArrayList();
+ int frontVal = 0;
+ int lastVal = 0;
+ int val = n;
+ frontVal = val;
+
+ while (val >= base) {
+ frontVal = val / base;
+ lastVal = val % base;
+ list.add(Character.toString(intToChar36(lastVal)));
+ val = frontVal;
+
+ }
+
+ if (frontVal > 0)
+ list.add(Character.toString(intToChar36(frontVal)));
+
+ for (int i = list.size() - 1; i >= 0; i--)
+ result += list.get(i).toLowerCase();
+
+ return result;
+ }
+
+ public static char intToChar36(int n) {
+
+ char result = (char) 0;
+
+ if (n >= 0 && n <= 9)
+ result = (char) (48 + n);
+ else if (n > 9 && n < base) {
+ result = (char) (65 - 10 + n);
+ }
+ return result;
+ }
+
+ public static char intToChar35(int n) {
+ char result = (char) 0;
+ if (n >= 0 && n <= 9)
+ result = (char) (48 + n);
+ else if (n > 9 && n < 14) {
+ result = (char) (65 - 10 + n);
+ } else if (n > 13 && n < 36)
+ result = (char) (65 - 10 + n + 1);
+ return result;
+ }
+
+ public static int char36ToInt(char c) {
+
+ int result = 0;
+ if (Character.isDigit(c))
+ result = (int) c - 48;
+ else if (Character.isAlphabetic(c)) {
+ if ((int) c <= 90) {
+ result = (int) c - (65 - 10);
+ }
+ }
+ return result;
+ }
+
+ public static int char35ToInt(char c) {
+ int result = char36ToInt(c);
+ if (result > 13)
+ result--;
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_two/AverageNumber.java b/src/practice_two/AverageNumber.java
new file mode 100644
index 0000000..2bddee0
--- /dev/null
+++ b/src/practice_two/AverageNumber.java
@@ -0,0 +1,18 @@
+package practice_two;
+/*
+Знайти середнє значення двох цілих чисел.
+Приклади:
+average( 4, 6 ) = 5
+average( -4, -7 ) = -5
+average( -4, 7 ) = 1
+ */
+
+public class AverageNumber {
+ public static int average(int a, int b) {
+ long c = 2;
+ long averageNumberFirst = ((long) a + b) / c;
+ int averageNumberLast = (int) averageNumberFirst;
+ return averageNumberLast;
+ }
+}
+
diff --git a/src/practice_two/CountBits.java b/src/practice_two/CountBits.java
new file mode 100644
index 0000000..3cb343c
--- /dev/null
+++ b/src/practice_two/CountBits.java
@@ -0,0 +1,17 @@
+package practice_two;
+
+/**
+ * Для даного числа порахувати кількість біт.
+ * Наприклад:
+ * Для числа 13 в бінарному вигляді 1101 повернути 3.
+ */
+public class CountBits {
+ public int count(int num) {
+ int count = 0;
+ while (num != 0) {
+ count++;
+ num = num & (num - 1);
+ }
+ return count;
+ }
+}
\ No newline at end of file
diff --git a/src/practice_two/PositiveAverageNumber.java b/src/practice_two/PositiveAverageNumber.java
new file mode 100644
index 0000000..49eb5d1
--- /dev/null
+++ b/src/practice_two/PositiveAverageNumber.java
@@ -0,0 +1,28 @@
+package practice_two;
+
+/**
+ * Знайти середнє арифметике двух додатніх чисел.
+ * Наприклад:
+ * average( 2, 4 ) = 3
+ * average( 4, 7 ) = 5
+ */
+public class PositiveAverageNumber {
+ public static int average(int a, int b) {
+ long c = 2;
+ long a1 = a;
+ long b1 = b;
+ long averageNumberFirst = (a1 + b1) / c;
+ int averageNumberLast = (int) averageNumberFirst;
+ return averageNumberLast;
+ }
+}
+
+/*
+ BigInteger c = BigInteger.valueOf(2);
+ BigInteger a1 = BigInteger.valueOf(a);
+ BigInteger b1 = BigInteger.valueOf(b);
+ BigInteger sum = a1.add(b1);
+ BigInteger averageNumberFirst = sum.divide(c);
+
+ int averageNumberLast = averageNumberFirst.intValue();
+ */
\ No newline at end of file
diff --git a/src/practice_two/SetZero.java b/src/practice_two/SetZero.java
new file mode 100644
index 0000000..10309ca
--- /dev/null
+++ b/src/practice_two/SetZero.java
@@ -0,0 +1,32 @@
+package practice_two;
+
+/**
+ * Дано число. Треба замінити i-й біт замінити на нуль.
+ * Наприклад:
+ * для числа 6 в бінарному вигляді 110,
+ * замінивши 2-й біт на нуль отримаємо 100 тобто 4.
+ * 1<= i <= 32
+ */
+public class SetZero {
+
+ public int set(int num, int i) {
+ char[] arr = new char[32];
+ for (int index = 0; index < 32; index++) {
+ if (index == 32 - i) arr[index] = '0';
+ else arr[index] = '1';
+ }
+ String str = new String(arr);
+ Long mask = Long.parseLong(str, 2);
+ return num & mask.intValue();
+ }
+}
+
+
+/*
+String binaryString = Integer.toBinaryString(num);
+ char[] chars = binaryString.toCharArray();
+ chars[i - 1] = '0';
+ String stringNum = String.valueOf(chars);
+ int finalResult = Integer.parseInt(stringNum, 2);
+ return finalResult;
+ */
\ No newline at end of file
diff --git a/src/some/Numbers.java b/src/some/Numbers.java
new file mode 100644
index 0000000..3bf2f3a
--- /dev/null
+++ b/src/some/Numbers.java
@@ -0,0 +1,22 @@
+package some;
+
+/**
+ * Создайте программу, выводящую на экран все четырёхзначные числа последовательности 1000 1003 1006 1009 1012 1015 ….
+ */
+public class Numbers {
+ public static void main(String[] args) {
+
+ int[] arr = new int[10];
+ numbers(arr);
+ }
+
+ public static void numbers(int[] arr) {
+
+ int num = 1000;
+ for (int i = 0; i < arr.length; i++) {
+ arr[i] = num;
+ System.out.println(arr[i]);
+ num = num + 3;
+ }
+ }
+}
diff --git a/src/some/Test.java b/src/some/Test.java
new file mode 100644
index 0000000..b5d7ab0
--- /dev/null
+++ b/src/some/Test.java
@@ -0,0 +1,17 @@
+package some;
+
+
+import java.util.Random;
+import java.util.concurrent.*;
+import java.util.stream.IntStream;
+
+public class Test {
+ public static void main(String[] args) {
+new Test().test();
+ }
+ public void test () {
+ ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
+ System.out.println("Task scheduled");
+ executorService.scheduleAtFixedRate(() -> System.out.println("Task executed"), 1, 1, TimeUnit.SECONDS);
+ }
+ }
diff --git a/src/some/toBase36.java b/src/some/toBase36.java
new file mode 100644
index 0000000..b5ae03f
--- /dev/null
+++ b/src/some/toBase36.java
@@ -0,0 +1,257 @@
+package some;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z].
+ * Повернути суму чисел, також в системі 36.
+ * Наприклад:
+ * "9" + "1" = "a"
+ * "z" + "1" = "10"
+ */
+public class toBase36 {
+ public static final BigInteger C36 = BigInteger.valueOf(36);
+ public static void main(String[] args) {
+ System.out.println(new toBase36().add("zjfghfhdsdfathjjhgjhghjfjfjhjhdsrreqqklhu456hfz5", "wsfgsgds56346263fgfhghfghfhgfsrr5476hjfgdhdhg3N"));
+ }
+ public String add(String a, String b) {
+ BigInteger ad = toDecimal(a.toLowerCase());
+ BigInteger bd = toDecimal(b.toLowerCase());
+ BigInteger sum = ad.add(bd);
+ return fromDecimal(sum);
+ }
+
+ public BigInteger toDecimal(String s){
+ BigInteger result = new BigInteger("0");
+ char[] chars = s.toCharArray();
+ for(char c: chars){
+ int diff = c>='0' && c<='9'
+ ? c-'0'
+ : c-'a'+10;
+ result=result.multiply(C36).add(BigInteger.valueOf(diff));
+ }
+ return result;
+ }
+
+ public String fromDecimal(BigInteger i){
+ StringBuilder sb = new StringBuilder();
+
+ BigInteger n=i;
+ while(n.compareTo(BigInteger.valueOf(0))>0){
+ BigInteger modBI = n.mod(C36);
+ int mod = modBI.intValue();
+ char c = (char)(mod<=9
+ ? mod+'0'
+ : mod+'a'-10);
+ sb.append(c);
+ n=n.divide(C36);
+ };
+
+ return sb.reverse().toString();
+ }
+}
+
+
+/*
+ public String add(String a, String b) {
+
+ return intToBase36(base36ToInt(a) + base36ToInt(b));
+ }
+
+ public static int base36ToInt(String str) {
+
+
+ //make sure that each case is upper
+ str = str.toUpperCase();
+ //This function will convert a base36 string to it's int equivalent
+ int result = 0;
+ double frontVal = 0;
+ double lastVal = 0;
+ int size = str.length();
+ boolean started = false;
+
+
+ frontVal = char36ToInt(str.charAt(0));
+ for (int i = 0; i < size; i++) {
+ //TODO: log this println("frontVal = " + frontVal);
+
+ if (i + 1 < size && (started || frontVal > 0.0)) {
+ lastVal = char36ToInt(str.charAt(i + 1));
+ //TODO: log this println("lastVal = " + lastVal);
+ //should contain the temp result:
+ frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base);
+ //TODO: log this println("new frontVal = " + frontVal);
+ } else if (!started) {
+ if (frontVal == 0.0 && i + 1 < size) {
+ lastVal = char36ToInt(str.charAt(i + 1));
+ if (lastVal > 0.0) {
+ frontVal = lastVal;
+ started = true;
+ }
+
+ }
+ }
+
+ }
+ result = (int) Math.round(frontVal);
+ return result;
+ }
+
+ public static String intToBase36(int n) {//passed test for base36!
+ //Converts an int value to a base36 string
+ String result = "";
+ ArrayList list = new ArrayList();
+ int frontVal = 0;
+ int lastVal = 0;
+ int val = n;//preserve input
+ frontVal = val;
+
+ while (val >= base) {
+
+ //val is greater than the base; so we need to continue loop until it is not
+
+ frontVal = val / base;//store the front part
+ lastVal = val % base;//store the last part
+ //TODO log thisprintln("val = " + val + "\tfrontVal = " +frontVal + "\tlastVal = " + lastVal);
+ list.add(Character.toString(intToChar36(lastVal)));
+ val = frontVal;
+
+ }
+
+ //add last base36 digit
+ if (frontVal > 0)
+ list.add(Character.toString(intToChar36(frontVal)));
+
+ //fill the rest of the string with 0s
+ // for (int i = list.size(); i < MAX_digits; i++)
+ // list.add("0");
+
+ //convert list to string, in order.
+ for (int i = list.size() - 1; i >= 0; i--)
+ result += list.get(i).toLowerCase();
+
+ return result;
+ }
+
+ public static char intToChar36(int n) {//passed test!
+ //Converts the integer value to the equivalent base 36 character
+ char result = (char) 0;
+
+ if (n >= 0 && n <= 9)
+ result = (char) (48 + n);
+ else if (n > 9 && n < base) {
+ result = (char) (65 - 10 + n);
+ }
+ return result;
+ }
+
+ public static char intToChar35(int n) {//passed test!
+ //Same as intToChar36; however it removes the 'E' char
+ //Converts the integer value to the equivalent base 36 character
+ char result = (char) 0;
+
+ if (n >= 0 && n <= 9)
+ result = (char) (48 + n);
+ else if (n > 9 && n < 14) {
+ result = (char) (65 - 10 + n);
+ } else if (n > 13 && n < 36)
+ result = (char) (65 - 10 + n + 1);
+ return result;
+ }
+
+ public static int char36ToInt(char c) {//passed test!
+ //Converts a base 36 character into its equivalent value in integer
+ int result = 0;
+ if (Character.isDigit(c))
+ result = (int) c - 48;
+ else if (Character.isAlphabetic(c)) {
+ //-10 because 0-9 are our 1st 10 in base36
+ if ((int) c <= 90) {
+ result = (int) c - (65 - 10);
+
+ }
+ }
+ return result;
+ }
+
+ public static int char35ToInt(char c) {//passed test!
+ int result = char36ToInt(c);
+ if (result > 13)
+ result--;
+ return result;
+
+ }
+}
+*/
+
+
+
+/*
+ public static int base36ToBase10(String text) {
+
+ String code = "0123456789abcdefghijklmnopqrstuvwxyz";
+ int num = 0;
+ int j = text.length();
+ for (int i = 0; i < j; i++) {
+ num += code.indexOf(text.charAt(0)) * Math.pow(code.length(), i);
+ text = text.substring(1);
+ }
+ return num;
+ }
+
+
+ public static String base10ToBase36(int num) {
+ String code = "0123456789abcdefghijklmnopqrstuvwxyz";
+ String text = "";
+ int j = (int) Math.ceil(Math.log(num) / Math.log(code.length()));
+ for (int i = 0; i < j; i++) {
+ //i goes to log base code.length() of num (using change of base formula)
+ text += code.charAt(num % code.length());
+ num /= code.length();
+ }
+ return text;
+ }
+}*/
+ /* public String add(String a, String b){
+ return base10ToBase36(base36ToBase10(a) + base36ToBase10(b));
+ }
+ private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz";
+
+ //"0123456789 abcdefghij klmnopqrst uvwxyz"
+ //"0123456789 0123456789 0123456789 012345"
+
+
+ private static String max36=base10ToBase36(Integer.MAX_VALUE);
+
+ public static String base10ToBase36(int inNum) {
+ if(inNum<0) {
+ throw new NumberFormatException("Value "+inNum +" to small");
+ }
+ int num = inNum;
+ String text = "";
+ int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length()));
+ for(int i = 0; i < j; i++){
+ text = codeBase36.charAt(num%codeBase36.length())+text;
+ num /= codeBase36.length();
+ }
+ return text;
+ }
+ public static int base36ToBase10(String in) {
+ String text = in.toLowerCase();
+ if(text.compareToIgnoreCase(max36)>0) {
+ throw new NumberFormatException("Value "+text+" to big");
+ }
+
+ if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){
+ throw new NumberFormatException("Value "+text+" false format");
+ }
+ int num=0;
+ int j = text.length();
+ for(int i = 0; i < j; i++){
+ num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i);
+ text = text.substring(0,text.length()-1);
+ }
+ return num;
+ }*/
diff --git a/src/test/module10/CeaserCipherTest.java b/src/test/module10/CeaserCipherTest.java
new file mode 100644
index 0000000..be06bf6
--- /dev/null
+++ b/src/test/module10/CeaserCipherTest.java
@@ -0,0 +1,51 @@
+package test.module10;
+
+import com.sun.prism.shader.Texture_Color_AlphaTest_Loader;
+import module10.*;
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class CeaserCipherTest {
+
+ @Test(timeout = 3000)
+ public void testEncrypt() throws Exception {
+
+ final String string = "Hello Java!!!";
+ final int key = 2;
+
+ CeasarCipher ceasarCipher = new CeasarCipher();
+ final String encryptString = ceasarCipher.encrypt(string, key);
+
+ Assert.assertEquals("Jgnnq Lcxc!!!", encryptString);
+ }
+
+ @Test(timeout = 3000)
+ public void testDeEncrypt() throws Exception {
+
+ final String string = "Jgnnq Lcxc!!!";
+ final int key = 2;
+
+ CeasarCipher ceasarCipher = new CeasarCipher();
+ final String decryptString = ceasarCipher.decrypt(string, key);
+
+ Assert.assertEquals("Hello Java!!!", decryptString);
+ }
+
+ @Test(timeout = 3000)
+ public void testFileUtil() throws Exception {
+
+ FileUtil fileUtil = new FileUtil();
+ try {
+ fileUtil.write("TextTest.txt", "Hello Sidney.");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ try {
+ fileUtil.read("TextTest.txt");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/test/module2_2/ExecutorImplTest.java b/src/test/module2_2/ExecutorImplTest.java
new file mode 100644
index 0000000..f5bc2d6
--- /dev/null
+++ b/src/test/module2_2/ExecutorImplTest.java
@@ -0,0 +1,30 @@
+package test.module2_2;
+
+import module2_2.*;
+import org.junit.Assert;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class ExecutorImplTest {
+
+
+ @Test
+ public void testExecuteWithoutValidator() throws Exception {
+ ExecutorImpl executor = new ExecutorImpl<>();
+ Task[] intTasks = new IntegerTask[1];
+ intTasks[0] = new IntegerTask(2);
+ Executor numberExecutor = new ExecutorImpl<>();
+
+ for (Task intTask : intTasks) {
+ numberExecutor.addTask(intTask);
+ }
+
+ numberExecutor.addTask(new LongTask(10L), new NumberValidator());
+ numberExecutor.addTask(new DoubleTask(39.2389)); // if number after point % 2 == 0 than doubleNumber is ValidResult
+
+ Assert.assertEquals(numberExecutor.getValidResults().get(1), Integer.valueOf(0));
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/test/module4/ex1_square/CalculateSquareTest.java b/src/test/module4/ex1_square/CalculateSquareTest.java
new file mode 100644
index 0000000..70e7e3c
--- /dev/null
+++ b/src/test/module4/ex1_square/CalculateSquareTest.java
@@ -0,0 +1,41 @@
+package test.module4.ex1_square;
+
+import module4.ex1_square.*;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class CalculateSquareTest {
+
+ @Test(timeout = 3000)
+ public void testCountCircleSquare() throws Exception {
+ final double radius = 5;
+
+ CircleSquare circleSquare = new CircleSquare(radius);
+ final double resultCircleSquare = circleSquare.countCircleSquare();
+
+ Assert.assertEquals(78.54, resultCircleSquare, 0.01);
+ }
+
+ @Test(timeout = 3000)
+ public void testCountRectangleSquare() throws Exception {
+ final double heightOfRectangle = 9;
+ final double widthOfRectangle = 8;
+
+ RectangleSquare rectangleSquare = new RectangleSquare(heightOfRectangle, widthOfRectangle);
+ final double resultRectangleSquare = rectangleSquare.countRectangleSquare();
+
+ Assert.assertEquals(36, resultRectangleSquare, 0.01);
+ }
+
+ @Test(timeout = 3000)
+ public void testCountTriangleSquare() throws Exception {
+ final double sideOfTriangle = 5;
+ final double heightOfTriangle = 5;
+
+ TriangleSquare triangleSquare = new TriangleSquare(sideOfTriangle, heightOfTriangle);
+ final double resultTriangleSquare = triangleSquare.countTriangleSquare();
+
+ Assert.assertEquals(12.5, resultTriangleSquare, 0.01);
+ }
+}
diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java
new file mode 100644
index 0000000..a41923e
--- /dev/null
+++ b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java
@@ -0,0 +1,30 @@
+package test.module4.ex2_temperature;
+import module4.ex2_temperature.*;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ConvertsTemperatureTest {
+
+ @Test(timeout = 3000)
+ public void testCelsiusToFahrenheit() throws Exception {
+ final double fahrenheitDegree = 709.8;
+
+ ConvertsTemperature convertsTemperature = new ConvertsTemperature();
+ convertsTemperature.setCelsiusDegree(21);
+ final double value = convertsTemperature.celsiusToFahrenheit();
+
+ Assert.assertEquals(fahrenheitDegree, value, 0.1);
+ }
+
+ @Test(timeout = 3000)
+ public void testFahrenheitToCelsius() throws Exception {
+ final double celsiusDegree = 21;
+
+ ConvertsTemperature convertsTemperature = new ConvertsTemperature();
+ convertsTemperature.setFahrenheitDegree(709);
+ final double value = convertsTemperature.fahrenheitToCelsius();
+
+ Assert.assertEquals(celsiusDegree, value, 0.1);
+ }
+}
diff --git a/src/test/module4/ex3_distance/CalculateDistanceTest.java b/src/test/module4/ex3_distance/CalculateDistanceTest.java
new file mode 100644
index 0000000..d9096fe
--- /dev/null
+++ b/src/test/module4/ex3_distance/CalculateDistanceTest.java
@@ -0,0 +1,23 @@
+package test.module4.ex3_distance;
+import module4.ex3_distance.*;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class CalculateDistanceTest {
+
+ @Test(timeout = 3000)
+
+ public void testDistanceBetweenTwoPoints() {
+ int distanceForCheck = 4;
+
+ CalculateDistance calculateDistance = new CalculateDistance();
+ calculateDistance.setX1(5);
+ calculateDistance.setX2(9);
+ calculateDistance.setY1(8);
+ calculateDistance.setY2(7);
+ final int distance = calculateDistance.distanceBetweenTwoPoints();
+
+ Assert.assertEquals(distanceForCheck, distance);
+ }
+}
+
diff --git a/src/test/module5/ArrMinMaxSortTest.java b/src/test/module5/ArrMinMaxSortTest.java
new file mode 100644
index 0000000..5fe253e
--- /dev/null
+++ b/src/test/module5/ArrMinMaxSortTest.java
@@ -0,0 +1,41 @@
+package test.module5;
+import module5.*;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ArrMinMaxSortTest {
+
+ @Test(timeout = 3000)
+ public void testDoBubbleSort() throws Exception {
+ final int[] arr = {1, 2, 3, 4};
+ final int[] arrToDoBubbleSort = {2, 1, 4, 3};
+
+ ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive();
+ final int[] resultDoBubbleSort = arrMinMaxSortTestDrive.doBubbleSort(arrToDoBubbleSort);
+
+ Assert.assertArrayEquals(arr, resultDoBubbleSort);
+ }
+ @Test(timeout = 3000)
+ public void testGetMaxValue() throws Exception {
+ final int[] arr = {1, 2, 3, 4};
+ final int max = 4;
+
+ ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive();
+ final int resultMax = arrMinMaxSortTestDrive.getMaxValue(arr);
+
+ Assert.assertEquals(max, resultMax);
+ }
+
+ @Test(timeout = 3000)
+ public void testGetMinValue() throws Exception {
+ final int[] arr = {1, 2, 3, 4};
+ final int min = 1;
+
+ ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive();
+ final int resultMin = arrMinMaxSortTestDrive.getMinValue(arr);
+
+ Assert.assertEquals(min, resultMin);
+ }
+}
+
diff --git a/src/test/module9/CezarTest.java b/src/test/module9/CezarTest.java
new file mode 100644
index 0000000..52d6cd1
--- /dev/null
+++ b/src/test/module9/CezarTest.java
@@ -0,0 +1,31 @@
+package test.module9;
+import module9.*;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class CezarTest {
+
+ @Test(timeout = 3000)
+ public void testEncrypt() throws Exception {
+
+ final String string = "Audio file";
+ final int key = 2;
+
+ CezarTestDrive cezarTestDrive = new CezarTestDrive();
+ final String encryptString = cezarTestDrive.encrypt(string, key);
+
+ Assert.assertEquals("Cwfkq hkng", encryptString);
+ }
+
+ @Test(timeout = 3000)
+ public void testDeEncrypt() throws Exception {
+
+ final String string = "Cwfkq hkng";
+ final int key = 2;
+
+ CezarTestDrive cezarTestDrive = new CezarTestDrive();
+ final String decryptString = cezarTestDrive.decrypt(string, key);
+
+ Assert.assertEquals("Audio file", decryptString);
+ }
+}
diff --git a/src/test/practice_five/BSTSearchTest.java b/src/test/practice_five/BSTSearchTest.java
new file mode 100644
index 0000000..253b171
--- /dev/null
+++ b/src/test/practice_five/BSTSearchTest.java
@@ -0,0 +1,16 @@
+package test.practice_five;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false.
+ */
+public class BSTSearchTest {
+
+ @Test
+ public void testExist() throws Exception {
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_one/FindMaxNumberTest.java b/src/test/practice_one/FindMaxNumberTest.java
new file mode 100644
index 0000000..609dded
--- /dev/null
+++ b/src/test/practice_one/FindMaxNumberTest.java
@@ -0,0 +1,18 @@
+package test.practice_one;
+
+import practice_one.FindMaxNumber;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class FindMaxNumberTest {
+
+ @Test
+ public void testMax() throws Exception {
+ int[] input = {-6, -2, -3};
+ int expected = -2;
+ FindMaxNumber findMaxNumber = new FindMaxNumber();
+ int extualResult = findMaxNumber.max(input);
+ Assert.assertEquals(expected, extualResult);
+ System.out.println(extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_one/FirstOddNumberTest.java b/src/test/practice_one/FirstOddNumberTest.java
new file mode 100644
index 0000000..de73d39
--- /dev/null
+++ b/src/test/practice_one/FirstOddNumberTest.java
@@ -0,0 +1,17 @@
+package test.practice_one;
+
+import practice_one.FirstOddNumber;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class FirstOddNumberTest {
+ @Test
+ public void testFind() throws Exception {
+ int[] input = {};
+ int expected = -1;
+ FirstOddNumber firstOddNumber = new FirstOddNumber();
+ int extualResult = firstOddNumber.find(input);
+ Assert.assertEquals(expected, extualResult);
+ System.out.println(extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_one/JoinCharactersTest.java b/src/test/practice_one/JoinCharactersTest.java
new file mode 100644
index 0000000..12d75c0
--- /dev/null
+++ b/src/test/practice_one/JoinCharactersTest.java
@@ -0,0 +1,29 @@
+package test.practice_one;
+
+import practice_one.JoinCharacters;
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class JoinCharactersTest {
+ JoinCharacters joinCharacters = new JoinCharacters();
+
+ @Test
+ public void testSingleElementArray() throws Exception {
+ char[] input = {'1'};
+ int expected = 1;
+
+ int extualResult = joinCharacters.join(input);
+
+ Assert.assertEquals("Characters should be joind correctly for single element array.", expected, extualResult);
+ }
+
+ @Test
+ public void testThreeElementsArray() throws Exception {
+ char[] input = {'1', '2', '3'};
+ int expected = 123;
+
+ int extualResult = joinCharacters.join(input);
+ Assert.assertEquals("Characters should be joind correctly for three elements array.", expected, extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_one/MatrixSnakeTraversalTest.java b/src/test/practice_one/MatrixSnakeTraversalTest.java
new file mode 100644
index 0000000..e8fc501
--- /dev/null
+++ b/src/test/practice_one/MatrixSnakeTraversalTest.java
@@ -0,0 +1,26 @@
+package test.practice_one;
+
+import practice_one.MatrixSnakeTraversal;
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class MatrixSnakeTraversalTest {
+
+ MatrixSnakeTraversal matrixSnakeTraversal = new MatrixSnakeTraversal();
+
+
+ @Test
+ public void testPrintForSquareMatrix() throws Exception {
+ int[][] input = {{1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}};
+
+ int[] expected = {1, 4, 7, 8, 5, 2, 3, 6, 9};
+ int[] extualResult = matrixSnakeTraversal.print(input);
+ Assert.assertArrayEquals(expected, extualResult);
+
+ }
+
+
+}
diff --git a/src/test/practice_one/MatrixTraversalTest.java b/src/test/practice_one/MatrixTraversalTest.java
new file mode 100644
index 0000000..e94950f
--- /dev/null
+++ b/src/test/practice_one/MatrixTraversalTest.java
@@ -0,0 +1,31 @@
+package test.practice_one;
+/*Обійти матрицю по спіралі і записати всі числа в одмірний масив.
+ Для матриці
+ [[1, 2, 3, 4],
+ [5, 6, 7, 8]
+ [9, 10, 11, 12]
+ [13, 14, 15, 16]]
+ вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
+*/
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_one.MatrixTraversal;
+
+public class MatrixTraversalTest {
+
+ MatrixTraversal matrixTraversal = new MatrixTraversal();
+
+ @Test
+ public void testPrint() throws Exception {
+ int[][] input = {{1, 2, 3, 4},
+ {5, 6, 7, 8},
+ {9, 10, 11, 12},
+ {13, 14, 15, 16}};
+
+ int[] expected = {1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10};
+ int[] extualResult = matrixTraversal.print(input);
+ Assert.assertArrayEquals(expected, extualResult);
+ }
+}
+
diff --git a/src/test/practice_one/SumDigitsTest.java b/src/test/practice_one/SumDigitsTest.java
new file mode 100644
index 0000000..d0fe01c
--- /dev/null
+++ b/src/test/practice_one/SumDigitsTest.java
@@ -0,0 +1,17 @@
+package test.practice_one;
+
+import practice_one.SumDigits;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SumDigitsTest {
+ @Test
+ public void testSum() throws Exception {
+ int input = -256;
+ int expected = 13;
+ SumDigits sumDigits = new SumDigits();
+ int extualResult = sumDigits.sum(input);
+ Assert.assertEquals(expected, extualResult);
+ System.out.println("Sum numbers in number " + input + " is " + extualResult + ".");
+ }
+}
diff --git a/src/test/practice_three/BinaryHeap.java b/src/test/practice_three/BinaryHeap.java
new file mode 100644
index 0000000..a088074
--- /dev/null
+++ b/src/test/practice_three/BinaryHeap.java
@@ -0,0 +1,145 @@
+package test.practice_three;
+import java.util.Arrays;
+/**
+ Реалізуйте структуру даних - Бінарна Купа (Binary Heap).
+ Конструктор проймає один параметр size.
+ Методи insert(int) що працює за O(logN) і poll(),
+ який видаляє і повертає максимальне число з купи і також працює за O(logN).
+ */
+public class BinaryHeap {
+ private int[] heap;
+ private int heapSize;
+
+ public BinaryHeap(int size){
+ heap = new int[size];
+ heapSize = 0;
+ Arrays.fill(heap, -1);
+ }
+
+ public int insert(int val){
+ int tmp;
+ int insertPoint = heapSize;
+
+ if(this.isFull() || val < 0){
+ throw new HeapException();
+ }
+
+ heap[heapSize] = val;
+
+ for(int i = getHeapSize(); getParent(i) >= 0; i = insertPoint) {
+ if (val < heap[getParent(i)]) {
+ tmp = heap[getParent(i)];
+ heap[getParent(i)] = heap[i];
+ heap[i] = tmp;
+ insertPoint = getParent(i);
+ }else if(val == heap[getParent(i)]){
+ throw new HeapException();
+ }
+ else{
+ insertPoint = i;
+ break;
+ }
+ }
+ heapSize++;
+ return insertPoint;
+ }
+
+ public int poll(){
+ if(this.isEmpty()){
+ throw new HeapException();
+ }
+ int result = heap[0];
+ int key = heap[heapSize - 1];
+ int tmp;
+ int insertPoint;
+
+ heap[0] = key;
+ heap[heapSize - 1] = -1;
+ heapSize--;
+
+ for(int i = 0; i < this.getHeapSize() - 1; i = insertPoint){
+ if(key > getLeftChild(key)){
+ tmp = getLeftChild(key);
+ heap[i] = tmp;
+ heap[2 * i + 1] = key;
+ insertPoint = 2 * i + 1;
+ }else if(key > getRightChild(key)){
+ tmp = getRightChild(key);
+ heap[i] = tmp;
+ heap[2 * i + 2] = key;
+ insertPoint = 2 * i + 2;
+ }else{
+ break;
+ }
+ }
+
+ return result;
+ }
+
+ public int peek(){
+ if(this.isEmpty()){
+ throw new HeapException();
+ }
+ return heap[0];
+ }
+
+ public boolean contains(int key){
+ for(int i = 0; i < this.heapSize; i++){
+ if(heap[i] == key){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean isEmpty(){
+ if(this.heapSize == 0){
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isFull(){
+ if(this.heapSize == heap.length){
+ return true;
+ }
+ return false;
+ }
+
+ public int getParent(int key){
+ int parent = -1;
+ if(key > 0){
+ parent = (key - 1) / 2;
+ }
+ return parent;
+ }
+
+ public int getLeftChild(int key){
+ for(int i = 0; (2 * i + 1) < this.heapSize; i++){
+ if(heap[i] == key){
+ return heap[2 * i + 1];
+ }
+ }
+ return -1;
+ }
+
+ public int getRightChild(int key){
+ for(int i = 0; (2 * i + 2) < this.heapSize; i++){
+ if(heap[i] == key){
+ return heap[2 * i + 2];
+ }
+ }
+ return -1;
+ }
+
+ public int getHeapSize(){
+ return this.heapSize;
+ }
+
+ public int[] getHeap(){
+ return this.heap;
+ }
+}
+
+class HeapException extends RuntimeException{
+}
\ No newline at end of file
diff --git a/src/test/practice_three/LongestStabilityPeriodTest.java b/src/test/practice_three/LongestStabilityPeriodTest.java
new file mode 100644
index 0000000..631d1df
--- /dev/null
+++ b/src/test/practice_three/LongestStabilityPeriodTest.java
@@ -0,0 +1,21 @@
+package test.practice_three;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+Найдовший Період Стабільності
+
+ Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США.
+ Необхідно знайти найдовший період стабільності.
+ Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1.
+ Повернути кількість місяців.
+ */
+public class LongestStabilityPeriodTest {
+
+ @Test
+ public void testCount() throws Exception {
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_three/ReversePolishNotationTest.java b/src/test/practice_three/ReversePolishNotationTest.java
new file mode 100644
index 0000000..8080a2f
--- /dev/null
+++ b/src/test/practice_three/ReversePolishNotationTest.java
@@ -0,0 +1,18 @@
+package test.practice_three;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ *Дано арифметичний вираз у вигляді Польського Інверсного запису.
+ Необхідно обчислити значення виразу і повернути його.
+ Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число.
+ */
+public class ReversePolishNotationTest {
+
+ @Test
+ public void testEvaluate() throws Exception {
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_two/AbcNumberTest.java b/src/test/practice_two/AbcNumberTest.java
new file mode 100644
index 0000000..ca0ff18
--- /dev/null
+++ b/src/test/practice_two/AbcNumberTest.java
@@ -0,0 +1,23 @@
+package test.practice_two;
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_two.AbcNumber;
+
+/**
+ Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j.
+ Необхідно повернути початкове число маючи конвертований рядок.
+ Наприклад:
+ Для "bcd" повернути 123
+ */
+public class AbcNumberTest {
+
+ @Test
+ public void testConvert() throws Exception {
+ String input = "d";
+ int expected = 123;
+ AbcNumber change = new AbcNumber();
+ int extualResult = change.convert(input);
+ Assert.assertEquals(expected, extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_two/AddBinaryTest.java b/src/test/practice_two/AddBinaryTest.java
new file mode 100644
index 0000000..7fa119b
--- /dev/null
+++ b/src/test/practice_two/AddBinaryTest.java
@@ -0,0 +1,32 @@
+package test.practice_two;
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_two.AddBinary;
+
+/**
+ * Додайте два беззнакових числа, що передаються як рядки.
+ * "101" + "100" = "1001"
+ */
+public class AddBinaryTest {
+ @Test
+ public void AddBinary() throws Exception {
+ String inputA = "101";
+ String inputB = "100";
+ String expected = "1001";
+ AddBinary addBinary = new AddBinary();
+ String extualResult = addBinary.add(inputA, inputB);
+ Assert.assertEquals(expected, extualResult);
+ }
+
+ @Test
+ public void AddBinaryLong() throws Exception {
+ String inputA = "10000000000000000000000000000000";
+ String inputB = "10000000000000000000000000000000";
+ String expected = "100000000000000000000000000000000";
+ AddBinary addBinary = new AddBinary();
+ String extualResult = addBinary.add(inputA, inputB);
+ Assert.assertEquals(expected, extualResult);
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/practice_two/AddNumberBase36Test.java b/src/test/practice_two/AddNumberBase36Test.java
new file mode 100644
index 0000000..5290113
--- /dev/null
+++ b/src/test/practice_two/AddNumberBase36Test.java
@@ -0,0 +1,19 @@
+package test.practice_two;
+
+import org.junit.Test;
+
+/**
+ * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z].
+ * Повернути суму чисел, також в системі 36.
+ * Наприклад:
+ * "9" + "1" = "a"
+ * "z" + "1" = "10"
+ */
+public class AddNumberBase36Test {
+
+ @Test
+ public void testAdd() throws Exception {
+
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_two/AverageNumberTest.java b/src/test/practice_two/AverageNumberTest.java
new file mode 100644
index 0000000..aa3ac57
--- /dev/null
+++ b/src/test/practice_two/AverageNumberTest.java
@@ -0,0 +1,24 @@
+package test.practice_two;
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_two.AverageNumber;
+
+/**
+ Знайти середнє значення двох цілих чисел.
+ Приклади:
+ average( 4, 6 ) = 5
+ average( -4, -7 ) = -5
+ average( -4, 7 ) = 1
+ */
+public class AverageNumberTest {
+ @Test
+ public void testAverage() throws Exception {
+ int inputA = 1073741824;
+ int inputB = 1073741824;
+ int expected = 1073741824;
+ AverageNumber averageNumber = new AverageNumber();
+ int extualResult = averageNumber.average(inputA,inputB);
+ Assert.assertEquals(expected, extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_two/PositiveAverageNumberTest.java b/src/test/practice_two/PositiveAverageNumberTest.java
new file mode 100644
index 0000000..f2cc05f
--- /dev/null
+++ b/src/test/practice_two/PositiveAverageNumberTest.java
@@ -0,0 +1,23 @@
+package test.practice_two;
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_two.PositiveAverageNumber;
+
+/**
+ Знайти середнє арифметике двух додатніх чисел.
+ Наприклад:
+ average( 2, 4 ) = 3
+ average( 4, 7 ) = 5
+ */
+public class PositiveAverageNumberTest {
+ @Test
+ public void testAverage() throws Exception {
+ int inputA = 1073741824;
+ int inputB = 1073741824;
+ int expected = 1073741824;
+ PositiveAverageNumber averageNumber = new PositiveAverageNumber();
+ int extualResult = averageNumber.average(inputA,inputB);
+ Assert.assertEquals(expected, extualResult);
+ }
+}
\ No newline at end of file
diff --git a/src/test/practice_two/SetZeroTest.java b/src/test/practice_two/SetZeroTest.java
new file mode 100644
index 0000000..de08118
--- /dev/null
+++ b/src/test/practice_two/SetZeroTest.java
@@ -0,0 +1,24 @@
+package test.practice_two;
+
+import org.junit.Assert;
+import org.junit.Test;
+import practice_two.SetZero;
+
+/**
+ Дано число. Треба замінити i-й біт замінити на нуль.
+ Наприклад:
+ для числа 6 в бінарному вигляді 110,
+ замінивши 2-й біт на нуль отримаємо 100 тобто 4.
+ 1<= i <= 32
+ */
+public class SetZeroTest {
+ @Test
+ public void set() throws Exception {
+ int inputA = 6;
+ int inputB = 2;
+ int expected = 4;
+ SetZero change = new SetZero();
+ int extualResult = change.set(inputA, inputB);
+ Assert.assertEquals(expected, extualResult);
+ }
+}
\ No newline at end of file