diff --git a/module2/pom.xml b/module2/pom.xml
new file mode 100644
index 0000000..7be2021
--- /dev/null
+++ b/module2/pom.xml
@@ -0,0 +1,31 @@
+
+
+ 4.0.0
+
+ org.example
+ module2
+ 1.0-SNAPSHOT
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ 5.9.0
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.9.0
+ test
+
+
+
+ 18
+ 18
+
+
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task1.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task1.java
new file mode 100644
index 0000000..f630266
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task1.java
@@ -0,0 +1,47 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дана матрица. Вывести на экран все нечетные столбцы, у которых
+ первый элемент больше последнего. */
+public class Task1 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 1) {
+ System.out.println("Matrix size must be greater than 1");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ int[][] matrix = new int[n][n];
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ String variableName = "matrix[" + i + "][" + j + "]";
+ matrix[i][j] = Parser.tryParseInt(scanner, variableName);
+ }
+ }
+ printOddColumnsWhereFirstElementIsGreaterThenLast(matrix);
+ }
+ }
+
+ public static void printOddColumnsWhereFirstElementIsGreaterThenLast(int[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int row = 0; row < matrix.length; ++row) {
+ boolean first = true;
+ for (int col = 0; col < matrix[row].length; col += 2) {
+ if (matrix[0][col] > matrix[matrix.length - 1][col]) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[row][col]);
+ }
+ }
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task10.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task10.java
new file mode 100644
index 0000000..94ebf33
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task10.java
@@ -0,0 +1,40 @@
+package by.training.dmgolub.array_of_arrays;
+
+public class Task10 {
+
+ public static void main(String[] args) {
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, -5, 6},
+ {7, 8, 9}
+ };
+ printPositiveElementsOfMainDiagonal(matrix);
+ }
+
+ /**
+ * Prints positive elements of the main diagonal of the given square matrix.
+ * @param matrix integer square matrix.
+ * @throws IllegalArgumentException when matrix is null of matrix is not
+ * a square matrix.
+ * @author DMGolub
+ */
+ public static void printPositiveElementsOfMainDiagonal(int[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (matrix.length > 0 && matrix.length != matrix[0].length) {
+ throw new IllegalArgumentException(
+ "The given matrix is not a square matrix");
+ }
+ boolean first = true;
+ for (int i = 0; i < matrix.length; ++i) {
+ if (matrix[i][i] > 0) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[i][i]);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task11.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task11.java
new file mode 100644
index 0000000..a697e71
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task11.java
@@ -0,0 +1,78 @@
+package by.training.dmgolub.array_of_arrays;
+
+/* Матрицу 10х20 заполнить случайными числами от 0 до 15.
+ Вывести на экран саму матрицу и номера строк,
+ в которых число 5 встречается 3 и более раз. */
+public class Task11 {
+
+ public static void main(String[] args) {
+ Integer[][] matrix = new Integer[10][20];
+ fillMatrix(matrix, 15);
+ printMatrix(matrix);
+ findAndPrintRows(matrix, 5, 3);
+ }
+
+ private static void printMatrix(Integer[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ boolean first = true;
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.printf("%2d", matrix[i][j]);
+ }
+ System.out.println();
+ }
+ }
+
+ /**
+ * Fills the given matrix with random integer numbers from 0 to given number.
+ * @param matrix integer matrix.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void fillMatrix(Integer[][] matrix, int number) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[i].length; ++j) {
+ matrix[i][j] = (int) (Math.random() * number);
+ }
+ }
+ }
+
+ /**
+ * Finds and prints rows of the given matrix in which the given number
+ * occurs at least the given number of times.
+ * @param matrix integer matrix,
+ * @param number integer number to be counter,
+ * @param minCount integer minimum count of number.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void findAndPrintRows(Integer[][] matrix, int number, int minCount) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ int numberCount = 0;
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (matrix[i][j] == number) {
+ ++numberCount;
+ }
+ }
+ if (numberCount >= minCount) {
+ System.out.print("Row " + i + ":");
+ for (int k = 0; k < matrix[i].length; ++k) {
+ System.out.printf(" %2d", matrix[i][k]);
+ }
+ System.out.println();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task12.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task12.java
new file mode 100644
index 0000000..63d6123
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task12.java
@@ -0,0 +1,52 @@
+package by.training.dmgolub.array_of_arrays;
+
+/* Отсортировать строки матрицы по возрастанию
+ и убыванию значений элементов. */
+public class Task12 {
+
+ public static void main(String[] args) {
+ Integer[][] matrix = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+ System.out.println("Matrix rows sorted in natural order:");
+ sortMatrixRows(matrix, true);
+ Task4.printMatrix(matrix);
+ System.out.println("Matrix rows sorted in reversed order:");
+ sortMatrixRows(matrix, false);
+ Task4.printMatrix(matrix);
+ }
+
+ /**
+ * Sorts matrix rows in natural order if naturalOrder is true and in reversed order otherwise.
+ * @param matrix integer matrix.
+ * @param naturalOrder boolean flag if natural order.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void sortMatrixRows(Integer[][] matrix, boolean naturalOrder) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int row = 0; row < matrix.length; ++row) {
+ for (int i = 0; i < matrix[row].length; ++i) {
+ for (int j = 1; j < matrix[row].length - i; ++j) {
+ if (naturalOrder) {
+ if (matrix[row][j] < matrix[row][j -1]) {
+ Integer temp = matrix[row][j];
+ matrix[row][j] = matrix[row][j -1];
+ matrix[row][j -1] = temp;
+ }
+ } else {
+ if (matrix[row][j] > matrix[row][j -1]) {
+ Integer temp = matrix[row][j];
+ matrix[row][j] = matrix[row][j -1];
+ matrix[row][j -1] = temp;
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task13.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task13.java
new file mode 100644
index 0000000..6cfb007
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task13.java
@@ -0,0 +1,52 @@
+package by.training.dmgolub.array_of_arrays;
+
+/* Отсортировать столбцы матрицы по возрастанию
+ и убыванию значений элементов. */
+public class Task13 {
+
+ public static void main(String[] args) {
+ Integer[][] matrix = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+ System.out.println("Matrix columns sorted in natural order:");
+ sortMatrixColumns(matrix, true);
+ Task4.printMatrix(matrix);
+ System.out.println("Matrix columns sorted in reversed order:");
+ sortMatrixColumns(matrix, false);
+ Task4.printMatrix(matrix);
+ }
+
+ /**
+ * Sorts matrix columns in natural order if naturalOrder is true and in reversed order otherwise.
+ * @param matrix integer matrix.
+ * @param naturalOrder boolean flag if natural order.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void sortMatrixColumns(Integer[][] matrix, boolean naturalOrder) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int column = 0; column < matrix.length; ++column) {
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 1; j < matrix.length - i; ++j) {
+ if (naturalOrder) {
+ if (matrix[j][column] < matrix[j - 1][column]) {
+ Integer temp = matrix[j][column];
+ matrix[j][column] = matrix[j - 1][column];
+ matrix[j - 1][column] = temp;
+ }
+ } else {
+ if (matrix[j][column] > matrix[j - 1][column]) {
+ Integer temp = matrix[j][column];
+ matrix[j][column] = matrix[j - 1][column];
+ matrix[j - 1][column] = temp;
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task14.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task14.java
new file mode 100644
index 0000000..e860f88
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task14.java
@@ -0,0 +1,90 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Сформировать случайную матрицу m x n, состоящую
+ из нулей и единиц, причем в каждом столбце число
+ единиц равно номеру столбца. */
+public class Task14 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int m = parseMatrixSize("m (number of rows)", scanner);
+ int n = parseMatrixSize("n (number of columns)", scanner);
+ while (m < n) {
+ System.out.println("Number of rows can not be " +
+ "less then number of columns. Please try again");
+ m = parseMatrixSize("m (number of rows)", scanner);
+ n = parseMatrixSize("n (number of columns)", scanner);
+ }
+ int[][] matrix = createRandomMatrix(m, n);
+ printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Creates random matrix of 0's and 1's.
+ * Number of 1's in each column is equal to column index (starts from 1).
+ * @param rows integer number of rows,
+ * @param columns integer number of columns.
+ * @return generated random matrix.
+ * @throws IllegalArgumentException when number of rows is less than
+ * number of columns.
+ * @author DMGolub
+ */
+ public static int[][] createRandomMatrix(int rows, int columns) {
+ if (rows < columns) {
+ throw new IllegalArgumentException("Number of rows " +
+ "can not be less than number of columns");
+ }
+ int[][] matrix = new int[rows][columns];
+ for (int columnIndex = 0; columnIndex < columns; ++columnIndex) {
+ int counter = 0;
+ while (counter <= columnIndex) {
+ int rowIndex = (int) (Math.random() * rows);
+ if (matrix[rowIndex][columnIndex] == 0) {
+ matrix[rowIndex][columnIndex] = 1;
+ ++counter;
+ }
+ }
+ }
+ return matrix;
+ }
+
+ /**
+ * Parses matrix size with provided name from console.
+ * Checks if the size is greater or equal to 1.
+ * @param sizeName String matrix size name,
+ * @param scanner Scanner.
+ * @return matrix size.
+ * @author DMGolub
+ */
+ private static int parseMatrixSize(String sizeName, Scanner scanner) {
+ int size = Parser.tryParseInt(scanner, "matrix size " + sizeName);
+ while (size < 1) {
+ System.out.println("Matrix size must be " +
+ "greater or equal to 1. Please try again.");
+ size = Parser.tryParseInt(scanner, "matrix size " + sizeName);
+ }
+ return size;
+ }
+
+ private static void printMatrix(int[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ boolean first = true;
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[i][j]);
+ }
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task15.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task15.java
new file mode 100644
index 0000000..a8ffdc4
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task15.java
@@ -0,0 +1,62 @@
+package by.training.dmgolub.array_of_arrays;
+
+/* Найти наибольший элемент матрицы и заменить
+ все нечетные элементы на него. */
+public class Task15 {
+
+ public static void main(String[] args) {
+ Integer[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+ System.out.println("Initial matrix:");
+ Task4.printMatrix(matrix);
+ int max = findMaxElement(matrix);
+ replaceOddNumbers(matrix, max);
+ System.out.println("Matrix with replaced odd elements:");
+ Task4.printMatrix(matrix);
+ }
+
+ /**
+ * Finds maximum element in the given matrix.
+ * @param matrix Integer matrix,
+ * @return maximum element.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static int findMaxElement(Integer[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ int max = Integer.MIN_VALUE;
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (matrix[i][j] > max) {
+ max = matrix[i][j];
+ }
+ }
+ }
+ return max;
+ }
+
+ /**
+ * Replaces all odd elements in the matrix by the given number.
+ * @param matrix Integer matrix,
+ * @param number integer number to replace odd elements.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void replaceOddNumbers(Integer[][] matrix, int number) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (matrix[i][j] % 2 == 1) {
+ matrix[i][j] = number;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task16.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task16.java
new file mode 100644
index 0000000..225bde4
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task16.java
@@ -0,0 +1,52 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Магическим квадратом порядка n называется квадратная
+ матрица размера n x n, составленная из чисел 1, 2, 3, ..., n^2
+ так, что суммы по каждому столбцу, каждой строке и каждой
+ из двух больших диагоналей равны между собой.
+ Построить такой квадрат. Пример магического квадрата порядка 3:
+ 6 1 8
+ 7 5 3
+ 2 9 4 */
+public class Task16 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "magic square size");
+ while (n < 1 && n != 2) {
+ System.out.println("Square size can not be " +
+ "less than 1 and equal to 2. Please try again.");
+ n = Parser.tryParseInt(scanner, "magic square size");
+ }
+ Integer[][] magicSquare = new Integer[n][n];
+ fillMagicSquare(magicSquare);
+ System.out.println("Magic square:");
+ Task4.printMatrix(magicSquare);
+
+ }
+ }
+
+ /**
+ * Fills the given matrix with numbers following the rule of magic square:
+ * the sums for each column, each row and each of the two large diagonals
+ * are equal to each other. Matrix size can not be 2 x 2.
+ * @param squareMatrix Integer square matrix.
+ * @throws IllegalArgumentException when matrix is null or matrix is not square.
+ * @author DMGolub
+ */
+ public static void fillMagicSquare(Integer[][] squareMatrix) {
+ if (squareMatrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (squareMatrix.length != squareMatrix[0].length) {
+ throw new IllegalArgumentException("Matrix must be square");
+ }
+ if (squareMatrix.length == 2) {
+ throw new IllegalArgumentException("Matrix size can not be 2");
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task2.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task2.java
new file mode 100644
index 0000000..707ef43
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task2.java
@@ -0,0 +1,48 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дана квадратная матрица. Вывести на экран
+ все элементы, стоящие на диагонали. */
+public class Task2 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 1) {
+ System.out.println("Matrix size must be greater than 1");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ int[][] matrix = new int[n][n];
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ String variableName = "matrix[" + i + "][" + j + "]";
+ matrix[i][j] = Parser.tryParseInt(scanner, variableName);
+ }
+ }
+ printDiagonal(matrix);
+ }
+ }
+
+ /**
+ * Prints elements located on the diagonal of the matrix.
+ * @param matrix integer square matrix.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void printDiagonal(int[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ boolean first = true;
+ for (int i = 0; i < matrix.length; ++i) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[i][i]);
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task3.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task3.java
new file mode 100644
index 0000000..f923532
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task3.java
@@ -0,0 +1,75 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+public class Task3 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 1) {
+ System.out.println("Matrix size must be greater than 1");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ int[][] matrix = new int[n][n];
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ String variableName = "matrix[" + i + "][" + j + "]";
+ matrix[i][j] = Parser.tryParseInt(scanner, variableName);
+ }
+ }
+ int row = Parser.tryParseInt(scanner, "matrix row to print");
+ System.out.print("Row " + row + ": ");
+ printRow(matrix, row);
+ int column = Parser.tryParseInt(scanner, "matrix column to print");
+ System.out.print("Column " + column + ": ");
+ printColumn(matrix, column);
+ }
+ }
+
+ public static void printRow(int[][] matrix, int row) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (row < 0) {
+ throw new IllegalArgumentException("Matrix row index can not be less than 0");
+ }
+ if (row >= matrix.length) {
+ throw new IllegalArgumentException("Row index can not " +
+ "be greater than matrix.length " + matrix.length);
+ }
+ boolean first = true;
+ for (int col = 0; col < matrix[row].length; ++col) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[row][col]);
+ }
+ System.out.println();
+ }
+
+ public static void printColumn(int[][] matrix, int column) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (column < 0) {
+ throw new IllegalArgumentException("Matrix column index can not be less than 0");
+ }
+ if (matrix.length > 0 && column >= matrix[0].length) {
+ throw new IllegalArgumentException("Matrix column index can not " +
+ "be greater than matrix width: " + matrix[0].length);
+ }
+ boolean first = true;
+ for (int row = 0; row < matrix.length; ++row) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[row][column]);
+ }
+ System.out.println();
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task4.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task4.java
new file mode 100644
index 0000000..0324034
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task4.java
@@ -0,0 +1,79 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Сформировать квадратную матрицу порядка N по заданному образу (n - четное).
+ 1 2 3 ... n
+ n n-1 n-2 ... 1
+ 1 2 3 ... n
+ ... ... ... ... ...
+ n n-1 n-2 ... 1 */
+public class Task4 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 2 && n % 2 == 1) {
+ System.out.println("Matrix size must be greater than 1 and even");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ Integer[][] matrix = new Integer[n][n];
+ fillMatrix(matrix);
+ printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Fills matrix following the principle:
+ * { 1 2 3 ... n }
+ * { n n-1 n-2 ... 1 }
+ * { 1 2 3 ... n }
+ * { ... ... ... ... ...}
+ * { n n-1 n-2 ... 1 }
+ * @param matrix integer square matrix.
+ * @throws IllegalArgumentException when matrix is null or matrix size is odd.
+ * @author DMGolub
+ */
+ public static void fillMatrix(Integer[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (matrix.length == 0 || matrix.length % 2 == 1) {
+ throw new IllegalArgumentException("Matrix size must be greater than 0 and even");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[0].length; ++j) {
+ if (i % 2 == 1) {
+ matrix[i][j] = matrix.length - j;
+ } else {
+ matrix[i][j] = j + 1;
+ }
+ }
+ }
+ }
+
+ /**
+ * Prints the given matrix;
+ * @param matrix matrix.
+ * @throws IllegalArgumentException if matrix is null.
+ * @author DMGolub
+ */
+ public static void printMatrix(T[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ boolean first = true;
+ for (int j = 0; j < matrix[i].length; ++j) {
+ if (!first) {
+ System.out.print(" ");
+ }
+ first = false;
+ System.out.print(matrix[i][j]);
+ }
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task5.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task5.java
new file mode 100644
index 0000000..561c293
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task5.java
@@ -0,0 +1,57 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Сформировать квадратную матрицу порядка N по заданному образу (n - четное).
+ 1 1 1 ... 1 1
+ 2 2 2 ... 2 0
+ 3 3 3 ... 0 0
+ ... ... ... ... ... ...
+ n-1 n-1 0 ... 0 0
+ n 0 0 ... 0 0 */
+public class Task5 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 2 && n % 2 == 1) {
+ System.out.println("Matrix size must be greater than 1 and even");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ Integer[][] matrix = new Integer[n][n];
+ fillMatrix(matrix);
+ Task4.printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Fills matrix following the principle:
+ * { 1 1 1 ... 1 1 }
+ * { 2 2 2 ... 2 0 }
+ * { 3 3 3 ... 0 0 }
+ * { ... ... ... ... ... ...}
+ * { n-1 n-1 0 ... 0 0 }
+ * { n 0 0 ... 0 0 }
+ * @param matrix integer square matrix.
+ * @throws IllegalArgumentException when matrix is null or matrix size is odd.
+ * @author DMGolub
+ */
+ public static void fillMatrix(Integer[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (matrix.length == 0 || matrix.length % 2 == 1) {
+ throw new IllegalArgumentException("Matrix size must be greater than 0 and even");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix.length - i; ++j) {
+ matrix[i][j] = i + 1;
+ }
+ for (int j = matrix.length - i; j < matrix[0].length; ++j) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task6.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task6.java
new file mode 100644
index 0000000..5ecbca1
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task6.java
@@ -0,0 +1,61 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Сформировать квадратную матрицу порядка n
+ по заданному образцу (n - четное):
+ { 1 1 1 ... 1 1 1 }
+ { 0 1 1 ... 1 1 0 }
+ { 0 0 1 ... 1 0 0 }
+ { .. .. .. ... .. .. ..}
+ { 0 1 1 ... 1 1 0 }
+ { 1 1 1 ... 1 1 1 } */
+public class Task6 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 2 && n % 2 == 1) {
+ System.out.println("Matrix size must be greater than 1 and even");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ Integer[][] matrix = new Integer[n][n];
+ fillMatrix(matrix);
+ Task4.printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Fills matrix following the principle:
+ * { 1 1 1 ... 1 1 1 }
+ * { 0 1 1 ... 1 1 0 }
+ * { 0 0 1 ... 1 0 0 }
+ * { .. .. .. ... .. .. ..}
+ * { 0 1 1 ... 1 1 0 }
+ * { 1 1 1 ... 1 1 1 }
+ * @param matrix integer square matrix.
+ * @throws IllegalArgumentException when matrix is null or matrix size is odd.
+ * @author DMGolub
+ */
+ public static void fillMatrix(Integer[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ if (matrix.length == 0 || matrix.length % 2 == 1) {
+ throw new IllegalArgumentException("Matrix size must be greater than 0 and even");
+ }
+ for (int i = 0; i < matrix.length; ++i) {
+ if (i < matrix.length / 2) {
+ for (int j = i; j < matrix.length - i; ++j) {
+ matrix[i][j] = 1;
+ }
+ } else {
+ for (int j = matrix.length - i - 1; j <= i; ++j) {
+ matrix[i][j] = 1;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task7.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task7.java
new file mode 100644
index 0000000..a46868a
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task7.java
@@ -0,0 +1,50 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Сформировать квадратную матрицу порядка N по правилу:
+ a[i][j] = sin((i * i - j * j) / n)
+ и подсчитать количество положительных элементов в ней. */
+public class Task7 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "matrix size");
+ while (n < 1) {
+ System.out.println("Matrix size must be greater than 0");
+ n = Parser.tryParseInt(scanner, "matrix size");
+ }
+ Double[][] matrix = new Double[n][n];
+ System.out.println("There are " +
+ fillMatrixAndCountPositive(matrix) + " positive values.");
+ System.out.println("Matrix:");
+ Task4.printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Fills matrix following the rule: a[i][j] = sin((i * i - j * j) / n)
+ * and counts the number of positive elements.
+ * @param matrix double square matrix.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static int fillMatrixAndCountPositive(Double[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ int positiveCount = 0;
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix.length; ++j) {
+ double value = Math.sin((i * i - j * j) / (double) matrix.length);
+ if (value > 0) {
+ ++positiveCount;
+ }
+ matrix[i][j] = value;
+ }
+ }
+ return positiveCount;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task8.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task8.java
new file mode 100644
index 0000000..90dc88d
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task8.java
@@ -0,0 +1,88 @@
+package by.training.dmgolub.array_of_arrays;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* В числовой матрице поменять местами два любых столбца,
+ т.е. все элементы одного столбца поставить на соответствующие
+ им позиции другого, а элементы второго переместить в первый.
+ Номера столбцов вводит пользователь с клавиатуры.
+ */
+public class Task8 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = parseMatrixSize("n", 1, scanner);
+ int m = parseMatrixSize("m", 2, scanner);
+ Integer[][] matrix = new Integer[n][m];
+ readMatrix(matrix, scanner);
+
+ System.out.println("Initial matrix:");
+ Task4.printMatrix(matrix);
+
+ int columnIndex1 = readColumnIndex("first column index", m - 1, scanner);
+ int columnIndex2 = readColumnIndex("second column index", m - 1, scanner);
+ swapColumns(matrix, columnIndex1, columnIndex2);
+ System.out.println("Matrix with swapped columns:");
+ Task4.printMatrix(matrix);
+ }
+ }
+
+ /**
+ * Swaps values of two given columns.
+ * @param matrix integer matrix.
+ * @param columnIndex1 integer first column index,
+ * @param columnIndex2 integer second column index.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static void swapColumns(Integer[][] matrix, int columnIndex1, int columnIndex2) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ for (int k = 0; k < matrix.length; ++k) {
+ int temp = matrix[k][columnIndex1];
+ matrix[k][columnIndex1] = matrix[k][columnIndex2];
+ matrix[k][columnIndex2] = temp;
+ }
+ }
+
+ /**
+ * Parses matrix size with provided name from console.
+ * Checks if the size is greater or equal to the given threshold.
+ * @param sizeName String matrix size name,
+ * @param minSize integer minimum size value,
+ * @param scanner Scanner.
+ * @return matrix size.
+ * @author DMGolub
+ */
+ private static int parseMatrixSize(String sizeName, int minSize, Scanner scanner) {
+ int size = Parser.tryParseInt(scanner, "matrix size " + sizeName);
+ while (size < minSize) {
+ System.out.println("Matrix size must be greater or equal to "
+ + minSize + ". Please try again.");
+ size = Parser.tryParseInt(scanner, "matrix size " + sizeName);
+ }
+ return size;
+ }
+
+ private static void readMatrix(Integer[][] matrix, Scanner scanner) {
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[0].length; ++j) {
+ String variableName = "matrix[" + i + "][" + j + "]";
+ matrix[i][j] = Parser.tryParseInt(scanner, variableName);
+ }
+ }
+ }
+
+ private static int readColumnIndex(String name, int maxValue, Scanner scanner) {
+ int index = Parser.tryParseInt(scanner, name);
+ while (index < 0 || index > maxValue) {
+ System.out.print("Column index can not be less than 0 or greater than "
+ + maxValue + ". Please try again.");
+ index = Parser.tryParseInt(scanner, name);
+ }
+ return index;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task9.java b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task9.java
new file mode 100644
index 0000000..e43c19b
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/array_of_arrays/Task9.java
@@ -0,0 +1,45 @@
+package by.training.dmgolub.array_of_arrays;
+
+/* Задана матрица неотрицательных чисел.
+ Посчитать сумму элементов в каждом столбце.
+ Определить, какой столбец содержит максимальную сумму. */
+public class Task9 {
+
+ public static void main(String[] args) {
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+ System.out.println("Column with maximal sum of elements: "
+ + findColumnWithMaxSumOfElements(matrix));
+ }
+
+ /**
+ * Finds column with maximal sum of column elements.
+ * @param matrix int matrix.
+ * @return index of column with maximal sum of column elements.
+ * @throws IllegalArgumentException when matrix is null.
+ * @author DMGolub
+ */
+ public static int findColumnWithMaxSumOfElements(int[][] matrix) {
+ if (matrix == null) {
+ throw new IllegalArgumentException("Matrix can not be null");
+ }
+ long[] sums = new long[matrix[0].length];
+ for (int i = 0; i < matrix.length; ++i) {
+ for (int j = 0; j < matrix[i].length; ++j) {
+ sums[j] += matrix[i][j];
+ }
+ }
+ long max = Long.MIN_VALUE;
+ int index = 0;
+ for (int k = 0; k < sums.length; ++k) {
+ if (sums[k] > max) {
+ max = sums[k];
+ index = k;
+ }
+ }
+ return index;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Point.java b/module2/src/main/java/by/training/dmgolub/decomposing/Point.java
new file mode 100644
index 0000000..d17749e
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Point.java
@@ -0,0 +1,47 @@
+package by.training.dmgolub.decomposing;
+
+import java.util.Objects;
+
+/**
+ * Represents a point with 2 double coordinates x and y.
+ * @author DMGolub
+ */
+public class Point {
+
+ private double x;
+ private double y;
+
+ public Point(double x, double y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public double getX() {
+ return x;
+ }
+
+ public void setX(double x) {
+ this.x = x;
+ }
+
+ public double getY() {
+ return y;
+ }
+
+ public void getY(double y) {
+ this.y = y;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Point point = (Point) o;
+ return Double.compare(point.x, x) == 0 && Double.compare(point.y, y) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(x, y);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task1.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task1.java
new file mode 100644
index 0000000..2ba98e6
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task1.java
@@ -0,0 +1,54 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Написать метод (методы) для нахождения наибольшего общего
+ делителя и наименьшего общего кратного двух натуральных чисел:
+ НОК(А, В) = A * B / НОД(A, B) */
+public class Task1 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int a = Parser.tryParseInt(scanner, "a");
+ int b = Parser.tryParseInt(scanner, "b");
+ System.out.println("Greatest common divisor = "
+ + greatestCommonDivisor(a, b));
+ System.out.println("Greatest common multiple = "
+ + smallestCommonMultiple(a, b));
+ }
+ }
+
+ /**
+ * Calculates the greatest common divisor of two given numbers.
+ * @param a int first number,
+ * @param b int second number.
+ * @return greatest common divisor.
+ * @author DMGolub
+ */
+ public static int greatestCommonDivisor(int a, int b) {
+ while (a != 0 && b != 0) {
+ if (Math.abs(a) > Math.abs(b)) {
+ a = a % b;
+ } else {
+ b = b % a;
+ }
+ }
+ return a + b;
+ }
+
+ /**
+ * Calculates the smallest common multiple of two given numbers.
+ * @param a int first number,
+ * @param b int second number.
+ * @return greatest common divisor.
+ * @author DMGolub
+ */
+ public static int smallestCommonMultiple(int a, int b) {
+ if (a == 0 || b == 0) {
+ return 0;
+ }
+ return Math.abs(a * b) / greatestCommonDivisor(a, b);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task10.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task10.java
new file mode 100644
index 0000000..5376fb3
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task10.java
@@ -0,0 +1,62 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дано натуральное число N. Написать метод (методы) для формирования
+ массива, элементами которого являются цифры числа N. */
+public class Task10 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "N");
+ while (n < 1) {
+ System.out.println("N can not be less than 1. Please try again.");
+ n = Parser.tryParseInt(scanner, "N");
+ }
+ int[] digits = splitNumber(n);
+ printArray(digits);
+ }
+ }
+
+ /**
+ * Forms an array of digits of the given natural number as its elements.
+ * @param number integer number.
+ * @return array of integer number representing digits of the given number.
+ * @throws IllegalArgumentException when the number is less than 1.
+ * @author DMGolub
+ */
+ public static int[] splitNumber(int number) {
+ if (number < 1) {
+ throw new IllegalArgumentException("Number can not be less than 1");
+ }
+ int digitCount = String.valueOf(number).length();
+ int[] digits = new int[digitCount];
+ for (int i = 0; i < digitCount; i++) {
+ digits[digitCount - i - 1] = number % 10;
+ number /= 10;
+ }
+ return digits;
+ }
+
+ /**
+ * Prints the given array.
+ * @param array integer array.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static void printArray(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ boolean first = true;
+ for (int item : array) {
+ if (!first) {
+ System.out.print(", ");
+ }
+ first = false;
+ System.out.print(item);
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task11.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task11.java
new file mode 100644
index 0000000..2afff62
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task11.java
@@ -0,0 +1,45 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Написать метод (методы), определяющмй, в каком из
+ данных двух чисел больше цифр. */
+public class Task11 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ double number1 = Parser.tryParseDouble(scanner, "first number");
+ double number2 = Parser.tryParseDouble(scanner, "second number");
+ int digitCountDifference = countDigits(number1) - countDigits(number2);
+ if (digitCountDifference > 0) {
+ System.out.println("The first number contains more digits than the second.");
+ } else if (digitCountDifference < 0) {
+ System.out.println("The second number contains more digits than the first.");
+ } else {
+ System.out.println("The numbers contain the same number of digits.");
+ }
+ }
+ }
+
+ /**
+ * Counts the number of digits in the given number.
+ * @param number double number.
+ * @return number of digits.
+ * @author DMGolub
+ */
+ public static int countDigits(double number) {
+ int count = 0;
+ String numberStr = String.valueOf(number);
+ for (int i = 0; i < numberStr.length(); i++) {
+ if (Character.isDigit(numberStr.charAt(i))) {
+ count++;
+ }
+ }
+ if (numberStr.endsWith(".0")) {
+ count--;
+ }
+ return count;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task12.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task12.java
new file mode 100644
index 0000000..efcdfc6
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task12.java
@@ -0,0 +1,68 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Даны натуральные числа K и N. Написать метод (методы) формирования
+ массива А, элементами которого являются числа, сумма цифр которых
+ равна K и которые не больше N. */
+public class Task12 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int sumOfDigits = parseNaturalInt(scanner, "sum of digits (K)");
+ int maxValue = parseNaturalInt(scanner, "maximum value (N)");
+ int[] array = formArray(sumOfDigits, maxValue);
+ printArray(array);
+ }
+ }
+
+ /**
+ * Parses natural integer number from console.
+ * @param scanner Scanner.
+ * @param name String variable name.
+ * @return parsed integer number.
+ * @throws IllegalArgumentException when scanner or variable name is null.
+ * @author DMGolub
+ */
+ public static int parseNaturalInt(Scanner scanner, String name) {
+ if (scanner == null) {
+ throw new IllegalArgumentException("Scanner can not be null");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name can not be null");
+ }
+ int value = Parser.tryParseInt(scanner, name);
+ while (value < 1) {
+ System.out.println(name + " can not be negative or zero. Please try again.");
+ value = Parser.tryParseInt(scanner, name);
+ }
+ return value;
+ }
+
+ public static int[] formArray(int sumOfDigits, int maxValue) {
+
+ return new int[0]; // temp
+ }
+
+ /**
+ * Prints the given array.
+ * @param array integer array.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static void printArray(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ boolean first = true;
+ for (int element : array) {
+ if (!first) {
+ System.out.print(", ");
+ }
+ first = false;
+ System.out.print(element);
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task13.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task13.java
new file mode 100644
index 0000000..e2ee524
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task13.java
@@ -0,0 +1,71 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Два простых числа называются "близнецами", если они отличаются
+ друг от друга на 2 (например, 41 и 43).
+ Найти и напечатать все пары "близнецов" из отрезка [n, 2 * n],
+ где n - заданное натуральное число больше 2.
+ Для решения задачи использовать декомпозицию. */
+public class Task13 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.println("This program finds all prime twins in the range [N, N * 2].");
+ int n = Parser.tryParseInt(scanner, "N (N > 2)");
+ while (n < 3) {
+ System.out.println("N can not be less than 3. Please try again.");
+ n = Parser.tryParseInt(scanner, "N (N > 2)");
+ }
+ printPrimeTwins(n, n * 2);
+ }
+ }
+
+ /**
+ * Prints all the prime twins found in the given range of natural numbers.
+ * @param fromNumber integer first number of the range,
+ * @param toNumber integer last number of the range.
+ * @throws IllegalArgumentException when any of bounds is negative.
+ * @author DMGolub
+ */
+ public static void printPrimeTwins(int fromNumber, int toNumber) {
+ if (fromNumber < 0 || toNumber < 0) {
+ throw new IllegalArgumentException("Bound can not be negative");
+ }
+ if (fromNumber > toNumber) {
+ int temp = fromNumber;
+ fromNumber = toNumber;
+ toNumber = temp;
+ }
+ int counter = 0;
+ for (int i = fromNumber; i <= toNumber - 2; i++) {
+ if (isPrimeNumber(i) && isPrimeNumber(i + 2)) {
+ System.out.println(i + ", " + (i + 2));
+ counter++;
+ }
+ }
+ if (counter == 0) {
+ System.out.println("No twins found");
+ }
+ }
+
+ /**
+ * Determines if the given number is prime.
+ * @param number integer.
+ * @return true if the given number is prime and false otherwise.
+ * @author DMGolub
+ */
+ public static boolean isPrimeNumber(int number) {
+ if (number < 2) {
+ return false;
+ }
+ for (int i = 2; i <= number / 2; ++i) {
+ if (number % i == 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task14.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task14.java
new file mode 100644
index 0000000..fc0063c
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task14.java
@@ -0,0 +1,91 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Натуральное число, в записи которого n цифр, называется числом Армстронга,
+ если сумма его цифр, возведенная в степень n, равна самому числу.
+ Найти все числа Армстронга от 1 до k.
+ Для решения задачи использовать декомпозицию. */
+public class Task14 {
+
+ private static final int MIN_NUMBER = 1;
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+
+ int k = Parser.tryParseInt(scanner, "K (K > 1)");
+ while (k < 2) {
+ System.out.println("K can not be less than 2. Please try again.");
+ k = Parser.tryParseInt(scanner, "K (K > 1)");
+ }
+ printArmstrongNumbers(MIN_NUMBER, k);
+ }
+ }
+
+ /**
+ * Prints all the Armstrong numbers found in the given range of natural numbers.
+ * @param fromNumber integer first number of the range,
+ * @param toNumber integer last number of the range.
+ * @throws IllegalArgumentException when any of bounds is negative.
+ * @author DMGolub
+ */
+ public static void printArmstrongNumbers(int fromNumber, int toNumber) {
+ if (fromNumber < 0 || toNumber < 0) {
+ throw new IllegalArgumentException("Bound can not be negative");
+ }
+ if (fromNumber > toNumber) {
+ int temp = fromNumber;
+ fromNumber = toNumber;
+ toNumber = temp;
+ }
+ int counter = 0;
+ for (int i = fromNumber; i <= toNumber; i++) {
+ if (isArmstrongNumber(i)) {
+ System.out.println(i);
+ counter++;
+ }
+ }
+ if (counter == 0) {
+ System.out.println("No Armstrong numbers found");
+ }
+ }
+
+ /**
+ * Determines if the given number is an Armstrong number.
+ * @param number integer number.
+ * @return true if the number is an Armstrong number and false otherwise.
+ * @author DMGolub
+ */
+ public static boolean isArmstrongNumber(int number) {
+ int count = countDigits(number);
+ int sumOfPowers = 0;
+ int temp = number;
+ while (temp != 0) {
+ sumOfPowers += Math.pow(temp % 10, count);
+ temp /= 10;
+ }
+ return sumOfPowers == number;
+ }
+
+ /**
+ * Counts the number of digits in the given number.
+ * @param number double number.
+ * @return number of digits.s
+ * @author DMGolub
+ */
+ public static int countDigits(double number) {
+ int count = 0;
+ String numberStr = String.valueOf(number);
+ for (int i = 0; i < numberStr.length(); i++) {
+ if (Character.isDigit(numberStr.charAt(i))) {
+ count++;
+ }
+ }
+ if (numberStr.endsWith(".0")) {
+ count--;
+ }
+ return count;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task17.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task17.java
new file mode 100644
index 0000000..96de562
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task17.java
@@ -0,0 +1,60 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Из заданного числа вычли сумму его цифр. Из результата
+ вновь вычли сумму его цифр и т.д. Сколько таких действий
+ надо произвести, чтобы получить нуль?
+ Для реления задачи ипользовать декомпоозицию. */
+public class Task17 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "number");
+ while (n < 0) {
+ System.out.println("Number can not be negative. Please try again.");
+ n = Parser.tryParseInt(scanner, "number");
+ }
+ int count = countIterations(n);
+ System.out.println(count + " iteration(s) needed");
+ }
+ }
+
+ /**
+ * Determines the number of iterations required to bring the given number
+ * to zero by subtracting the sum of its digits from the number.
+ * @param number integer number.
+ * @return number of iterations.
+ * @throws IllegalArgumentException when number is negative.
+ * @author DMGolub
+ */
+ public static int countIterations(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("Number can not be negative");
+ }
+ int count = 0;
+ while (number != 0) {
+ number -= sumOfDigits(number);
+ count++;
+ System.out.println("Iteration: " + count + " number = " + number);
+ }
+ return count;
+ }
+
+ /**
+ * Calculates the sum of digits of the given number.
+ * @param number integer number.
+ * @return sum of digits of the given number.
+ * @author DMGolub
+ */
+ public static int sumOfDigits(int number) {
+ int sum = 0;
+ while (number != 0) {
+ sum += number % 10;
+ number /= 10;
+ }
+ return Math.abs(sum);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task2.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task2.java
new file mode 100644
index 0000000..ec298e4
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task2.java
@@ -0,0 +1,53 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Написать метод (методы) для нахождения наибольшего
+ общего делителя четырех натуральных чисел. */
+public class Task2 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int a = Parser.tryParseInt(scanner, "a");
+ int b = Parser.tryParseInt(scanner, "b");
+ int c = Parser.tryParseInt(scanner, "c");
+ int d = Parser.tryParseInt(scanner, "d");
+ System.out.println("Greatest common divisor = "
+ + greatestCommonDivisor(a, b, c, d));
+ }
+ }
+
+ /**
+ * Calculates the greatest common divisor of four given numbers.
+ * @param a int first number,
+ * @param b int second number,
+ * @param c int third number,
+ * @param d int fourth number.
+ * @return greatest common divisor.
+ * @author DMGolub
+ */
+ public static int greatestCommonDivisor(int a, int b, int c, int d) {
+ return greatestCommonDivisor(greatestCommonDivisor(a, b),
+ greatestCommonDivisor(c, d));
+ }
+
+ /**
+ * Calculates the greatest common divisor of two given numbers.
+ * @param a int first number,
+ * @param b int second number.
+ * @return greatest common divisor.
+ * @author DMGolub
+ */
+ public static int greatestCommonDivisor(int a, int b) {
+ while (a != 0 && b != 0) {
+ if (Math.abs(a) > Math.abs(b)) {
+ a = a % b;
+ } else {
+ b = b % a;
+ }
+ }
+ return a + b;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task3.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task3.java
new file mode 100644
index 0000000..3c31f26
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task3.java
@@ -0,0 +1,52 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.awt.color.ICC_ColorSpace;
+import java.util.Scanner;
+
+/* Вычислить площадь правильного шестиугольника со стороной a,
+ используя метод вычисления площади треугольника. */
+public class Task3 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ double a = Parser.tryParseDouble(scanner, "a");
+ while (a < 0) {
+ System.out.println("Hexagon side size can not "
+ + "be negative. Please try again");
+ a = Parser.tryParseDouble(scanner, "a");
+ }
+ System.out.println("Hexagon area = " + calculateRegularHexagonArea(a));
+ }
+ }
+
+ /**
+ * Calculates the area of a regular hexagon with a given side length.
+ * @param sideLength double hexagon side length.
+ * @return hexagon area.
+ * @throws IllegalArgumentException when side length is negative.
+ * @author DMGolub
+ */
+ public static double calculateRegularHexagonArea(double sideLength) {
+ if (sideLength < 0) {
+ throw new IllegalArgumentException("Hexagon side length can not be negative");
+ }
+ final int HEXAGON_SIDES_NUMBER = 6;
+ return HEXAGON_SIDES_NUMBER * calculateRegularTriangleArea(sideLength);
+ }
+
+ /**
+ * Calculates the area of a regular triangle with a given side length.
+ * @param sideLength double triangle side length.
+ * @return triangle area.
+ * @throws IllegalArgumentException when side length is negative.
+ * @author DMGolub
+ */
+ public static double calculateRegularTriangleArea(double sideLength) {
+ if (sideLength < 0) {
+ throw new IllegalArgumentException("Triangle side length can not be negative");
+ }
+ return sideLength * sideLength * Math.sqrt(3) / 4;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task4.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task4.java
new file mode 100644
index 0000000..c474663
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task4.java
@@ -0,0 +1,71 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* На плоскости заданы своими координатами n точек. Написать метод(ы),
+ определяющие, между какими из пар точек самое больше расстояние.
+ Указание: коррдинаты точек занести в массив. */
+public class Task4 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "points count");
+ while (n < 2) {
+ System.out.println("Number of points can not be less than 2. Please try again.");
+ n = Parser.tryParseInt(scanner, "points count");
+ }
+ Point[] points = new Point[n];
+ for (int i = 0; i < n; i++) {
+ String pointName = "point[" + i + "]";
+ double x = Parser.tryParseDouble(scanner, pointName + " x");
+ double y = Parser.tryParseDouble(scanner, pointName + " y");
+ points[i] = new Point(x, y);
+ }
+ double maxDistance = findMaxDistanceBetweenPoints(points);
+ System.out.println("Maximum distance = " + maxDistance);
+ }
+ }
+
+ /**
+ * Finds maximum distance between given points.
+ * @param points Points array.
+ * @return maximum distance.
+ * @throws IllegalArgumentException when points array is null or array length is less than 2.
+ * @author DMGolub
+ */
+ public static double findMaxDistanceBetweenPoints(Point[] points) {
+ if (points == null) {
+ throw new IllegalArgumentException("array of points can not be null");
+ }
+ if (points.length < 2) {
+ throw new IllegalArgumentException("number of points can not be less than 2");
+ }
+ double maxDistance = Double.MIN_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ for (int j = 0; j < points.length; j++) {
+ double distance = distanceBetweenPoints(points[i], points[j]);
+ if (distance > maxDistance) {
+ maxDistance = distance;
+ }
+ }
+ }
+ return maxDistance;
+ }
+
+ /**
+ * Calculates distance between two given points with coordinates x, y.
+ * @param a double coordinate x,
+ * @param b double coordinate y.
+ * @return calculated distance.
+ * @throws IllegalArgumentException when point is null.
+ * @author DMGolub
+ */
+ public static double distanceBetweenPoints(Point a, Point b) {
+ if (a == null || b == null) {
+ throw new IllegalArgumentException("Point can not be null");
+ }
+ return Math.sqrt(Math.pow(b.getX() - a.getX(), 2.0) + Math.pow(b.getY() - a.getY(), 2.0));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task5.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task5.java
new file mode 100644
index 0000000..91e8200
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task5.java
@@ -0,0 +1,58 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Составить программу, которая в массиве A[N] находит второе по величине число
+ (вывести на печать число, которое меньше максимального элемента массива, но
+ больше всех других элементов). */
+public class Task5 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "number of elements in array");
+ while (n < 2) {
+ System.out.println("Number of elements can not be less than 2. Please try again.");
+ n = Parser.tryParseInt(scanner, "number of elements in array");
+ }
+ int[] numbers = new int[n];
+ for (int i = 0; i < n; i++) {
+ String variableName = "array[" + i + "]";
+ numbers[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ int secondMaximum = findSecondMaximum(numbers);
+ if (secondMaximum == Integer.MAX_VALUE) {
+ System.out.println("Could not find second maximum.");
+ } else {
+ System.out.println(secondMaximum);
+ }
+ }
+ }
+
+ /**
+ * Finds second maximum in the given array.
+ * @param numbers integer array.
+ * @return second maximum or Integer.MAX_VALUE if it can not be found.
+ * @throws IllegalArgumentException when array of numbers is null.
+ * @author DMGolub
+ */
+ public static int findSecondMaximum(int[] numbers) {
+ if (numbers == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int maximum = Integer.MIN_VALUE;
+ int secondMaximum = Integer.MIN_VALUE;
+ boolean isFound = false;
+ for (int number : numbers) {
+ if (number > maximum) {
+ secondMaximum = maximum;
+ maximum = number;
+ isFound = true;
+ } else if (number != maximum && number > secondMaximum) {
+ secondMaximum = number;
+ }
+ }
+ return isFound ? secondMaximum : Integer.MAX_VALUE;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task6.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task6.java
new file mode 100644
index 0000000..784d40c
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task6.java
@@ -0,0 +1,50 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Написать метод (методы), проверяющий, являются ли данные
+ три числа взаимно простыми. */
+public class Task6 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int a = Parser.tryParseInt(scanner, "number a");
+ int b = Parser.tryParseInt(scanner, "number b");
+ int c = Parser.tryParseInt(scanner, "number c");
+ System.out.println(areMutuallyPrimeNumbers(a, b, c) ? "YES" : "NO");
+ }
+ }
+
+ /**
+ * Determines if three given numbers are mutually prime.
+ * @param a integer number one,
+ * @param b integer number two,
+ * @param c integer number tree.
+ * @return true if the given numbers are mutually prime and false otherwise.
+ * @author DMGolub
+ */
+ public static boolean areMutuallyPrimeNumbers(int a, int b, int c) {
+ int gcd = greatestCommonDivisor(a, greatestCommonDivisor(b, c));
+ return gcd == 1;
+ }
+
+ /**
+ * Calculates the greatest common divisor of two given numbers.
+ * @param a int first number,
+ * @param b int second number.
+ * @return greatest common divisor.
+ * @author DMGolub
+ */
+ public static int greatestCommonDivisor(int a, int b) {
+ while (a != 0 && b != 0) {
+ if (Math.abs(a) > Math.abs(b)) {
+ a = a % b;
+ } else {
+ b = b % a;
+ }
+ }
+ return a + b;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task7.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task7.java
new file mode 100644
index 0000000..8ff1e0e
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task7.java
@@ -0,0 +1,52 @@
+package by.training.dmgolub.decomposing;
+
+/* Написать метод (методы) для вычисления суммы факториалов
+ все нечетных чисел от 1 до 9. */
+public class Task7 {
+
+ public static void main(String[] args) {
+ final int limit = 9;
+ long sum = sumOfFactorialsOfOddNumbers(limit);
+ System.out.println("Sum of factorials of odd numbers from 1 to 9 = " + sum);
+ }
+
+ /**
+ * Calculates the sum of factorials of odd numbers from 1 to the given number.
+ * @param number integer limit.
+ * @return sum of factorials.
+ * @throws IllegalArgumentException when number is less than 1.
+ * @author DMGolub
+ */
+ public static long sumOfFactorialsOfOddNumbers(int number) {
+ if (number < 1) {
+ throw new IllegalArgumentException("Number can not be less than 1");
+ }
+ long sum = 0;
+ for (int i = 1; i <= number; i += 2) {
+ sum += factorial(i);
+ }
+ return sum;
+ }
+
+ /**
+ * Calculates the factorial of the given number.
+ * @param number integer number.
+ * @return 1 if number is 0 or factorial of the given number otherwise.
+ * @throws IllegalArgumentException when number is negative.
+ * @author DMGolub
+ */
+ public static long factorial(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("Number can not be negative");
+ }
+ if (number == 0) {
+ return 1;
+ }
+ long result = 1;
+ for (long i = 1; i <= number; i++) {
+ result *= i;
+ System.out.println("i = " + i + ", result = " + result);
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task8.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task8.java
new file mode 100644
index 0000000..669e2f2
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task8.java
@@ -0,0 +1,58 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Задан массив D. Определить следующие суммы: D[1] + D[2] + D[3];
+ D[3] + D[4] + D[5]; D[4] + D[5]+ D[6].
+ Пояснение: составить метод (методы) для вычисления суммы трех
+ последовательно расположенных элементов массива с номерами от
+ k до m. */
+public class Task8 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int arraySize = Parser.tryParseInt(scanner, "array size");
+ while (arraySize < 6) {
+ System.out.println("Array size can not be less than 6. Please try again");
+ arraySize = Parser.tryParseInt(scanner, "array size");
+ }
+ int[] array = new int[arraySize];
+ for (int i = 0; i < arraySize; i++) {
+ String variableName = "D[" + (i + 1) + "]";
+ array[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ System.out.println("D[1] + D[2] + D[3] = " + sumOfThreeElements(array, 0));
+ System.out.println("D[3] + D[4] + D[5] = " + sumOfThreeElements(array, 2));
+ System.out.println("D[4] + D[5] + D[6] = " + sumOfThreeElements(array, 3));
+ }
+ }
+
+ /**
+ * Calculates sum of three consecutive elements of the given array. Indexes start from 0.
+ * @param array integer array.
+ * @param fromIndex first index of three consecutive elements.
+ * @return calculated sum.
+ * @throws IllegalArgumentException when array is null or first index is negative or
+ * array size is less than first index plus three.
+ * @author DMGolub
+ */
+ public static int sumOfThreeElements(int[] array, int fromIndex) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ if (fromIndex < 0) {
+ throw new IllegalArgumentException("First index can not be negative");
+ }
+ if (fromIndex + 2 >= array.length) {
+ throw new IllegalArgumentException("First index can not be " +
+ "greater or equal to array length - 2");
+ }
+ int sum = 0;
+ for (int i = fromIndex; i < fromIndex + 3; i++) {
+ sum += array[i];
+ }
+ return sum;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/decomposing/Task9.java b/module2/src/main/java/by/training/dmgolub/decomposing/Task9.java
new file mode 100644
index 0000000..cdedea8
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/decomposing/Task9.java
@@ -0,0 +1,111 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Даны числа X, Y, Z, T - длины сторон четырехугольника.
+ Написать метод (методы) вычисления его площади, если
+ угол между сторонами длиной X и Y - прямой. */
+public class Task9 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ double x = parseSideLength(scanner, "X");
+ double y = parseSideLength(scanner, "Y");
+ double z = parseSideLength(scanner, "Z");
+ double t = parseSideLength(scanner, "T");
+ System.out.println("Area = " + computeQuadrilateralArea(x, y, z, t));
+ }
+ }
+
+ /**
+ * Parses quadrilateral side length from console.
+ * @param scanner Scanner.
+ * @param name String quadrilateral size name.
+ * @return parsed length.
+ * @throws IllegalArgumentException when scanner or side name is null.
+ * @author DMGolub
+ */
+ public static double parseSideLength(Scanner scanner, String name) {
+ if (scanner == null) {
+ throw new IllegalArgumentException("Scanner can not be null");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name can not be null");
+ }
+ double size = Parser.tryParseDouble(scanner, name);
+ while (size <= 0) {
+ System.out.println("Side length can not be <= 0. Please try again.");
+ size = Parser.tryParseDouble(scanner, name);
+ }
+ return size;
+ }
+
+ /**
+ * Computes area of the given quadrilateral by its sides.
+ * The angle between sides X and Y is 90 degrees.
+ * @param x double first side length,
+ * @param y double second side length,
+ * @param z double third side length,
+ * @param t double fourth side length.
+ * @return calculated area.
+ * @throws IllegalArgumentException when any of given sides length is negative or zero.
+ * @author DMGolub
+ */
+ public static double computeQuadrilateralArea(double x, double y, double z, double t) {
+ if (x <= 0 || y <= 0 || z <= 0 || t <= 0) {
+ throw new IllegalArgumentException("Quadrilateral side length must be >= 0");
+ }
+ double hypotenuse = computeHypotenuse(x, y);
+ return computeRightTriangleArea(x, y) + computeTriangleArea(hypotenuse, z, t);
+ }
+
+ /**
+ * Computes area of the given right triangle by its sides.
+ * @param a double first triangle cathet length,
+ * @param b double second triangle cathet length.
+ * @return calculated sum.
+ * @throws IllegalArgumentException when any of cathets length is negative or zero.
+ * @author DMGolub
+ */
+ public static double computeRightTriangleArea(double a, double b) {
+ if (a <= 0 || b <= 0) {
+ throw new IllegalArgumentException("Triangle side length must be >= 0");
+ }
+ return a * b / 2.0;
+ }
+
+ /**
+ * Computes area of the given triangle by its sides.
+ * @param a double first triangle side length,
+ * @param b double second triangle side length,
+ * @param c double third triangle side length.
+ * @return calculated sum.
+ * @throws IllegalArgumentException when any of triangle sides length is negative or zero.
+ * @author DMGolub
+ */
+ public static double computeTriangleArea(double a, double b, double c) {
+ if (a <= 0 || b <= 0 || c <= 0) {
+ throw new IllegalArgumentException("Triangle side length must be >= 0");
+ }
+ double halfPerimeter = (a + b + c) / 2.0;
+ return Math.sqrt(halfPerimeter * (halfPerimeter - a) *
+ (halfPerimeter - b) * (halfPerimeter - c));
+ }
+
+ /**
+ * Computes length of the triangle hypotenuse by two cathets sizes.
+ * @param a double first triangle cathet length,
+ * @param b double second triangle cathet length.
+ * @return hypotenuse length.
+ * @throws IllegalArgumentException when any of cathets length is negative or zero.
+ * @author DMGolub
+ */
+ public static double computeHypotenuse(double a, double b) {
+ if (a <= 0 || b <= 0) {
+ throw new IllegalArgumentException("Triangle side length must be >= 0");
+ }
+ return Math.sqrt(a * a + b * b);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task1.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task1.java
new file mode 100644
index 0000000..4686e8d
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task1.java
@@ -0,0 +1,47 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* В массив A[N] занесены натуральные числа. Найти сумму тех элементов,
+ которые кратны данному K. */
+public class Task1 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "array A length (N)");
+ while (n < 1) {
+ System.out.println("Array length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "array A length (N)");
+ }
+ int[] a = new int[n];
+ for (int i = 0; i < n; ++i) {
+ String itemName = "A[" + i + "]";
+ a[i] = Parser.tryParseInt(scanner, itemName);
+ }
+ int k = Parser.tryParseInt(scanner, "k");
+ System.out.println("Sum of multiples of k in A[N] = " + sumOfMultiples(a, k));
+ }
+ }
+
+ /**
+ * Calculates the sum of array elements that are multiples of a given number;
+ * @param array integer array,
+ * @param k integer
+ * @return sum of array elements that are multiples of k.
+ * @author DMGolub
+ */
+ public static int sumOfMultiples(int[] array, int k) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int sum = 0;
+ for (int item : array) {
+ if (item % k == 0) {
+ sum += item;
+ }
+ }
+ return sum;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task10.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task10.java
new file mode 100644
index 0000000..39a2f2a
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task10.java
@@ -0,0 +1,57 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дан целочисленный массив с количеством элементов n. Сжать массив,
+ выбросив из него каждый второй элемент (освободившиеся элементы
+ заполнить нулями).
+ Примечание: дополнительный массив не использовать. */
+public class Task10 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "array length");
+ while (n < 1) {
+ System.out.println("Array length must be greater than 1. Please try again.");
+ n = Parser.tryParseInt(scanner, "array length");
+ }
+ int[] array = new int[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "array[" + i + "]";
+ array[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ compressArray(array);
+ System.out.print("Compressed array:");
+ for (int element : array) {
+ System.out.print(" " + element);
+ }
+ }
+ }
+
+ /**
+ * Compresses an array by deleting every second element, then moving
+ * elements left replacing them by zero.
+ * @param array integer sequence.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static void compressArray(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ if (array.length < 2) {
+ return;
+ }
+ int index = 1;
+ for (int i = 2; i < array.length; i += 2) {
+ array[index++] = array[i];
+ if (i > 2) {
+ array[i -1] = 0;
+ }
+ array[i] = 0;
+ }
+ array[array.length - 1] = 0;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task2.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task2.java
new file mode 100644
index 0000000..63d6f1a
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task2.java
@@ -0,0 +1,51 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дана последовательность действительных чисел a1, a2, ..., aN.
+ Заменить все ее члены, большие данного Z, эти числом.
+ Подсчитать количество замен. */
+public class Task2 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence A length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence A length (N)");
+ }
+ double[] sequence = new double[n];
+ for (int i = 0; i < n; ++i) {
+ String itemName = "A[" + i + "]";
+ sequence[i] = Parser.tryParseDouble(scanner, itemName);
+ }
+ double z = Parser.tryParseDouble(scanner, "Z");
+ System.out.println(replaceAllMembersLargerThanGiven(sequence, z)
+ + " members replaced.");
+ }
+ }
+
+ /**
+ * Replaces all sequence members larger than given number (Z) with Z and
+ * calculates the number of substitutions.
+ * @param sequence double number sequence,
+ * @param z double threshold.
+ * @return number of substitutions.
+ * @author DMGolub
+ */
+ public static int replaceAllMembersLargerThanGiven(double[] sequence, double z) {
+ if (sequence == null) {
+ throw new IllegalArgumentException("Sequence can not be null");
+ }
+ int count = 0;
+ for (int i = 0; i < sequence.length; ++i) {
+ if (sequence[i] > z) {
+ sequence[i] = z;
+ ++count;
+ }
+ }
+ return count;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task3.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task3.java
new file mode 100644
index 0000000..0796604
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task3.java
@@ -0,0 +1,53 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дан массив действительных чисел, размерность которого N.
+ Подсчитать, сколько в нем отрицательных, положительных
+ и нулевых элементов. */
+public class Task3 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "array length (N)");
+ while (n < 1) {
+ System.out.println("Array length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "array length (N)");
+ }
+ double[] array = new double[n];
+ for (int i = 0; i < n; ++i) {
+ String itemName = "array[" + i + "]";
+ array[i] = Parser.tryParseDouble(scanner, itemName);
+ }
+ countNegativeZeroPositiveArrayElements(array);
+ }
+ }
+
+ /**
+ * Counts and prints number of negative, zero and positive elements in a given array.
+ * @param array double array.
+ * @author DMGolub
+ */
+ public static void countNegativeZeroPositiveArrayElements(double[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int countNegative = 0;
+ int countZero = 0;
+ int countPositive = 0;
+ for (double element : array) {
+ if (element < 0) {
+ ++countNegative;
+ } else if (element > 0) {
+ ++countPositive;
+ } else {
+ ++countZero;
+ }
+ }
+ System.out.println("Number of negative elements = " + countNegative);
+ System.out.println("Number of zero elements = " + countZero);
+ System.out.println("Number of positive elements = " + countPositive);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task4.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task4.java
new file mode 100644
index 0000000..6a6df15
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task4.java
@@ -0,0 +1,58 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Даны действительные числа a1, a2, ..., aN. Поменять местами
+ наибольший и наименьший элементы. */
+public class Task4 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence A length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence A length (N)");
+ }
+ double[] array = new double[n];
+ for (int i = 0; i < n; ++i) {
+ String itemName = "A[" + i + "]";
+ array[i] = Parser.tryParseDouble(scanner, itemName);
+ }
+ swapMinAndMaxArrayElements(array);
+ }
+ }
+
+ /**
+ * Swaps minimal and maximal elements of the given array.
+ * @param array double array.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static void swapMinAndMaxArrayElements(double[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ if (array.length == 0) {
+ return;
+ }
+ double minElement = Double.MAX_VALUE;
+ double maxElement = Double.MIN_VALUE;
+ int minElementIndex = 0;
+ int maxElementIndex = 0;
+ for (int i = 0; i < array.length; ++i) {
+ if (array[i] < minElement) {
+ minElement = array[i];
+ minElementIndex = i;
+ }
+ if (array[i] > maxElement) {
+ maxElement = array[i];
+ maxElementIndex = i;
+ }
+ }
+ double temp = array[minElementIndex];
+ array[minElementIndex] = array[maxElementIndex];
+ array[maxElementIndex] = temp;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task5.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task5.java
new file mode 100644
index 0000000..24b7e84
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task5.java
@@ -0,0 +1,43 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Даны целые числа a1, a2, ..., aN. Вывести на печать те числа,
+ для которых ai > i. */
+public class Task5 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence A length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence length (N)");
+ }
+ int[] array = new int[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "a[" + i + "]";
+ array[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ printElementsGreaterThanIndex(array);
+ }
+
+ }
+
+ /**
+ * Prints elements of an array, that are greater than element index.
+ * @param array integer array.
+ * @author DMGolub
+ */
+ public static void printElementsGreaterThanIndex(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ for (int i = 0; i < array.length; ++i) {
+ if (array[i] > i) {
+ System.out.println(array[i]);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task6.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task6.java
new file mode 100644
index 0000000..3d17e14
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task6.java
@@ -0,0 +1,65 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Задана последовательность N вещественных чисел. Вычислить сумму
+ чисел, порядковые номера которых являются простыми числами. */
+public class Task6 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence length (N)");
+ }
+ double[] array = new double[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "array[" + i + "]";
+ array[i] = Parser.tryParseDouble(scanner, variableName);
+ }
+ System.out.println("Sum of elements with prime indexes = "
+ + sumOfElementsWithPrimeIndexes(array));
+ }
+ }
+
+ /**
+ * Calculates the sum of elements of an array with prime indexes.
+ * @param array double sequence.
+ * @return sum of elements.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub.
+ */
+ public static double sumOfElementsWithPrimeIndexes(double[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ double sum = 0.0;
+ for (int i = 0; i < array.length; ++i) {
+ if (isPrimeNumber(i)) {
+ sum += array[i];
+ }
+ }
+ return sum;
+ }
+
+ /**
+ * Determines if the given number is prime.
+ * @param number integer.
+ * @return true if the given number is prime and false otherwise.
+ * @author DMGolub
+ */
+ public static boolean isPrimeNumber(int number) {
+ if (number < 2) {
+ return false;
+ }
+ for (int i = 2; i <= number / 2; ++i) {
+ if (number % i == 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task7.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task7.java
new file mode 100644
index 0000000..2d585cd
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task7.java
@@ -0,0 +1,51 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Даны действительные числа a1, a2, ..., a2N.
+ Найти max(a1 + a2N, a2 + a2N-1, ..., aN + aN+1) */
+public class Task7 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence length (N)");
+ }
+ double[] array = new double[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "sequence[" + i + "]";
+ array[i] = Parser.tryParseDouble(scanner, variableName);
+ }
+ System.out.println("Max of (a[1] + a[2N], a[2] + a[2N-1], " +
+ "..., a[N] + a[N+1]) = " + findMaxOfPairs(array));
+ }
+ }
+
+ /**
+ * Finds maximum of pairs (a[1] + a[2N], a[2] + a[2N-1], a[N] + a[N+1]).
+ * @param array double sequence.
+ * @return maximum of pairs.
+ * @throws IllegalArgumentException when array is null of array length in not even.
+ * @author DMGolub
+ */
+ public static double findMaxOfPairs(double[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ if (array.length % 2 != 0) {
+ throw new IllegalArgumentException("Array length must be even");
+ }
+ double max = Double.MIN_VALUE;
+ for (int i = 0; i < array.length / 2; ++i) {
+ double sumOfPair = array[i] + array[array.length - i - 1];
+ if (sumOfPair > max) {
+ max = sumOfPair;
+ }
+ }
+ return max;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task8.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task8.java
new file mode 100644
index 0000000..8441bcd
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task8.java
@@ -0,0 +1,94 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* Дана последовательность целых чисел a1, a2, ..., aN. Образовать
+ новую последовательность, выбросив из исходной те члены, которые
+ равны min(a1, a2, ..., aN). */
+public class Task8 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence length (N)");
+ }
+ int[] array = new int[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "sequence[" + i + "]";
+ array[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ int[] arrayWithoutMinimums = excludeMinElements(array);
+ for (int element : arrayWithoutMinimums) {
+ System.out.println(element);
+ }
+ }
+ }
+
+ /**
+ * Excludes minimum elements from the given array.
+ * @param array integer sequence.
+ * @return array without miniumu elements.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static int[] excludeMinElements(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int min = findMin(array);
+ int minCount = countElements(array, min);
+ int[] result = new int[array.length - minCount];
+ int index = 0;
+ for (int element : array) {
+ if (element != min) {
+ result[index++] = element;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Counts the number of elements in the given array equal to the given element.
+ * @param array integer array.
+ * @param element integer number.
+ * @return counted number of elements.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static int countElements(int[] array, int element) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int count = 0;
+ for (int currElement : array) {
+ if (currElement == element) {
+ ++count;
+ }
+ }
+ return count;
+ }
+
+ /**
+ * Finds minimum element of a given array.
+ * @param array integer sequence.
+ * @return min element.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static int findMin(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int min = Integer.MAX_VALUE;
+ for (int element : array) {
+ if (element < min) {
+ min = element;
+ }
+ }
+ return min;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task9.java b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task9.java
new file mode 100644
index 0000000..233af4f
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/one_dimensional_array/Task9.java
@@ -0,0 +1,77 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import by.training.dmgolub.parser.Parser;
+
+import java.util.Scanner;
+
+/* В массиве целых чисел с количеством элементов n найти
+ наиболее часто встречающееся число. Если таких чисел
+ несколько, то определить наименьшее из них. */
+public class Task9 {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ int n = Parser.tryParseInt(scanner, "sequence length (N)");
+ while (n < 1) {
+ System.out.println("Sequence length must be greater than 0. Please try again.");
+ n = Parser.tryParseInt(scanner, "sequence length (N)");
+ }
+ int[] array = new int[n];
+ for (int i = 0; i < n; ++i) {
+ String variableName = "sequence[" + i + "]";
+ array[i] = Parser.tryParseInt(scanner, variableName);
+ }
+ System.out.println("Most common number = "
+ + findMostCommonNumber(array));
+ }
+ }
+
+ /**
+ * Finds most common number in the given sequence.
+ * @param array integer sequence.
+ * @return most common number.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static int findMostCommonNumber(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can no be null");
+ }
+ int[] counters = new int[array.length];
+ for (int i = 0; i < array.length; ++i) {
+ for (int j = 0; j < array.length; ++j) {
+ if (array[i] == array[j]) {
+ ++counters[i];
+ }
+ }
+ }
+ int max = findMax(counters);
+ int result = Integer.MAX_VALUE;
+ for (int i = 0; i < counters.length; ++i) {
+ if (counters[i] == max && array[i] < result) {
+ result = array[i];
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Finds maximum element of a given array.
+ * @param array integer sequence.
+ * @return min element.
+ * @throws IllegalArgumentException when array is null.
+ * @author DMGolub
+ */
+ public static int findMax(int[] array) {
+ if (array == null) {
+ throw new IllegalArgumentException("Array can not be null");
+ }
+ int max = Integer.MIN_VALUE;
+ for (int element : array) {
+ if (element > max) {
+ max = element;
+ }
+ }
+ return max;
+ }
+}
\ No newline at end of file
diff --git a/module2/src/main/java/by/training/dmgolub/parser/Parser.java b/module2/src/main/java/by/training/dmgolub/parser/Parser.java
new file mode 100644
index 0000000..d97a5b5
--- /dev/null
+++ b/module2/src/main/java/by/training/dmgolub/parser/Parser.java
@@ -0,0 +1,58 @@
+package by.training.dmgolub.parser;
+
+import java.util.Scanner;
+
+public class Parser {
+
+ /**
+ * Parses integer value from Scanner. If the specified input is not an integer value,
+ * asks user to retry input.
+ * @param scanner Scanner,
+ * @param variableName String variable name.
+ * @return integer value parsed from input.
+ */
+ public static int tryParseInt(Scanner scanner, String variableName) {
+ if (scanner == null) {
+ throw new IllegalArgumentException("Scanner can not be null!");
+ }
+ if (variableName == null) {
+ throw new IllegalArgumentException("Variable name can not be null!");
+ }
+ if (variableName.isEmpty()) {
+ throw new IllegalArgumentException("Variable name can not be empty!");
+ }
+ System.out.print("Enter " + variableName + ": ");
+ while (!scanner.hasNextInt()) {
+ String str = scanner.nextLine();
+ System.out.println("Wrong input: " + str + ". Please try again.");
+ System.out.print("Enter " + variableName + ": ");
+ }
+ return scanner.nextInt();
+ }
+
+ /**
+ * Parses double value from Scanner. If the specified input is not a double value,
+ * asks user to retry input.
+ * @param scanner Scanner,
+ * @param variableName String variable name.
+ * @return double value parsed from input.
+ */
+ public static double tryParseDouble(Scanner scanner, String variableName) {
+ if (scanner == null) {
+ throw new IllegalArgumentException("Scanner can not be null!");
+ }
+ if (variableName == null) {
+ throw new IllegalArgumentException("Variable name can not be null!");
+ }
+ if (variableName.isEmpty()) {
+ throw new IllegalArgumentException("Variable name can not be empty!");
+ }
+ System.out.print("Enter " + variableName + ": ");
+ while (!scanner.hasNextDouble()) {
+ String str = scanner.nextLine();
+ System.out.println("Wrong input: " + str + ". Please try again.");
+ System.out.print("Enter " + variableName + ": ");
+ }
+ return scanner.nextDouble();
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task10Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task10Test.java
new file mode 100644
index 0000000..9969fb6
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task10Test.java
@@ -0,0 +1,40 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task10Test {
+
+ @Test
+ public void print_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task10.printPositiveElementsOfMainDiagonal(null));
+ }
+
+ @Test
+ public void print_shouldThrowIllegalArgumentException_whenMatrixIsNotSquare() {
+ int[][] matrix = new int[2][3];
+ assertThrows(IllegalArgumentException.class,
+ () -> Task10.printPositiveElementsOfMainDiagonal(matrix));
+ }
+
+ @Test
+ public void print_shouldPrint2Elements_whenThereAreTwoPositiveElements() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1 9";
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, -5, 6},
+ {7, 8, 9}
+ };
+
+ Task10.printPositiveElementsOfMainDiagonal(matrix);
+
+ assertEquals(expected, out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task11Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task11Test.java
new file mode 100644
index 0000000..623c569
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task11Test.java
@@ -0,0 +1,61 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task11Test {
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task11.fillMatrix(null, 15));
+ }
+
+ @Test
+ public void fillMatrix_shouldFillMatrixWithNumbersFrom0To15_whenMatrixIsNotNull() {
+ Integer[][] matrix = new Integer[10][20];
+
+ Task11.fillMatrix(matrix, 16);
+ boolean numbersFrom0To15 = true;
+ for (int i = 0; i < 10; ++i) {
+ for (int j = 0; j < 20; ++j) {
+ if (matrix[i][j] < 0 || matrix[i][j] > 15) {
+ numbersFrom0To15 = false;
+ break;
+ }
+ }
+ }
+
+ assertTrue(numbersFrom0To15);
+ }
+
+ @Test
+ public void findAndPrintRows_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task11.findAndPrintRows(null, 1, 1));
+ }
+
+ @Test
+ public void findAndPrintRows_shouldPrint2Rows_whenThereAre2SuchRows() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Integer[][] matrix = {
+ {6, 5, 12, 10, 5, 10, 1, 5, 7, 14, 7, 10, 7, 3, 14, 2, 0, 8, 0, 7},
+ {13, 12, 11, 13, 11, 8, 10, 11, 10, 14, 0, 2, 9, 3, 2, 1, 5, 10, 6, 14},
+ {5, 7, 3, 5, 13, 4, 13, 6, 3, 13, 0, 4, 2, 7, 11, 9, 6, 10, 5, 4},
+ {14, 7, 8, 6, 12, 4, 4, 3, 10, 10, 3, 14, 13, 14, 6, 13, 9, 13, 2, 5}
+ };
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("Row 0: 6 5 12 10 5 10 1 5 7 14 7 10 7 3 14 2 0 8 0 7")
+ .add("Row 2: 5 7 3 5 13 4 13 6 3 13 0 4 2 7 11 9 6 10 5 4");
+
+ Task11.findAndPrintRows(matrix, 5, 3);
+
+ assertEquals(expected.toString() + System.lineSeparator(), out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task12Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task12Test.java
new file mode 100644
index 0000000..d2f288a
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task12Test.java
@@ -0,0 +1,50 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task12Test {
+
+ @Test
+ public void sort_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task12.sortMatrixRows(null, true));
+ }
+
+ @Test
+ public void sort_shouldSortMatrixInNaturalOrder_whenFlagIsTrue() {
+ Integer[][] matrix = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+ Integer[][] expected = {
+ {7, 8, 9},
+ {4, 5, 6},
+ {1, 2, 3}
+ };
+
+ Task12.sortMatrixRows(matrix, true);
+
+ assertArrayEquals(expected, matrix);
+ }
+
+ @Test
+ public void sort_shouldSortMatrixInReversedOrder_whenFlagIsFalse() {
+ Integer[][] matrix = {
+ {7, 8, 9},
+ {4, 5, 6},
+ {1, 2, 3}
+ };
+ Integer[][] expected = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+
+ Task12.sortMatrixRows(matrix, false);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task13Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task13Test.java
new file mode 100644
index 0000000..02562b5
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task13Test.java
@@ -0,0 +1,50 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task13Test {
+
+ @Test
+ public void sort_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task13.sortMatrixColumns(null, true));
+ }
+
+ @Test
+ public void sort_shouldSortMatrixColumnsInNaturalOrder_whenFlagIsTrue() {
+ Integer[][] matrix = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+ Integer[][] expected = {
+ {3, 2, 1},
+ {6, 5, 4},
+ {9, 8, 7}
+ };
+
+ Task13.sortMatrixColumns(matrix, true);
+
+ assertArrayEquals(expected, matrix);
+ }
+
+ @Test
+ public void sort_shouldSortMatrixColumnsInReversedOrder_whenFlagIsFalse() {
+ Integer[][] matrix = {
+ {3, 2, 1},
+ {6, 5, 4},
+ {9, 8, 7}
+ };
+ Integer[][] expected = {
+ {9, 8, 7},
+ {6, 5, 4},
+ {3, 2, 1}
+ };
+
+ Task13.sortMatrixColumns(matrix, false);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task14Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task14Test.java
new file mode 100644
index 0000000..09ea4eb
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task14Test.java
@@ -0,0 +1,65 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task14Test {
+
+ @Test
+ public void createMatrix_shouldThrowIllegalArgumentException_whenRowsLessThanColumns() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task14.createRandomMatrix(2, 4));
+ }
+
+ @Test
+ public void createMatrix_shouldCreateMatrix_whenRows1Columns1() {
+ int[][] expected = {
+ {1}
+ };
+
+ assertArrayEquals(expected, Task14.createRandomMatrix(1, 1));
+ }
+
+ @Test
+ public void createMatrix_shouldCreateRandomMatrix_whenRows3Columns3() {
+ int rows = 3;
+ int columns = 3;
+ int[] expectedCounts = {
+ 1, 2, 3
+ };
+
+ int[][] result = Task14.createRandomMatrix(rows, columns);
+ int[] oneCountForColumn = new int[columns];
+ for (int row = 0; row < rows; ++row) {
+ for (int column = 0; column < columns; ++column) {
+ if (result[row][column] == 1) {
+ ++oneCountForColumn[column];
+ }
+ }
+ }
+
+ assertArrayEquals(expectedCounts, oneCountForColumn);
+ }
+
+ @Test
+ public void createMatrix_shouldCreateRandomMatrix_whenRows6Columns4() {
+ int rows = 6;
+ int columns = 4;
+ int[] expectedCounts = {
+ 1, 2, 3, 4
+ };
+
+ int[][] result = Task14.createRandomMatrix(rows, columns);
+ int[] oneCountForColumn = new int[columns];
+ for (int row = 0; row < rows; ++row) {
+ for (int column = 0; column < columns; ++column) {
+ if (result[row][column] == 1) {
+ ++oneCountForColumn[column];
+ }
+ }
+ }
+
+ assertArrayEquals(expectedCounts, oneCountForColumn);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task15Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task15Test.java
new file mode 100644
index 0000000..8f446ea
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task15Test.java
@@ -0,0 +1,49 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task15Test {
+
+ @Test
+ public void findMax_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task15.findMaxElement(null));
+ }
+
+ @Test
+ public void findMax_shouldReturnMaximumElement_whenMatrixContainsElements() {
+ Integer[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ assertEquals(9, Task15.findMaxElement(matrix));
+ }
+
+ @Test
+ public void replace_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task15.replaceOddNumbers(null, 1));
+ }
+
+ @Test
+ public void replace_shouldReplaceOddElements_whenThereAreSuchElementsInTheMatrix() {
+ Integer[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+ Integer[][] expected = {
+ {9, 2, 9},
+ {4, 9, 6},
+ {9, 8, 9}
+ };
+
+ Task15.replaceOddNumbers(matrix, 9);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task16Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task16Test.java
new file mode 100644
index 0000000..92e16ed
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task16Test.java
@@ -0,0 +1,77 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task16Test {
+
+ @Test
+ public void fillSquare_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task16.fillMagicSquare(null));
+ }
+
+ @Test
+ public void fillSquare_shouldThrowIllegalArgumentException_whenMatrixSizeIs2() {
+ Integer[][] square = new Integer[2][2];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task16.fillMagicSquare(square));
+ }
+
+ @Test
+ public void fillSquare_shouldFillMagicSquare_whenMatrixSizeIs1() {
+ Integer[][] square = new Integer[1][1];
+ Integer[][] expected = {
+ {1}
+ };
+
+ Task16.fillMagicSquare(square);
+
+ assertArrayEquals(expected, square);
+ }
+
+ @Test
+ public void fillSquare_shouldFillMagicSquare_whenMatrixSizeIs3() {
+ Integer[][] square = new Integer[3][3];
+ Integer[][] expected = {
+ {6, 1, 8},
+ {7, 5 ,3},
+ {2, 9, 4}
+ };
+
+ Task16.fillMagicSquare(square);
+
+ assertArrayEquals(expected, square);
+ }
+
+ @Test
+ public void fillSquare_shouldFillMagicSquare_whenMatrixSizeIs5() {
+ final int squareSize = 5;
+ Integer[][] square = new Integer[squareSize][squareSize];
+
+ Task16.fillMagicSquare(square);
+
+ boolean isMagicSquare = true;
+ int mainDiagonalSum = 0;
+ int sideDiagonalSum = 0;
+ for (int i = 0; i < squareSize; ++i) {
+ mainDiagonalSum += square[i][i];
+ sideDiagonalSum += square[i][squareSize - i - 1];
+ }
+ isMagicSquare = mainDiagonalSum == sideDiagonalSum;
+ int[] rowSums = new int[squareSize];
+ int[] columnSums = new int[squareSize];
+ for (int j = 0; j < squareSize; ++j) {
+ for (int k = 0; k < squareSize; ++k) {
+ // sum
+ }
+ }
+ for (int m = 0; m < squareSize; ++m) {
+ isMagicSquare = isMagicSquare && rowSums[m] == mainDiagonalSum;
+ isMagicSquare = isMagicSquare && columnSums[m] == mainDiagonalSum;
+ }
+ assertTrue(isMagicSquare);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task1Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task1Test.java
new file mode 100644
index 0000000..2aa4703
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task1Test.java
@@ -0,0 +1,38 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task1Test {
+
+ @Test
+ public void printOdd_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task1.printOddColumnsWhereFirstElementIsGreaterThenLast(null));
+ }
+
+ @Test
+ public void printOdd_shouldPrintTwoColumns_whenThereAreTwoSuchColumns() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("1 5").add("1 5").add("2 6").add("2 6").add("0 4");
+ int[][] matrix = {
+ {1, 2, 3, 4, 5},
+ {1, 2, 3, 4, 5},
+ {2, 3, 4, 5, 6},
+ {2, 3, 4, 5, 6},
+ {0, 1, 5, 3, 4}
+ };
+
+ Task1.printOddColumnsWhereFirstElementIsGreaterThenLast(matrix);
+
+ assertEquals(expected.toString() + System.lineSeparator(),
+ out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task2Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task2Test.java
new file mode 100644
index 0000000..1a348ce
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task2Test.java
@@ -0,0 +1,60 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task2Test {
+
+ @Test
+ public void printDiagonal_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task2.printDiagonal(null));
+ }
+
+ @Test
+ public void printDiagonal_shouldPrintOneElement_whenMatrixIs1By1() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1";
+ int[][] matrix = {{1}};
+
+ Task2.printDiagonal(matrix);
+
+ assertEquals(expected, out.toString());
+ }
+
+ @Test
+ public void printDiagonal_shouldPrintTwoElements_whenMatrixIs2By2() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1 4";
+ int[][] matrix = {
+ {1, 2},
+ {3, 4}
+ };
+
+ Task2.printDiagonal(matrix);
+
+ assertEquals(expected, out.toString());
+ }
+
+ @Test
+ public void printDiagonal_shouldPrintThreeElements_whenMatrixIs3By3() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1 5 9";
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ Task2.printDiagonal(matrix);
+
+ assertEquals(expected, out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task3Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task3Test.java
new file mode 100644
index 0000000..96f4f2c
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task3Test.java
@@ -0,0 +1,87 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task3Test {
+
+ @Test
+ public void printRow_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printRow(null, 1));
+ }
+
+ @Test
+ public void printRow_shouldThrowIllegalArgumentException_whenRowIsLessThan0() {
+ int[][] matrix = new int[1][1];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printRow(matrix, -1));
+ }
+
+ @Test
+ public void printRow_shouldThrowIllegalArgumentException_whenRowIndexIsOutOfBounds() {
+ int[][] matrix = new int[1][1];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printRow(matrix, 1));
+ }
+
+ @Test
+ public void printRow_shouldPrintRow_whenThereIsSuchRowInTheMatrix() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "4 5 6";
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ Task3.printRow(matrix, 1);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+
+ @Test
+ public void printColumn_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printColumn(null, 1));
+ }
+
+ @Test
+ public void printColumn_shouldThrowIllegalArgumentException_whenRowIsLessThan0() {
+ int[][] matrix = new int[1][1];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printColumn(matrix, -1));
+ }
+
+ @Test
+ public void printColumn_shouldThrowIllegalArgumentException_whenRowIndexIsOutOfBounds() {
+ int[][] matrix = new int[1][1];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.printColumn(matrix, 1));
+ }
+
+ @Test
+ public void printColumn_shouldPrintRow_whenThereIsSuchColumnInTheMatrix() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "2 5 8";
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ Task3.printColumn(matrix, 1);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task4Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task4Test.java
new file mode 100644
index 0000000..31c89cf
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task4Test.java
@@ -0,0 +1,63 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task4Test {
+
+ @Test
+ public void printMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.printMatrix(null));
+ }
+
+ @Test
+ public void printMatrix_shouldPrintMatrix_whenMatrixSizeIsGreaterThan0() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1 2\n3 4";
+ Integer[][] matrix = {
+ {1, 2},
+ {3, 4}
+ };
+
+ Task4.printMatrix(matrix);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.fillMatrix(null));
+ }
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixSizeIsOdd() {
+ Integer[][] matrix = new Integer[3][3];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.fillMatrix(matrix));
+ }
+
+ @Test
+ public void fillMatrix_shouldFillTheMatrix_whenMatrixSizeIsEven() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Integer[][] expected = {
+ {1, 2, 3, 4},
+ {4, 3, 2, 1},
+ {1, 2, 3, 4},
+ {4, 3, 2, 1},
+ };
+ Integer[][] matrix = new Integer[4][4];
+
+ Task4.fillMatrix(matrix);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task5Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task5Test.java
new file mode 100644
index 0000000..acd5449
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task5Test.java
@@ -0,0 +1,42 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task5Test {
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task5.fillMatrix(null));
+ }
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixSizeIsOdd() {
+ Integer[][] matrix = new Integer[3][3];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task5.fillMatrix(matrix));
+ }
+
+ @Test
+ public void fillMatrix_shouldFillTheMatrix_whenMatrixSizeIsEven() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Integer[][] expected = {
+ {1, 1, 1, 1},
+ {2, 2, 2, 0},
+ {3, 3, 0, 0},
+ {4, 0, 0, 0}
+ };
+ Integer[][] matrix = new Integer[4][4];
+
+ Task5.fillMatrix(matrix);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task6Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task6Test.java
new file mode 100644
index 0000000..07bcc95
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task6Test.java
@@ -0,0 +1,44 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task6Test {
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task6.fillMatrix(null));
+ }
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixSizeIsOdd() {
+ Integer[][] matrix = new Integer[3][3];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task6.fillMatrix(matrix));
+ }
+
+ @Test
+ public void fillMatrix_shouldFillTheMatrix_whenMatrixSizeIsEven() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ int[][] expected = {
+ {1, 1, 1, 1, 1, 1},
+ {0, 1, 1, 1, 1, 0},
+ {0, 0, 1, 1, 0, 0},
+ {0, 0, 1, 1, 0, 0},
+ {0, 1, 1, 1, 1, 0},
+ {1, 1, 1, 1, 1, 1}
+ };
+ Integer[][] matrix = new Integer[6][6];
+
+ Task6.fillMatrix(matrix);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task7Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task7Test.java
new file mode 100644
index 0000000..fdc3d6e
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task7Test.java
@@ -0,0 +1,50 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task7Test {
+
+ @Test
+ public void fillMatrix_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task7.fillMatrixAndCountPositive(null));
+ }
+
+ @Test
+ public void fillMatrix_shouldFillTheMatrix_whenMatrixSizeIs2() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Double[][] expected = {
+ {Math.sin(0), Math.sin(-1 / 2.0)},
+ {Math.sin(1 / 2.0), Math.sin(0.0)}
+ };
+ Double[][] matrix = new Double[2][2];
+
+ int positiveCount = Task7.fillMatrixAndCountPositive(matrix);
+
+ assertArrayEquals(expected, matrix);
+ assertEquals(1, positiveCount);
+ }
+
+ @Test
+ public void fillMatrix_shouldFillTheMatrix_whenMatrixSizeIs3() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Double[][] expected = {
+ {Math.sin(0), Math.sin(-1 / 3.0), Math.sin(-4 / 3.0)},
+ {Math.sin(1 / 3.0), Math.sin(0.0), Math.sin(-3 / 3.0)},
+ {Math.sin(4 / 3.0), Math.sin(3 / 3.0), Math.sin(0.0)}
+ };
+ Double[][] matrix = new Double[3][3];
+
+ int positiveCount = Task7.fillMatrixAndCountPositive(matrix);
+
+ assertArrayEquals(expected, matrix);
+ assertEquals(3, positiveCount);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task8Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task8Test.java
new file mode 100644
index 0000000..a65d587
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task8Test.java
@@ -0,0 +1,37 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task8Test {
+
+ @Test
+ public void swapColumns_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.swapColumns(null, 1, 2));
+ }
+
+ @Test
+ public void swapColumns_shouldSwapColumns_whenMatrixHasThreeColumns() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ Integer[][] expected = {
+ {1, 3, 2},
+ {4, 6, 5},
+ {7, 9, 8}
+ };
+ Integer[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ Task8.swapColumns(matrix, 1, 2);
+
+ assertArrayEquals(expected, matrix);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task9Test.java b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task9Test.java
new file mode 100644
index 0000000..919ccb2
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/array_of_arrays/Task9Test.java
@@ -0,0 +1,26 @@
+package by.training.dmgolub.array_of_arrays;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task9Test {
+
+ @Test
+ public void findColumn_shouldThrowIllegalArgumentException_whenMatrixIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.findColumnWithMaxSumOfElements(null));
+ }
+
+ @Test
+ public void findColumn_shouldReturn2_whenMaxSumColumIndexIs2() {
+ int[][] matrix = {
+ {1, 2, 3},
+ {4, 5, 6},
+ {7, 8, 9}
+ };
+
+ assertEquals(2,
+ Task9.findColumnWithMaxSumOfElements(matrix));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task10Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task10Test.java
new file mode 100644
index 0000000..179c2bc
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task10Test.java
@@ -0,0 +1,42 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task10Test {
+
+ @Test
+ public void splitNumber_shouldThrowIllegalArgumentException_whenNumberIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task10.splitNumber(-1));
+ }
+
+ @Test
+ public void splitNumber_shouldSplitNumberAndReturnAnArray_whenNumberIsGreaterThan0() {
+ int[] expected = {1, 2, 3};
+
+ assertArrayEquals(expected, Task10.splitNumber(123));
+ }
+
+ @Test
+ public void printArray_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task10.printArray(null));
+ }
+
+ @Test
+ public void printArray_shouldPrintTheGivenArray_whenArraySizeIsGreaterThan0() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "1, 2, 3";
+ int[] array = {1, 2, 3};
+
+ Task10.printArray(array);
+
+ assertEquals(expected, out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task11Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task11Test.java
new file mode 100644
index 0000000..5fa94b7
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task11Test.java
@@ -0,0 +1,33 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task11Test {
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIs5() {
+ assertEquals(1, Task11.countDigits(5));
+ }
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIsMinus5() {
+ assertEquals(1, Task11.countDigits(-5));
+ }
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIsMinus5Point0() {
+ assertEquals(1, Task11.countDigits(-5.0));
+ }
+
+ @Test
+ public void countDigits_shouldReturn2_whenNumberIs5Point2() {
+ assertEquals(2, Task11.countDigits(5.2));
+ }
+
+ @Test
+ public void countDigits_shouldReturn2_whenNumberIsMinus5Point3() {
+ assertEquals(2, Task11.countDigits(-5.3));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task13Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task13Test.java
new file mode 100644
index 0000000..ff8e4ab
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task13Test.java
@@ -0,0 +1,66 @@
+package by.training.dmgolub.decomposing;
+
+import by.training.dmgolub.one_dimensional_array.Task6;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task13Test {
+
+ @Test
+ public void isPrimeNumber_shouldReturnFalse_whenNumberIsNegative() {
+ assertFalse(by.training.dmgolub.one_dimensional_array.Task6.isPrimeNumber(-1));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnTrue_whenNumberIs2() {
+ assertTrue(by.training.dmgolub.one_dimensional_array.Task6.isPrimeNumber(2));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnFalse_whenNumberIs4() {
+ assertFalse(by.training.dmgolub.one_dimensional_array.Task6.isPrimeNumber(4));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnTrue_whenNumberIs5() {
+ assertTrue(Task6.isPrimeNumber(5));
+ }
+
+ @Test
+ public void printPrimeTwins_shouldThrowIllegalArgumentException_whenFromIndexIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task13.printPrimeTwins(-1, 5));
+ }
+
+ @Test
+ public void printPrimeTwins_shouldThrowIllegalArgumentException_whenToIndexIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task13.printPrimeTwins(2, -4));
+ }
+
+ @Test
+ public void printPrimeTwins_shouldPrint3And5_whenN3() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "3, 5";
+
+ Task13.printPrimeTwins(3, 6);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+
+ @Test
+ public void printPrimeTwins_shouldPrint5And7_whenN5() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ String expected = "5, 7";
+
+ Task13.printPrimeTwins(5, 10);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task14Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task14Test.java
new file mode 100644
index 0000000..73cabd8
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task14Test.java
@@ -0,0 +1,77 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task14Test {
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIs5() {
+ assertEquals(1, Task11.countDigits(5));
+ }
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIsMinus5() {
+ assertEquals(1, Task11.countDigits(-5));
+ }
+
+ @Test
+ public void countDigits_shouldReturn1_whenNumberIsMinus5Point0() {
+ assertEquals(1, Task11.countDigits(-5.0));
+ }
+
+ @Test
+ public void countDigits_shouldReturn2_whenNumberIs5Point2() {
+ assertEquals(2, Task11.countDigits(5.2));
+ }
+
+ @Test
+ public void countDigits_shouldReturn2_whenNumberIsMinus5Point3() {
+ assertEquals(2, Task11.countDigits(-5.3));
+ }
+
+ @Test
+ public void isArmstrongNumber_shouldReturnTrue_whenNumberIs153() {
+ assertTrue(Task14.isArmstrongNumber(153));
+ }
+
+ @Test
+ public void isArmstrongNumber_shouldReturnTrue_whenNumberIs370() {
+ assertTrue(Task14.isArmstrongNumber(370));
+ }
+
+ @Test
+ public void isArmstrongNumber_shouldReturnTrue_whenNumberIs371() {
+ assertTrue(Task14.isArmstrongNumber(371));
+ }
+
+ @Test
+ public void isArmstrongNumber_shouldReturnFalse_whenNumberIs372() {
+ assertFalse(Task14.isArmstrongNumber(372));
+ }
+
+ @Test
+ public void printArmstrongNumbers_shouldPrintFrom1To9_whenNumberIs20() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("1")
+ .add("2")
+ .add("3")
+ .add("4")
+ .add("5")
+ .add("6")
+ .add("7")
+ .add("8")
+ .add("9");
+
+ Task14.printArmstrongNumbers(1, 20);
+
+ assertEquals(expected.toString() + System.lineSeparator(), out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task17Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task17Test.java
new file mode 100644
index 0000000..2ca6bdc
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task17Test.java
@@ -0,0 +1,44 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task17Test {
+
+ @Test
+ public void countIterations_shouldThrowIllegalArgumentException_whenNumberIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task17.countIterations(-1));
+ }
+
+ @Test
+ public void countIterations_shouldReturn1_whenNumberIs9() {
+ assertEquals(1, Task17.countIterations(9));
+ }
+
+ @Test
+ public void countIterations_shouldReturn2_whenNumberIs11() {
+ assertEquals(2, Task17.countIterations(11));
+ }
+
+ @Test
+ public void countIterations_shouldReturn12_whenNumberis111() {
+ assertEquals(12, Task17.countIterations(111));
+ }
+
+ @Test
+ public void sumOfDigits_shouldReturn3_whenNumberIs111() {
+ assertEquals(3, Task17.sumOfDigits(111));
+ }
+
+ @Test
+ public void sumOfDigits_shouldReturn6_whenNumberIs123() {
+ assertEquals(6, Task17.sumOfDigits(123));
+ }
+
+ @Test
+ public void sumOfDigits_shouldReturn6_whenNumberIsMinus123() {
+ assertEquals(6, Task17.sumOfDigits(-123));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task1Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task1Test.java
new file mode 100644
index 0000000..26ce516
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task1Test.java
@@ -0,0 +1,58 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task1Test {
+
+ @Test
+ public void greatestCommonDivisor_shouldReturn3_whenA3B15() {
+ assertEquals(3, Task1.greatestCommonDivisor(3, 15));
+ }
+
+ @Test
+ public void greatestCommonDivisor_shouldReturn3_whenA3BMinus15() {
+ assertEquals(3, Task1.greatestCommonDivisor(3, -15));
+ }
+
+ @Test
+ public void greatestCommonDivisor_shouldReturn5_whenA0B5() {
+ assertEquals(5, Task1.greatestCommonDivisor(0, 5));
+ }
+
+ @Test
+ public void greatestCommonDivisor_shouldReturn5_whenA5B0() {
+ assertEquals(5, Task1.greatestCommonDivisor(5, 0));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn30_whenA3B10() {
+ assertEquals(30, Task1.smallestCommonMultiple(3, 10));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn80_whenA16B20() {
+ assertEquals(80, Task1.smallestCommonMultiple(16, 20));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn80_whenAMinus16B20() {
+ assertEquals(80, Task1.smallestCommonMultiple(-16, 20));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn0_whenA0B5() {
+ assertEquals(0, Task1.smallestCommonMultiple(0, 5));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn0_whenA5B0() {
+ assertEquals(0, Task1.smallestCommonMultiple(5, 0));
+ }
+
+ @Test
+ public void smallestCommonMultiple_shouldReturn0_whenA0B0() {
+ assertEquals(0, Task1.smallestCommonMultiple(0, 0));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task2Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task2Test.java
new file mode 100644
index 0000000..bcf42f4
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task2Test.java
@@ -0,0 +1,18 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task2Test {
+
+ @Test
+ public void greatestCommonDivisor_shouldReturn3_whenA15B21C81D9() {
+ int a = 15;
+ int b = 21;
+ int c = 18;
+ int d = 9;
+
+ assertEquals(3, Task2.greatestCommonDivisor(a, b, c, d));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task3Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task3Test.java
new file mode 100644
index 0000000..e90d95e
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task3Test.java
@@ -0,0 +1,44 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task3Test {
+
+ @Test
+ public void calculateTriangle_shouldThrowIllegalArgumentException_whenSideIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.calculateRegularTriangleArea(-1));
+ }
+
+ @Test
+ public void calculateTriangleArea_shouldReturn0_whenSideLengthIs0() {
+ assertEquals(0, Task3.calculateRegularTriangleArea(0));
+ }
+
+ @Test
+ public void calculateTriangleArea_shouldCalculateArea_whenSideLengthIsPositive() {
+ double expected = Math.sqrt(3);
+
+ assertEquals(expected, Task3.calculateRegularTriangleArea(2));
+ }
+
+ @Test
+ public void calculateHexagonArea_shouldThrowIllegalArgumentException_whenSideIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.calculateRegularHexagonArea(-1));
+ }
+
+ @Test
+ public void calculateHexagonArea_shouldReturn0_whenSideLengthIs0() {
+ assertEquals(0, Task3.calculateRegularHexagonArea(0));
+ }
+
+ @Test
+ public void calculateHexagonArea_shouldCalculateArea_whenSideLengthIsPositive() {
+ double expected = 6 * Math.sqrt(3);
+
+ assertEquals(expected, Task3.calculateRegularHexagonArea(2));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task4Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task4Test.java
new file mode 100644
index 0000000..34c6817
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task4Test.java
@@ -0,0 +1,62 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task4Test {
+
+ @Test
+ public void findMax_shouldThrowIllegalArgumentException_whenPointsIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.findMaxDistanceBetweenPoints(null));
+ }
+
+ @Test
+ public void findMax_shouldReturn5_whenAX0Y0PointBX2Y0PointCXMinus2Y3PointDX2Y3() {
+ Point[] points = {
+ new Point(0, 0),
+ new Point(2, 0),
+ new Point(-2, 3),
+ new Point(2, 3)
+ };
+
+ assertEquals(5.0, Task4.findMaxDistanceBetweenPoints(points));
+ }
+
+ @Test
+ public void distance_shouldThrowIllegalArgumentException_whenPointAIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.distanceBetweenPoints(null, new Point(1.0, 2.0)));
+ }
+
+ @Test
+ public void distance_shouldThrowIllegalArgumentException_whenPointBIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.distanceBetweenPoints(new Point(1.0, 2.0), null));
+ }
+
+ @Test
+ public void distance_shouldReturn2_whenPointAX0Y0PointBX2Y0() {
+ Point a = new Point(0, 0);
+ Point b = new Point(2, 0);
+
+ assertEquals(2.0, Task4.distanceBetweenPoints(a, b));
+ }
+
+ @Test
+ public void distance_shouldReturn4_whenPointAXMinus2Y3PointBX2Y3() {
+ Point a = new Point(-2, 3);
+ Point b = new Point(2, 3);
+
+ assertEquals(4.0, Task4.distanceBetweenPoints(a, b));
+ }
+
+ @Test
+ public void distance_shouldReturn5_whenPointAXMinus2Y3PointBX2Y0() {
+ Point a = new Point(-2, 3);
+ Point b = new Point(2, 0);
+
+ assertEquals(5.0, Task4.distanceBetweenPoints(a, b));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task5Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task5Test.java
new file mode 100644
index 0000000..a8411e0
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task5Test.java
@@ -0,0 +1,35 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task5Test {
+
+ @Test
+ public void findSecondMaximum_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task5.findSecondMaximum(null));
+ }
+
+ @Test
+ public void findSecondMaximum_shouldReturnSecondMaximum_whenArrayIsAscending() {
+ int[] numbers = {1, 2, 3, 4, 5};
+
+ assertEquals(4, Task5.findSecondMaximum(numbers));
+ }
+
+ @Test
+ public void findSecondMaximum_shouldReturnSecondMaximum_whenArrayIsDescending() {
+ int[] numbers = {5, 4, 3, 2, 1};
+
+ assertEquals(4, Task5.findSecondMaximum(numbers));
+ }
+
+ @Test
+ public void findSecondMaximum_shouldReturnSecondMaximum_whenThereAreTwoMaximumElements() {
+ int[] numbers = {5, 1, 2, 3, 4, 5};
+
+ assertEquals(4, Task5.findSecondMaximum(numbers));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task6Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task6Test.java
new file mode 100644
index 0000000..d760e6a
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task6Test.java
@@ -0,0 +1,33 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task6Test {
+
+ @Test
+ public void primeNumbers_shouldReturnTrue_whenA6B8C9() {
+ assertTrue(Task6.areMutuallyPrimeNumbers(6, 8, 9));
+ }
+
+ @Test
+ public void primeNumbers_shouldReturnTrue_whenA8B15C45() {
+ assertTrue(Task6.areMutuallyPrimeNumbers(8, 15, 49));
+ }
+
+ @Test
+ public void primeNumbers_shouldReturnTrue_whenA331B463C733() {
+ assertTrue(Task6.areMutuallyPrimeNumbers(331, 463, 733));
+ }
+
+ @Test
+ public void primeNumbers_shouldReturnFalse_whenA2B4C8() {
+ assertFalse(Task6.areMutuallyPrimeNumbers(2, 4, 8));
+ }
+
+ @Test
+ public void primeNumbers_shouldReturnFalse_whenA3B6C12() {
+ assertFalse(Task6.areMutuallyPrimeNumbers(3, 6, 12));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task7Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task7Test.java
new file mode 100644
index 0000000..2f5a0db
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task7Test.java
@@ -0,0 +1,39 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task7Test {
+
+ @Test
+ public void factorial_shouldThrowIllegalArgumentException_whenNumberIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task7.factorial(-1));
+ }
+
+ @Test
+ public void factorial_shouldReturn1_whenNumberIs0() {
+ assertEquals(1, Task7.factorial(0));
+ }
+
+ @Test
+ public void factorial_shouldReturn1_whenNumberIs1() {
+ assertEquals(1, Task7.factorial(1));
+ }
+
+ @Test
+ public void factorial_shouldReturn6_whenNumberIs3() {
+ assertEquals(6, Task7.factorial(3));
+ }
+
+ @Test
+ public void factorial_shouldReturn120_whenNumberIs5() {
+ assertEquals(120, Task7.factorial(5));
+ }
+
+ @Test
+ public void sumOfFactorialsOfOddNumbers_shouldReturn368047_whenNumberIs9() {
+ assertEquals(368047, Task7.sumOfFactorialsOfOddNumbers(9));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task8Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task8Test.java
new file mode 100644
index 0000000..6df628c
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task8Test.java
@@ -0,0 +1,39 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task8Test {
+
+ @Test
+ public void sumOfThreeElements_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.sumOfThreeElements(null, 1));
+ }
+
+ @Test
+ public void sumOfThreeElements_shouldThrowIllegalArgumentException_whenIndexIsNegative() {
+ int[] array = {1, 2, 3};
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.sumOfThreeElements(array, -1));
+ }
+
+ @Test
+ public void sumOfThreeElements_shouldThrowIllegalArgumentException_whenLengthIsLessThanIndexPlus3() {
+ int[] array = {1, 2, 3};
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.sumOfThreeElements(array, 2));
+ }
+
+ @Test
+ public void sumOfThreeElements_() {
+ int[] array = {1, 2, 3, 4, 5, 6};
+
+ assertEquals(6, Task8.sumOfThreeElements(array, 0));
+ assertEquals(12, Task8.sumOfThreeElements(array, 2));
+ assertEquals(15, Task8.sumOfThreeElements(array, 3));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/decomposing/Task9Test.java b/module2/src/test/java/by/training/dmgolub/decomposing/Task9Test.java
new file mode 100644
index 0000000..37c679e
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/decomposing/Task9Test.java
@@ -0,0 +1,69 @@
+package by.training.dmgolub.decomposing;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Scanner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task9Test {
+
+ @Test
+ public void parseSideSize_shouldThrowIllegalArgumentException_whenScannerIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.parseSideLength(null, "name"));
+ }
+
+ @Test
+ public void parseSideSize_shouldThrowIllegalArgumentException_whenNameIsNull() {
+ Scanner scanner = new Scanner(System.in);
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.parseSideLength(scanner, null));
+ }
+
+ @Test
+ public void computeQuadrilateralArea_shouldReturn12_whenX3Y4Z3T4() {
+ assertEquals(12.0, Task9.computeQuadrilateralArea(3, 4, 3, 4));
+ }
+
+ @Test
+ public void computeRightTriangleArea_shouldThrowIllegalArgumentException_whenAIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.computeRightTriangleArea(-1, 3));
+ }
+
+ @Test
+ public void computeRightTriangleArea_shouldThrowIllegalArgumentException_whenBIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.computeRightTriangleArea(3, -1));
+ }
+
+ @Test
+ public void computeRightTriangleArea_shouldReturn8_whenA8B8() {
+ assertEquals(32, Task9.computeRightTriangleArea(8, 8));
+ }
+
+ @Test
+ public void computeTriangleArea_shouldThrowIllegalArgumentExceptionWhenAIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.computeTriangleArea(-1, 1, 1));
+ }
+
+ @Test
+ public void computeTriangleArea_shouldThrowIllegalArgumentExceptionWhenBIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.computeTriangleArea(1, -1, 1));
+ }
+
+ @Test
+ public void computeTriangleArea_shouldThrowIllegalArgumentExceptionWhenCIsNegative() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.computeTriangleArea(1, 1, -1));
+ }
+
+ @Test
+ public void computeTriangleArea_shouldReturn6_whenA3B4C5() {
+ assertEquals(6.0, Task9.computeTriangleArea(3.0, 4.0, 5.0));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task10Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task10Test.java
new file mode 100644
index 0000000..f962f62
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task10Test.java
@@ -0,0 +1,74 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task10Test {
+
+ @Test
+ public void compressArray_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task10.compressArray(null));
+ }
+
+ @Test
+ public void compressArray_shouldReturn1_whenArrayIs1() {
+ int[] expected = {1};
+ int[] array = {1};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+
+ @Test
+ public void compressArray_shouldReturn10_whenArrayIs12() {
+ int[] expected = {1, 0};
+ int[] array = {1, 2};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+
+ @Test
+ public void compressArray_shouldReturn130_whenArrayIs123() {
+ int[] expected = {1, 3, 0};
+ int[] array = {1, 2, 3};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+
+ @Test
+ public void compressArray_shouldReturn1300_whenArrayIs1234() {
+ int[] expected = {1, 3, 0, 0};
+ int[] array = {1, 2, 3, 4};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+
+ @Test
+ public void compressArray_shouldReturn13500_whenArrayIs12345() {
+ int[] expected = {1, 3, 5, 0, 0};
+ int[] array = {1, 2, 3, 4, 5};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+
+ @Test
+ public void compressArray_shouldReturn135000_whenArrayIs123456() {
+ int[] expected = {1, 3, 5, 0, 0, 0};
+ int[] array = {1, 2, 3, 4, 5, 6};
+
+ Task10.compressArray(array);
+
+ assertArrayEquals(expected, array);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task1Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task1Test.java
new file mode 100644
index 0000000..3c4f700
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task1Test.java
@@ -0,0 +1,35 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task1Test {
+
+ @Test
+ public void sumOfMultiples_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task1.sumOfMultiples(null, 2));
+ }
+
+ @Test
+ public void sumOfMultiples_shouldReturn0_whenArraySizeIs0() {
+ int[] array = new int[0];
+
+ assertEquals(0, Task1.sumOfMultiples(array, 2));
+ }
+
+ @Test
+ public void sumOfMultiples_shouldReturn0_whenThereAreNoMultiples() {
+ int[] array = {1, 3, 5, 7, 9};
+
+ assertEquals(0, Task1.sumOfMultiples(array, 2));
+ }
+
+ @Test
+ public void sumOfMultiples_shouldReturnSum_whenThereAreMultiples() {
+ int[] array = {1, 2, 3, 4, 5, 6};
+
+ assertEquals(12, Task1.sumOfMultiples(array, 2));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task2Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task2Test.java
new file mode 100644
index 0000000..d75a69d
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task2Test.java
@@ -0,0 +1,43 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task2Test {
+
+ @Test
+ public void replaceAllMembers_shouldThrowIllegalArgumentException_whenSequenceIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task2.replaceAllMembersLargerThanGiven(null, 2.0));
+ }
+
+ @Test
+ public void replaceAllMembers_shouldReturn0_whenSequenceSizeIs0() {
+ double[] sequence = new double[0];
+
+ assertEquals(0, Task2.replaceAllMembersLargerThanGiven(sequence, 2.0));
+ }
+
+ @Test
+ public void replaceAllMembers_shouldReplaceMembersAndReturnCount_whenThereAreSuchMembers() {
+ double[] sequence = {1.0, 2.0, 3.0, 4.0, 5.0};
+
+ double[] expected = {1.0, 2.0, 3.0, 3.0, 3.0};
+ int count = Task2.replaceAllMembersLargerThanGiven(sequence, 3.0);
+
+ assertEquals(2, count);
+ assertArrayEquals(expected, sequence);
+ }
+
+ @Test
+ public void replaceAllMembers_shouldNotReplaceMembersAndReturn0_whenThereAreNoSuchMembers() {
+ double[] sequence = {1.0, 2.0, 3.0, 4.0, 5.0};
+
+ double[] expected = {1.0, 2.0, 3.0, 4.0, 5.0};
+ int count = Task2.replaceAllMembersLargerThanGiven(sequence, 6.0);
+
+ assertEquals(0, count);
+ assertArrayEquals(expected, sequence);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task3Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task3Test.java
new file mode 100644
index 0000000..e4329b4
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task3Test.java
@@ -0,0 +1,48 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task3Test {
+
+ @Test
+ public void count_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task3.countNegativeZeroPositiveArrayElements(null));
+ }
+
+ @Test
+ public void count_shouldPrintZeros_whenArrayIsEmpty() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("Number of negative elements = 0");
+ expected.add("Number of zero elements = 0");
+ expected.add("Number of positive elements = 0");
+
+ double[] array = new double[0];
+ Task3.countNegativeZeroPositiveArrayElements(array);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+
+ @Test
+ public void count_shouldCountElementsAndPrintResult_whenArrayIsNotEmpty() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("Number of negative elements = 2");
+ expected.add("Number of zero elements = 1");
+ expected.add("Number of positive elements = 2");
+
+ double[] array = {-2.0, -1.0, 0.0, 1.0, 2.0};
+ Task3.countNegativeZeroPositiveArrayElements(array);
+
+ assertEquals(expected + System.lineSeparator(), out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task4Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task4Test.java
new file mode 100644
index 0000000..e3f821b
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task4Test.java
@@ -0,0 +1,24 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task4Test {
+
+ @Test
+ public void swap_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task4.swapMinAndMaxArrayElements(null));
+ }
+
+ @Test
+ public void swap_shouldSwapElements_whenThereAreMaxAndMinElements() {
+ double[] array = {-1.0, 1.0, 0, 2.0};
+ double[] expected = {2.0, 1.0, 0, -1.0};
+
+ Task4.swapMinAndMaxArrayElements(array);
+
+ assertArrayEquals(expected, array);
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task5Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task5Test.java
new file mode 100644
index 0000000..01e4d1d
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task5Test.java
@@ -0,0 +1,53 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task5Test {
+
+ @Test
+ public void printElements_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task5.printElementsGreaterThanIndex(null));
+ }
+
+ @Test
+ public void printElements_shouldPrintNothing_whenArrayIsEmpty() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+
+ Task5.printElementsGreaterThanIndex(new int[0]);
+
+ assertEquals("", out.toString());
+ }
+
+ @Test
+ public void printElements_shouldPrintNothing_whenThereAreNoSuchElements() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ int[] array = {0, 1, 2, 3, 4};
+
+ Task5.printElementsGreaterThanIndex(array);
+
+ assertEquals("", out.toString());
+ }
+
+ @Test
+ public void printElements_shouldPrintElements_whenThereAreSuchElements() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(out));
+ int[] array = {0, 1, 2, 4, 5, 6};
+ StringJoiner expected = new StringJoiner(System.lineSeparator());
+ expected.add("4").add("5").add("6");
+
+ Task5.printElementsGreaterThanIndex(array);
+
+ assertEquals(expected.toString() + System.lineSeparator(),
+ out.toString());
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task6Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task6Test.java
new file mode 100644
index 0000000..40b2169
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task6Test.java
@@ -0,0 +1,53 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task6Test {
+
+ @Test
+ public void isPrimeNumber_shouldReturnFalse_whenNumberIsNegative() {
+ assertFalse(Task6.isPrimeNumber(-1));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnTrue_whenNumberIs2() {
+ assertTrue(Task6.isPrimeNumber(2));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnFalse_whenNumberIs4() {
+ assertFalse(Task6.isPrimeNumber(4));
+ }
+
+ @Test
+ public void isPrimeNumber_shouldReturnTrue_whenNumberIs5() {
+ assertTrue(Task6.isPrimeNumber(5));
+ }
+
+ @Test
+ public void sumOfElements_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task6.sumOfElementsWithPrimeIndexes(null));
+ }
+
+ @Test
+ public void sumOfElements_shouldReturn0_whenArrayIsEmpty() {
+ assertEquals(0, Task6.sumOfElementsWithPrimeIndexes(new double[0]));
+ }
+
+ @Test
+ public void sumOfElements_shouldReturn0_whenThereAreNoSuchElements() {
+ double[] array = {1.0, 2.0};
+
+ assertEquals(0, Task6.sumOfElementsWithPrimeIndexes(array));
+ }
+
+ @Test
+ public void sumOfElements_shouldReturnSum_whenThereAreSuchElements() {
+ double[] array = {0.0, 1.0, 2.0, 3.0, 4.0};
+
+ assertEquals(5.0, Task6.sumOfElementsWithPrimeIndexes(array));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task7Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task7Test.java
new file mode 100644
index 0000000..10a2515
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task7Test.java
@@ -0,0 +1,36 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task7Test {
+
+ @Test
+ public void findMax_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task7.findMaxOfPairs(null));
+ }
+
+ @Test
+ public void findMax_shouldThrowIllegalArgumentException_whenArrayLengthInNotEven() {
+ double[] array = new double[5];
+
+ assertThrows(IllegalArgumentException.class,
+ () -> Task7.findMaxOfPairs(array));
+ }
+
+ @Test
+ public void findMax_shouldReturnMax_whenThereIsOnePair() {
+ double[] array = {1.0, 2.0};
+
+ assertEquals(3.0, Task7.findMaxOfPairs(array));
+ }
+
+ @Test
+ public void findMax_shouldReturnMax_whenThereAreSeveralPairs() {
+ double[] array = {1.0, 2.0, 3.0, 3.0, 6.0, 6.0};
+
+ assertEquals(8.0, Task7.findMaxOfPairs(array));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task8Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task8Test.java
new file mode 100644
index 0000000..0add2c3
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task8Test.java
@@ -0,0 +1,56 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task8Test {
+
+ @Test
+ public void countElements_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.countElements(null, 1));
+ }
+
+ @Test
+ public void countElements_shouldCountGivenElements_whenThereAreSuchElements() {
+ int[] array = {5, 4, 3, 2, 1, 5};
+
+ assertEquals(2, Task8.countElements(array, 5));
+ }
+
+ @Test
+ public void findMin_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.findMin(null));
+ }
+
+ @Test
+ public void findMin_shouldFindMinElement_whenThereAreElementsInTheArray() {
+ int[] array = {5, 4, 3, 2, 1};
+
+ assertEquals(1, Task8.findMin(array));
+ }
+
+ @Test
+ public void excludeMinElements_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task8.excludeMinElements(null));
+ }
+
+ @Test
+ public void excludeMinElements_shouldReturnEmptyArray_whenAllElementsAreEqual() {
+ int[] array = {1, 1, 1, 1};
+
+ assertArrayEquals(new int[0], Task8.excludeMinElements(array));
+ }
+
+ @Test
+ public void excludeMinElements_shouldReturnArrayWithoutMinElements_whenElementsAreNotEqual() {
+ int[] array = {1, 2, 1, 3, 1, 4};
+
+ int[] expected = {2, 3, 4};
+
+ assertArrayEquals(expected, Task8.excludeMinElements(array));
+ }
+}
\ No newline at end of file
diff --git a/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task9Test.java b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task9Test.java
new file mode 100644
index 0000000..57dd112
--- /dev/null
+++ b/module2/src/test/java/by/training/dmgolub/one_dimensional_array/Task9Test.java
@@ -0,0 +1,41 @@
+package by.training.dmgolub.one_dimensional_array;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class Task9Test {
+
+ @Test
+ public void findMostCN_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.findMostCommonNumber(null));
+ }
+
+ @Test
+ public void findMostCN_shouldReturnMostCommonNumber_whenThereIsOneSuchNumber() {
+ int[] array = {1, 2, 3, 3, 4};
+
+ assertEquals(3, Task9.findMostCommonNumber(array));
+ }
+
+ @Test
+ public void findMostCN_shouldReturnMinimumOfMCNumbers_whenThereAreTwoSuchNumbers() {
+ int[] array = {1, 2, 2, 3, 3, 4};
+
+ assertEquals(2, Task9.findMostCommonNumber(array));
+ }
+
+ @Test
+ public void findMax_shouldThrowIllegalArgumentException_whenArrayIsNull() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Task9.findMax(null));
+ }
+
+ @Test
+ public void findMax_shouldReturnMaxElement_whenArrayContainsElements() {
+ int[] array = {5, 2, 4, 1, 3};
+
+ assertEquals(5, Task9.findMax(array));
+ }
+}
\ No newline at end of file