diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index 0de145f60c67..4aca8fb40624 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java @@ -22,7 +22,9 @@ public class IIRFilter { */ public IIRFilter(int order) throws IllegalArgumentException { if (order < 1) { - throw new IllegalArgumentException("order must be greater than zero"); + throw new IllegalArgumentException( + "order must be greater than zero" + ); } this.order = order; @@ -45,17 +47,24 @@ public IIRFilter(int order) throws IllegalArgumentException { * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 */ - public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { + public void setCoeffs(double[] aCoeffs, double[] bCoeffs) + throws IllegalArgumentException { if (aCoeffs.length != order) { - throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length); + throw new IllegalArgumentException( + "aCoeffs must be of size " + order + ", got " + aCoeffs.length + ); } if (aCoeffs[0] == 0.0) { - throw new IllegalArgumentException("aCoeffs.get(0) must not be zero"); + throw new IllegalArgumentException( + "aCoeffs.get(0) must not be zero" + ); } if (bCoeffs.length != order) { - throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length); + throw new IllegalArgumentException( + "bCoeffs must be of size " + order + ", got " + bCoeffs.length + ); } for (int i = 0; i <= order; i++) { @@ -75,7 +84,8 @@ public double process(double sample) { // Process for (int i = 1; i <= order; i++) { - result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); + result += + (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); } result = (result + coeffsB[0] * sample) / coeffsA[0]; diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index 1298621a179b..c2d148a270e8 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -7,7 +7,9 @@ * @author Alan Piao (https://github.com/cpiao3) */ public class Combination { + private static int length; + /** * Find all combinations of given array using backtracking * @param arr the array. @@ -26,6 +28,7 @@ public static List> combination(T[] arr, int n) { backtracking(array, 0, new TreeSet(), result); return result; } + /** * Backtrack all possible combinations of a given array * @param arr the array. @@ -34,7 +37,12 @@ public static List> combination(T[] arr, int n) { * @param result the list contains all combination. * @param the type of elements in the array. */ - private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) { + private static void backtracking( + T[] arr, + int index, + TreeSet currSet, + List> result + ) { if (index + length - currSet.size() > arr.length) return; if (length - 1 == currSet.size()) { for (int i = index; i < arr.length; i++) { diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java index d7842a6713dd..aeafde33372a 100644 --- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java +++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java @@ -13,13 +13,11 @@ public class FloodFill { * @param x The x co-ordinate of which color is to be obtained * @param y The y co-ordinate of which color is to be obtained */ - - public static int getPixel(int[][] image, int x, int y) { - - return image[x][y]; - - } - + + public static int getPixel(int[][] image, int x, int y) { + return image[x][y]; + } + /** * Put the color at the given co-odrinates of a 2D image * @@ -27,13 +25,10 @@ public static int getPixel(int[][] image, int x, int y) { * @param x The x co-ordinate at which color is to be filled * @param y The y co-ordinate at which color is to be filled */ - public static void putPixel(int[][] image, int x, int y, int newColor) { - - image[x][y] = newColor; - - } - - + public static void putPixel(int[][] image, int x, int y, int newColor) { + image[x][y] = newColor; + } + /** * Fill the 2D image with new color * @@ -44,26 +39,29 @@ public static void putPixel(int[][] image, int x, int y, int newColor) { * @param oldColor The old color which is to be replaced in the image * @return */ - public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { - - if(x < 0 || x >= image.length) return; - if(y < 0 || y >= image[x].length) return; - if(getPixel(image, x, y) != oldColor) return; - - putPixel(image, x, y, newColor); - - /* Recursively check for horizontally & vertically adjacent coordinates */ - floodFill(image, x + 1, y, newColor, oldColor); - floodFill(image, x - 1, y, newColor, oldColor); - floodFill(image, x, y + 1, newColor, oldColor); - floodFill(image, x, y - 1, newColor, oldColor); + public static void floodFill( + int[][] image, + int x, + int y, + int newColor, + int oldColor + ) { + if (x < 0 || x >= image.length) return; + if (y < 0 || y >= image[x].length) return; + if (getPixel(image, x, y) != oldColor) return; - /* Recursively check for diagonally adjacent coordinates */ - floodFill(image, x + 1, y - 1, newColor, oldColor); - floodFill(image, x - 1, y + 1, newColor, oldColor); - floodFill(image, x + 1, y + 1, newColor, oldColor); - floodFill(image, x - 1, y - 1, newColor, oldColor); + putPixel(image, x, y, newColor); - } + /* Recursively check for horizontally & vertically adjacent coordinates */ + floodFill(image, x + 1, y, newColor, oldColor); + floodFill(image, x - 1, y, newColor, oldColor); + floodFill(image, x, y + 1, newColor, oldColor); + floodFill(image, x, y - 1, newColor, oldColor); -} \ No newline at end of file + /* Recursively check for diagonally adjacent coordinates */ + floodFill(image, x + 1, y - 1, newColor, oldColor); + floodFill(image, x - 1, y + 1, newColor, oldColor); + floodFill(image, x + 1, y + 1, newColor, oldColor); + floodFill(image, x - 1, y - 1, newColor, oldColor); + } +} diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java index e337df8f6e8e..a2075fd9d778 100644 --- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java +++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java @@ -25,10 +25,19 @@ */ public class KnightsTour { - private final static int base = 12; - private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; // Possible moves by knight on chess - private static int[][] grid; // chess grid - private static int total; // total squares in chess + private static final int base = 12; + private static final int[][] moves = { + { 1, -2 }, + { 2, -1 }, + { 2, 1 }, + { 1, 2 }, + { -1, 2 }, + { -2, 1 }, + { -2, -1 }, + { -1, -2 }, + }; // Possible moves by knight on chess + private static int[][] grid; // chess grid + private static int total; // total squares in chess public static void main(String[] args) { grid = new int[base][base]; @@ -52,7 +61,6 @@ public static void main(String[] args) { } else { System.out.println("no result"); } - } // Return True when solvable @@ -67,17 +75,23 @@ private static boolean solve(int row, int column, int count) { return false; } - Collections.sort(neighbor, new Comparator() { - public int compare(int[] a, int[] b) { - return a[2] - b[2]; + Collections.sort( + neighbor, + new Comparator() { + public int compare(int[] a, int[] b) { + return a[2] - b[2]; + } } - }); + ); for (int[] nb : neighbor) { row = nb[0]; column = nb[1]; grid[row][column] = count; - if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) { + if ( + !orphanDetected(count, row, column) && + solve(row, column, count + 1) + ) { return true; } grid[row][column] = 0; @@ -95,7 +109,7 @@ private static List neighbors(int row, int column) { int y = m[1]; if (grid[row + y][column + x] == 0) { int num = countNeighbors(row + y, column + x); - neighbour.add(new int[]{row + y, column + x, num}); + neighbour.add(new int[] { row + y, column + x, num }); } } return neighbour; diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java index c52a4e6f847d..60f02b902c06 100644 --- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java +++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java @@ -2,157 +2,154 @@ public class MazeRecursion { - public static void mazeRecursion() { - // First create a 2 dimensions array to mimic a maze map - int[][] map = new int[8][7]; - int[][] map2 = new int[8][7]; - - // We use 1 to indicate wall - // Set the ceiling and floor to 1 - for (int i = 0; i < 7; i++) { - map[0][i] = 1; - map[7][i] = 1; - } - - // Then we set the left and right wall to 1 - for (int i = 0; i < 8; i++) { - map[i][0] = 1; - map[i][6] = 1; - } - - // Now we have created a maze with its wall initialized - - // Here we set the obstacle - map[3][1] = 1; - map[3][2] = 1; - - // Print the current map - System.out.println("The condition of the map: "); - for (int i = 0; i < 8; i++) { - for (int j = 0; j < 7; j++) { - System.out.print(map[i][j] + " "); - } - System.out.println(); - } - - // clone another map for setWay2 method - for (int i = 0; i < map.length; i++) { - for (int j = 0; j < map[i].length; j++) { - map2[i][j] = map[i][j]; - } - } - - // By using recursive backtracking to let your ball(target) find its way in the - // maze - // The first parameter is the map - // Second parameter is x coordinate of your target - // Thrid parameter is the y coordinate of your target - setWay(map, 1, 1); - setWay2(map2, 1, 1); - - // Print out the new map1, with the ball footprint - System.out.println("After the ball goes through the map1,show the current map1 condition"); - for (int i = 0; i < 8; i++) { - for (int j = 0; j < 7; j++) { - System.out.print(map[i][j] + " "); - } - System.out.println(); - } - - // Print out the new map2, with the ball footprint - System.out.println("After the ball goes through the map2,show the current map2 condition"); - for (int i = 0; i < 8; i++) { - for (int j = 0; j < 7; j++) { - System.out.print(map2[i][j] + " "); - } - System.out.println(); - } - } - - - - // Using recursive path finding to help the ball find its way in the maze - // Description: - // 1. map (means the maze) - // 2. i, j (means the initial coordinate of the ball in the maze) - // 3. if the ball can reach the end of maze, that is position of map[6][5], - // means the we have found a path for the ball - // 4. Additional Information: 0 in the map[i][j] means the ball has not gone - // through this position, 1 means the wall, 2 means the path is feasible, 3 - // means the ball has gone through the path but this path is dead end - // 5. We will need strategy for the ball to pass through the maze for example: - // Down -> Right -> Up -> Left, if the path doesn't work, then backtrack - /** - * - * @Description - * @author OngLipWei - * @date Jun 23, 202111:36:14 AM - * @param map The maze - * @param i x coordinate of your ball(target) - * @param j y coordinate of your ball(target) - * @return If we did find a path for the ball,return true,else false - */ - public static boolean setWay(int[][] map, int i, int j) { - if (map[6][5] == 2) {// means the ball find its path, ending condition - return true; - } - if (map[i][j] == 0) { // if the ball haven't gone through this point - // then the ball follows the move strategy : down -> right -> up -> left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 - if (setWay(map, i + 1, j)) { // go down - return true; - } else if (setWay(map, i, j + 1)) { // go right - return true; - } else if (setWay(map, i - 1, j)) { // go up - return true; - } else if (setWay(map, i, j - 1)) { // go left - return true; - } else { - // means that the current point is the dead end, the ball cannot proceed, set - // the current point to 3 and return false, the backtraking will start, it will - // go to the previous step and check for feasible path again - map[i][j] = 3; - return false; - } - - } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the - // ball cannot hit the wall, cannot go to the path that has gone though before, - // and cannot head to deadend. - return false; - } - - } - - // Here is another move strategy for the ball: up->right->down->left - public static boolean setWay2(int[][] map, int i, int j) { - if (map[6][5] == 2) {// means the ball find its path, ending condition - return true; - } - if (map[i][j] == 0) { // if the ball haven't gone through this point - // then the ball follows the move strategy : up->right->down->left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 - if (setWay2(map, i - 1, j)) { // go up - return true; - } else if (setWay2(map, i, j + 1)) { // go right - return true; - } else if (setWay2(map, i + 1, j)) { // go down - return true; - } else if (setWay2(map, i, j - 1)) { // go left - return true; - } else { - // means that the current point is the dead end, the ball cannot proceed, set - // the current point to 3 and return false, the backtraking will start, it will - // go to the previous step and check for feasible path again - map[i][j] = 3; - return false; - } - - } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the - // ball cannot hit the wall, cannot go to the path that has gone though before, - // and cannot head to deadend. - return false; - } - - } - + public static void mazeRecursion() { + // First create a 2 dimensions array to mimic a maze map + int[][] map = new int[8][7]; + int[][] map2 = new int[8][7]; + + // We use 1 to indicate wall + // Set the ceiling and floor to 1 + for (int i = 0; i < 7; i++) { + map[0][i] = 1; + map[7][i] = 1; + } + + // Then we set the left and right wall to 1 + for (int i = 0; i < 8; i++) { + map[i][0] = 1; + map[i][6] = 1; + } + + // Now we have created a maze with its wall initialized + + // Here we set the obstacle + map[3][1] = 1; + map[3][2] = 1; + + // Print the current map + System.out.println("The condition of the map: "); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // clone another map for setWay2 method + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[i].length; j++) { + map2[i][j] = map[i][j]; + } + } + + // By using recursive backtracking to let your ball(target) find its way in the + // maze + // The first parameter is the map + // Second parameter is x coordinate of your target + // Thrid parameter is the y coordinate of your target + setWay(map, 1, 1); + setWay2(map2, 1, 1); + + // Print out the new map1, with the ball footprint + System.out.println( + "After the ball goes through the map1,show the current map1 condition" + ); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // Print out the new map2, with the ball footprint + System.out.println( + "After the ball goes through the map2,show the current map2 condition" + ); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map2[i][j] + " "); + } + System.out.println(); + } + } + + // Using recursive path finding to help the ball find its way in the maze + // Description: + // 1. map (means the maze) + // 2. i, j (means the initial coordinate of the ball in the maze) + // 3. if the ball can reach the end of maze, that is position of map[6][5], + // means the we have found a path for the ball + // 4. Additional Information: 0 in the map[i][j] means the ball has not gone + // through this position, 1 means the wall, 2 means the path is feasible, 3 + // means the ball has gone through the path but this path is dead end + // 5. We will need strategy for the ball to pass through the maze for example: + // Down -> Right -> Up -> Left, if the path doesn't work, then backtrack + /** + * + * @Description + * @author OngLipWei + * @date Jun 23, 202111:36:14 AM + * @param map The maze + * @param i x coordinate of your ball(target) + * @param j y coordinate of your ball(target) + * @return If we did find a path for the ball,return true,else false + */ + public static boolean setWay(int[][] map, int i, int j) { + if (map[6][5] == 2) { // means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : down -> right -> up -> left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay(map, i + 1, j)) { // go down + return true; + } else if (setWay(map, i, j + 1)) { // go right + return true; + } else if (setWay(map, i - 1, j)) { // go up + return true; + } else if (setWay(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + } + + // Here is another move strategy for the ball: up->right->down->left + public static boolean setWay2(int[][] map, int i, int j) { + if (map[6][5] == 2) { // means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : up->right->down->left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay2(map, i - 1, j)) { // go up + return true; + } else if (setWay2(map, i, j + 1)) { // go right + return true; + } else if (setWay2(map, i + 1, j)) { // go down + return true; + } else if (setWay2(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + } } diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java index fb0138d10d20..a567c57b451a 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -47,7 +47,14 @@ public static void placeQueens(final int queens) { List> arrangements = new ArrayList>(); getSolution(queens, arrangements, new int[queens], 0); if (arrangements.isEmpty()) { - System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens); + System.out.println( + "There is no way to place " + + queens + + " queens on board of size " + + queens + + "x" + + queens + ); } else { System.out.println("Arrangement for placing " + queens + " queens"); } @@ -65,7 +72,12 @@ public static void placeQueens(final int queens) { * @param columns: columns[i] = rowId where queen is placed in ith column. * @param columnIndex: This is the column in which queen is being placed */ - private static void getSolution(int boardSize, List> solutions, int[] columns, int columnIndex) { + private static void getSolution( + int boardSize, + List> solutions, + int[] columns, + int columnIndex + ) { if (columnIndex == boardSize) { // this means that all queens have been placed List sol = new ArrayList(); @@ -99,7 +111,11 @@ private static void getSolution(int boardSize, List> solutions, int * @param columnIndex: column in which queen is being placed * @return true: if queen can be placed safely false: otherwise */ - private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { + private static boolean isPlacedCorrectly( + int[] columns, + int rowIndex, + int columnIndex + ) { for (int i = 0; i < columnIndex; i++) { int diff = Math.abs(columns[i] - rowIndex); if (diff == 0 || columnIndex - i == diff) { diff --git a/src/main/java/com/thealgorithms/backtracking/Permutation.java b/src/main/java/com/thealgorithms/backtracking/Permutation.java index e48d8539e65c..9ad18e1e9dc2 100644 --- a/src/main/java/com/thealgorithms/backtracking/Permutation.java +++ b/src/main/java/com/thealgorithms/backtracking/Permutation.java @@ -8,6 +8,7 @@ * @author Alan Piao (https://github.com/cpiao3) */ public class Permutation { + /** * Find all permutations of given array using backtracking * @param arr the array. @@ -20,6 +21,7 @@ public static List permutation(T[] arr) { backtracking(array, 0, result); return result; } + /** * Backtrack all possible orders of a given array * @param arr the array. @@ -37,6 +39,7 @@ private static void backtracking(T[] arr, int index, List result) { swap(index, i, arr); } } + /** * Swap two element for a given array * @param a first index diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java index bbaf83ecaa98..3365255f4600 100644 --- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java +++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java @@ -18,10 +18,17 @@ public static void main(String[] args) { PowerSum ps = new PowerSum(); int count = ps.powSum(N, X); //printing the answer. - System.out.println("Number of combinations of different natural number's raised to " + X + " having sum " + N + " are : "); + System.out.println( + "Number of combinations of different natural number's raised to " + + X + + " having sum " + + N + + " are : " + ); System.out.println(count); sc.close(); } + private int count = 0, sum = 0; public int powSum(int N, int X) { @@ -48,7 +55,7 @@ else if (sum + power(i, X) <= N) { } } - //creating a separate power function so that it can be used again and again when required. + //creating a separate power function so that it can be used again and again when required. private int power(int a, int b) { return (int) Math.pow(a, b); } diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java index 879523af37bc..65c6ce7953c2 100644 --- a/src/main/java/com/thealgorithms/ciphers/AES.java +++ b/src/main/java/com/thealgorithms/ciphers/AES.java @@ -14,22 +14,262 @@ public class AES { * Used as 'RCON' during the key expansion. */ private static final int[] RCON = { - 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, - 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, - 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, - 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, - 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, - 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, - 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, - 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, - 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, - 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, - 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, - 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, - 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, - 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, - 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, - 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d + 0x8d, + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x1b, + 0x36, + 0x6c, + 0xd8, + 0xab, + 0x4d, + 0x9a, + 0x2f, + 0x5e, + 0xbc, + 0x63, + 0xc6, + 0x97, + 0x35, + 0x6a, + 0xd4, + 0xb3, + 0x7d, + 0xfa, + 0xef, + 0xc5, + 0x91, + 0x39, + 0x72, + 0xe4, + 0xd3, + 0xbd, + 0x61, + 0xc2, + 0x9f, + 0x25, + 0x4a, + 0x94, + 0x33, + 0x66, + 0xcc, + 0x83, + 0x1d, + 0x3a, + 0x74, + 0xe8, + 0xcb, + 0x8d, + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x1b, + 0x36, + 0x6c, + 0xd8, + 0xab, + 0x4d, + 0x9a, + 0x2f, + 0x5e, + 0xbc, + 0x63, + 0xc6, + 0x97, + 0x35, + 0x6a, + 0xd4, + 0xb3, + 0x7d, + 0xfa, + 0xef, + 0xc5, + 0x91, + 0x39, + 0x72, + 0xe4, + 0xd3, + 0xbd, + 0x61, + 0xc2, + 0x9f, + 0x25, + 0x4a, + 0x94, + 0x33, + 0x66, + 0xcc, + 0x83, + 0x1d, + 0x3a, + 0x74, + 0xe8, + 0xcb, + 0x8d, + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x1b, + 0x36, + 0x6c, + 0xd8, + 0xab, + 0x4d, + 0x9a, + 0x2f, + 0x5e, + 0xbc, + 0x63, + 0xc6, + 0x97, + 0x35, + 0x6a, + 0xd4, + 0xb3, + 0x7d, + 0xfa, + 0xef, + 0xc5, + 0x91, + 0x39, + 0x72, + 0xe4, + 0xd3, + 0xbd, + 0x61, + 0xc2, + 0x9f, + 0x25, + 0x4a, + 0x94, + 0x33, + 0x66, + 0xcc, + 0x83, + 0x1d, + 0x3a, + 0x74, + 0xe8, + 0xcb, + 0x8d, + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x1b, + 0x36, + 0x6c, + 0xd8, + 0xab, + 0x4d, + 0x9a, + 0x2f, + 0x5e, + 0xbc, + 0x63, + 0xc6, + 0x97, + 0x35, + 0x6a, + 0xd4, + 0xb3, + 0x7d, + 0xfa, + 0xef, + 0xc5, + 0x91, + 0x39, + 0x72, + 0xe4, + 0xd3, + 0xbd, + 0x61, + 0xc2, + 0x9f, + 0x25, + 0x4a, + 0x94, + 0x33, + 0x66, + 0xcc, + 0x83, + 0x1d, + 0x3a, + 0x74, + 0xe8, + 0xcb, + 0x8d, + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x1b, + 0x36, + 0x6c, + 0xd8, + 0xab, + 0x4d, + 0x9a, + 0x2f, + 0x5e, + 0xbc, + 0x63, + 0xc6, + 0x97, + 0x35, + 0x6a, + 0xd4, + 0xb3, + 0x7d, + 0xfa, + 0xef, + 0xc5, + 0x91, + 0x39, + 0x72, + 0xe4, + 0xd3, + 0xbd, + 0x61, + 0xc2, + 0x9f, + 0x25, + 0x4a, + 0x94, + 0x33, + 0x66, + 0xcc, + 0x83, + 0x1d, + 0x3a, + 0x74, + 0xe8, + 0xcb, + 0x8d, }; /** @@ -37,22 +277,262 @@ public class AES { * step, as well as the key expansion. */ private static final int[] SBOX = { - 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, - 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, - 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, - 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, - 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, - 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, - 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, - 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, - 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, - 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, - 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, - 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, - 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, - 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, - 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, - 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 + 0x63, + 0x7C, + 0x77, + 0x7B, + 0xF2, + 0x6B, + 0x6F, + 0xC5, + 0x30, + 0x01, + 0x67, + 0x2B, + 0xFE, + 0xD7, + 0xAB, + 0x76, + 0xCA, + 0x82, + 0xC9, + 0x7D, + 0xFA, + 0x59, + 0x47, + 0xF0, + 0xAD, + 0xD4, + 0xA2, + 0xAF, + 0x9C, + 0xA4, + 0x72, + 0xC0, + 0xB7, + 0xFD, + 0x93, + 0x26, + 0x36, + 0x3F, + 0xF7, + 0xCC, + 0x34, + 0xA5, + 0xE5, + 0xF1, + 0x71, + 0xD8, + 0x31, + 0x15, + 0x04, + 0xC7, + 0x23, + 0xC3, + 0x18, + 0x96, + 0x05, + 0x9A, + 0x07, + 0x12, + 0x80, + 0xE2, + 0xEB, + 0x27, + 0xB2, + 0x75, + 0x09, + 0x83, + 0x2C, + 0x1A, + 0x1B, + 0x6E, + 0x5A, + 0xA0, + 0x52, + 0x3B, + 0xD6, + 0xB3, + 0x29, + 0xE3, + 0x2F, + 0x84, + 0x53, + 0xD1, + 0x00, + 0xED, + 0x20, + 0xFC, + 0xB1, + 0x5B, + 0x6A, + 0xCB, + 0xBE, + 0x39, + 0x4A, + 0x4C, + 0x58, + 0xCF, + 0xD0, + 0xEF, + 0xAA, + 0xFB, + 0x43, + 0x4D, + 0x33, + 0x85, + 0x45, + 0xF9, + 0x02, + 0x7F, + 0x50, + 0x3C, + 0x9F, + 0xA8, + 0x51, + 0xA3, + 0x40, + 0x8F, + 0x92, + 0x9D, + 0x38, + 0xF5, + 0xBC, + 0xB6, + 0xDA, + 0x21, + 0x10, + 0xFF, + 0xF3, + 0xD2, + 0xCD, + 0x0C, + 0x13, + 0xEC, + 0x5F, + 0x97, + 0x44, + 0x17, + 0xC4, + 0xA7, + 0x7E, + 0x3D, + 0x64, + 0x5D, + 0x19, + 0x73, + 0x60, + 0x81, + 0x4F, + 0xDC, + 0x22, + 0x2A, + 0x90, + 0x88, + 0x46, + 0xEE, + 0xB8, + 0x14, + 0xDE, + 0x5E, + 0x0B, + 0xDB, + 0xE0, + 0x32, + 0x3A, + 0x0A, + 0x49, + 0x06, + 0x24, + 0x5C, + 0xC2, + 0xD3, + 0xAC, + 0x62, + 0x91, + 0x95, + 0xE4, + 0x79, + 0xE7, + 0xC8, + 0x37, + 0x6D, + 0x8D, + 0xD5, + 0x4E, + 0xA9, + 0x6C, + 0x56, + 0xF4, + 0xEA, + 0x65, + 0x7A, + 0xAE, + 0x08, + 0xBA, + 0x78, + 0x25, + 0x2E, + 0x1C, + 0xA6, + 0xB4, + 0xC6, + 0xE8, + 0xDD, + 0x74, + 0x1F, + 0x4B, + 0xBD, + 0x8B, + 0x8A, + 0x70, + 0x3E, + 0xB5, + 0x66, + 0x48, + 0x03, + 0xF6, + 0x0E, + 0x61, + 0x35, + 0x57, + 0xB9, + 0x86, + 0xC1, + 0x1D, + 0x9E, + 0xE1, + 0xF8, + 0x98, + 0x11, + 0x69, + 0xD9, + 0x8E, + 0x94, + 0x9B, + 0x1E, + 0x87, + 0xE9, + 0xCE, + 0x55, + 0x28, + 0xDF, + 0x8C, + 0xA1, + 0x89, + 0x0D, + 0xBF, + 0xE6, + 0x42, + 0x68, + 0x41, + 0x99, + 0x2D, + 0x0F, + 0xB0, + 0x54, + 0xBB, + 0x16, }; /** @@ -60,22 +540,262 @@ public class AES { * subBytesDec step. */ private static final int[] INVERSE_SBOX = { - 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, - 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, - 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, - 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, - 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, - 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, - 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, - 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, - 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, - 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, - 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, - 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, - 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, - 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, - 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D + 0x52, + 0x09, + 0x6A, + 0xD5, + 0x30, + 0x36, + 0xA5, + 0x38, + 0xBF, + 0x40, + 0xA3, + 0x9E, + 0x81, + 0xF3, + 0xD7, + 0xFB, + 0x7C, + 0xE3, + 0x39, + 0x82, + 0x9B, + 0x2F, + 0xFF, + 0x87, + 0x34, + 0x8E, + 0x43, + 0x44, + 0xC4, + 0xDE, + 0xE9, + 0xCB, + 0x54, + 0x7B, + 0x94, + 0x32, + 0xA6, + 0xC2, + 0x23, + 0x3D, + 0xEE, + 0x4C, + 0x95, + 0x0B, + 0x42, + 0xFA, + 0xC3, + 0x4E, + 0x08, + 0x2E, + 0xA1, + 0x66, + 0x28, + 0xD9, + 0x24, + 0xB2, + 0x76, + 0x5B, + 0xA2, + 0x49, + 0x6D, + 0x8B, + 0xD1, + 0x25, + 0x72, + 0xF8, + 0xF6, + 0x64, + 0x86, + 0x68, + 0x98, + 0x16, + 0xD4, + 0xA4, + 0x5C, + 0xCC, + 0x5D, + 0x65, + 0xB6, + 0x92, + 0x6C, + 0x70, + 0x48, + 0x50, + 0xFD, + 0xED, + 0xB9, + 0xDA, + 0x5E, + 0x15, + 0x46, + 0x57, + 0xA7, + 0x8D, + 0x9D, + 0x84, + 0x90, + 0xD8, + 0xAB, + 0x00, + 0x8C, + 0xBC, + 0xD3, + 0x0A, + 0xF7, + 0xE4, + 0x58, + 0x05, + 0xB8, + 0xB3, + 0x45, + 0x06, + 0xD0, + 0x2C, + 0x1E, + 0x8F, + 0xCA, + 0x3F, + 0x0F, + 0x02, + 0xC1, + 0xAF, + 0xBD, + 0x03, + 0x01, + 0x13, + 0x8A, + 0x6B, + 0x3A, + 0x91, + 0x11, + 0x41, + 0x4F, + 0x67, + 0xDC, + 0xEA, + 0x97, + 0xF2, + 0xCF, + 0xCE, + 0xF0, + 0xB4, + 0xE6, + 0x73, + 0x96, + 0xAC, + 0x74, + 0x22, + 0xE7, + 0xAD, + 0x35, + 0x85, + 0xE2, + 0xF9, + 0x37, + 0xE8, + 0x1C, + 0x75, + 0xDF, + 0x6E, + 0x47, + 0xF1, + 0x1A, + 0x71, + 0x1D, + 0x29, + 0xC5, + 0x89, + 0x6F, + 0xB7, + 0x62, + 0x0E, + 0xAA, + 0x18, + 0xBE, + 0x1B, + 0xFC, + 0x56, + 0x3E, + 0x4B, + 0xC6, + 0xD2, + 0x79, + 0x20, + 0x9A, + 0xDB, + 0xC0, + 0xFE, + 0x78, + 0xCD, + 0x5A, + 0xF4, + 0x1F, + 0xDD, + 0xA8, + 0x33, + 0x88, + 0x07, + 0xC7, + 0x31, + 0xB1, + 0x12, + 0x10, + 0x59, + 0x27, + 0x80, + 0xEC, + 0x5F, + 0x60, + 0x51, + 0x7F, + 0xA9, + 0x19, + 0xB5, + 0x4A, + 0x0D, + 0x2D, + 0xE5, + 0x7A, + 0x9F, + 0x93, + 0xC9, + 0x9C, + 0xEF, + 0xA0, + 0xE0, + 0x3B, + 0x4D, + 0xAE, + 0x2A, + 0xF5, + 0xB0, + 0xC8, + 0xEB, + 0xBB, + 0x3C, + 0x83, + 0x53, + 0x99, + 0x61, + 0x17, + 0x2B, + 0x04, + 0x7E, + 0xBA, + 0x77, + 0xD6, + 0x26, + 0xE1, + 0x69, + 0x14, + 0x63, + 0x55, + 0x21, + 0x0C, + 0x7D, }; /** @@ -83,22 +803,262 @@ public class AES { * the MixColums step during encryption. */ private static final int[] MULT2 = { - 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, - 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, - 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, - 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, - 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, - 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, - 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, - 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, - 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05, - 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25, - 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, - 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, - 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, - 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, - 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, - 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 + 0x00, + 0x02, + 0x04, + 0x06, + 0x08, + 0x0a, + 0x0c, + 0x0e, + 0x10, + 0x12, + 0x14, + 0x16, + 0x18, + 0x1a, + 0x1c, + 0x1e, + 0x20, + 0x22, + 0x24, + 0x26, + 0x28, + 0x2a, + 0x2c, + 0x2e, + 0x30, + 0x32, + 0x34, + 0x36, + 0x38, + 0x3a, + 0x3c, + 0x3e, + 0x40, + 0x42, + 0x44, + 0x46, + 0x48, + 0x4a, + 0x4c, + 0x4e, + 0x50, + 0x52, + 0x54, + 0x56, + 0x58, + 0x5a, + 0x5c, + 0x5e, + 0x60, + 0x62, + 0x64, + 0x66, + 0x68, + 0x6a, + 0x6c, + 0x6e, + 0x70, + 0x72, + 0x74, + 0x76, + 0x78, + 0x7a, + 0x7c, + 0x7e, + 0x80, + 0x82, + 0x84, + 0x86, + 0x88, + 0x8a, + 0x8c, + 0x8e, + 0x90, + 0x92, + 0x94, + 0x96, + 0x98, + 0x9a, + 0x9c, + 0x9e, + 0xa0, + 0xa2, + 0xa4, + 0xa6, + 0xa8, + 0xaa, + 0xac, + 0xae, + 0xb0, + 0xb2, + 0xb4, + 0xb6, + 0xb8, + 0xba, + 0xbc, + 0xbe, + 0xc0, + 0xc2, + 0xc4, + 0xc6, + 0xc8, + 0xca, + 0xcc, + 0xce, + 0xd0, + 0xd2, + 0xd4, + 0xd6, + 0xd8, + 0xda, + 0xdc, + 0xde, + 0xe0, + 0xe2, + 0xe4, + 0xe6, + 0xe8, + 0xea, + 0xec, + 0xee, + 0xf0, + 0xf2, + 0xf4, + 0xf6, + 0xf8, + 0xfa, + 0xfc, + 0xfe, + 0x1b, + 0x19, + 0x1f, + 0x1d, + 0x13, + 0x11, + 0x17, + 0x15, + 0x0b, + 0x09, + 0x0f, + 0x0d, + 0x03, + 0x01, + 0x07, + 0x05, + 0x3b, + 0x39, + 0x3f, + 0x3d, + 0x33, + 0x31, + 0x37, + 0x35, + 0x2b, + 0x29, + 0x2f, + 0x2d, + 0x23, + 0x21, + 0x27, + 0x25, + 0x5b, + 0x59, + 0x5f, + 0x5d, + 0x53, + 0x51, + 0x57, + 0x55, + 0x4b, + 0x49, + 0x4f, + 0x4d, + 0x43, + 0x41, + 0x47, + 0x45, + 0x7b, + 0x79, + 0x7f, + 0x7d, + 0x73, + 0x71, + 0x77, + 0x75, + 0x6b, + 0x69, + 0x6f, + 0x6d, + 0x63, + 0x61, + 0x67, + 0x65, + 0x9b, + 0x99, + 0x9f, + 0x9d, + 0x93, + 0x91, + 0x97, + 0x95, + 0x8b, + 0x89, + 0x8f, + 0x8d, + 0x83, + 0x81, + 0x87, + 0x85, + 0xbb, + 0xb9, + 0xbf, + 0xbd, + 0xb3, + 0xb1, + 0xb7, + 0xb5, + 0xab, + 0xa9, + 0xaf, + 0xad, + 0xa3, + 0xa1, + 0xa7, + 0xa5, + 0xdb, + 0xd9, + 0xdf, + 0xdd, + 0xd3, + 0xd1, + 0xd7, + 0xd5, + 0xcb, + 0xc9, + 0xcf, + 0xcd, + 0xc3, + 0xc1, + 0xc7, + 0xc5, + 0xfb, + 0xf9, + 0xff, + 0xfd, + 0xf3, + 0xf1, + 0xf7, + 0xf5, + 0xeb, + 0xe9, + 0xef, + 0xed, + 0xe3, + 0xe1, + 0xe7, + 0xe5, }; /** @@ -106,22 +1066,262 @@ public class AES { * the MixColums step during encryption. */ private static final int[] MULT3 = { - 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11, - 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, - 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, - 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, - 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, - 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, - 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, - 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, - 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a, - 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba, - 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, - 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, - 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, - 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, - 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, - 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a + 0x00, + 0x03, + 0x06, + 0x05, + 0x0c, + 0x0f, + 0x0a, + 0x09, + 0x18, + 0x1b, + 0x1e, + 0x1d, + 0x14, + 0x17, + 0x12, + 0x11, + 0x30, + 0x33, + 0x36, + 0x35, + 0x3c, + 0x3f, + 0x3a, + 0x39, + 0x28, + 0x2b, + 0x2e, + 0x2d, + 0x24, + 0x27, + 0x22, + 0x21, + 0x60, + 0x63, + 0x66, + 0x65, + 0x6c, + 0x6f, + 0x6a, + 0x69, + 0x78, + 0x7b, + 0x7e, + 0x7d, + 0x74, + 0x77, + 0x72, + 0x71, + 0x50, + 0x53, + 0x56, + 0x55, + 0x5c, + 0x5f, + 0x5a, + 0x59, + 0x48, + 0x4b, + 0x4e, + 0x4d, + 0x44, + 0x47, + 0x42, + 0x41, + 0xc0, + 0xc3, + 0xc6, + 0xc5, + 0xcc, + 0xcf, + 0xca, + 0xc9, + 0xd8, + 0xdb, + 0xde, + 0xdd, + 0xd4, + 0xd7, + 0xd2, + 0xd1, + 0xf0, + 0xf3, + 0xf6, + 0xf5, + 0xfc, + 0xff, + 0xfa, + 0xf9, + 0xe8, + 0xeb, + 0xee, + 0xed, + 0xe4, + 0xe7, + 0xe2, + 0xe1, + 0xa0, + 0xa3, + 0xa6, + 0xa5, + 0xac, + 0xaf, + 0xaa, + 0xa9, + 0xb8, + 0xbb, + 0xbe, + 0xbd, + 0xb4, + 0xb7, + 0xb2, + 0xb1, + 0x90, + 0x93, + 0x96, + 0x95, + 0x9c, + 0x9f, + 0x9a, + 0x99, + 0x88, + 0x8b, + 0x8e, + 0x8d, + 0x84, + 0x87, + 0x82, + 0x81, + 0x9b, + 0x98, + 0x9d, + 0x9e, + 0x97, + 0x94, + 0x91, + 0x92, + 0x83, + 0x80, + 0x85, + 0x86, + 0x8f, + 0x8c, + 0x89, + 0x8a, + 0xab, + 0xa8, + 0xad, + 0xae, + 0xa7, + 0xa4, + 0xa1, + 0xa2, + 0xb3, + 0xb0, + 0xb5, + 0xb6, + 0xbf, + 0xbc, + 0xb9, + 0xba, + 0xfb, + 0xf8, + 0xfd, + 0xfe, + 0xf7, + 0xf4, + 0xf1, + 0xf2, + 0xe3, + 0xe0, + 0xe5, + 0xe6, + 0xef, + 0xec, + 0xe9, + 0xea, + 0xcb, + 0xc8, + 0xcd, + 0xce, + 0xc7, + 0xc4, + 0xc1, + 0xc2, + 0xd3, + 0xd0, + 0xd5, + 0xd6, + 0xdf, + 0xdc, + 0xd9, + 0xda, + 0x5b, + 0x58, + 0x5d, + 0x5e, + 0x57, + 0x54, + 0x51, + 0x52, + 0x43, + 0x40, + 0x45, + 0x46, + 0x4f, + 0x4c, + 0x49, + 0x4a, + 0x6b, + 0x68, + 0x6d, + 0x6e, + 0x67, + 0x64, + 0x61, + 0x62, + 0x73, + 0x70, + 0x75, + 0x76, + 0x7f, + 0x7c, + 0x79, + 0x7a, + 0x3b, + 0x38, + 0x3d, + 0x3e, + 0x37, + 0x34, + 0x31, + 0x32, + 0x23, + 0x20, + 0x25, + 0x26, + 0x2f, + 0x2c, + 0x29, + 0x2a, + 0x0b, + 0x08, + 0x0d, + 0x0e, + 0x07, + 0x04, + 0x01, + 0x02, + 0x13, + 0x10, + 0x15, + 0x16, + 0x1f, + 0x1c, + 0x19, + 0x1a, }; /** @@ -129,22 +1329,262 @@ public class AES { * the MixColums step during decryption. */ private static final int[] MULT9 = { - 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, - 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, - 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, - 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, - 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, - 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, - 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, - 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, - 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b, - 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b, - 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, - 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, - 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, - 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, - 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, - 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46 + 0x00, + 0x09, + 0x12, + 0x1b, + 0x24, + 0x2d, + 0x36, + 0x3f, + 0x48, + 0x41, + 0x5a, + 0x53, + 0x6c, + 0x65, + 0x7e, + 0x77, + 0x90, + 0x99, + 0x82, + 0x8b, + 0xb4, + 0xbd, + 0xa6, + 0xaf, + 0xd8, + 0xd1, + 0xca, + 0xc3, + 0xfc, + 0xf5, + 0xee, + 0xe7, + 0x3b, + 0x32, + 0x29, + 0x20, + 0x1f, + 0x16, + 0x0d, + 0x04, + 0x73, + 0x7a, + 0x61, + 0x68, + 0x57, + 0x5e, + 0x45, + 0x4c, + 0xab, + 0xa2, + 0xb9, + 0xb0, + 0x8f, + 0x86, + 0x9d, + 0x94, + 0xe3, + 0xea, + 0xf1, + 0xf8, + 0xc7, + 0xce, + 0xd5, + 0xdc, + 0x76, + 0x7f, + 0x64, + 0x6d, + 0x52, + 0x5b, + 0x40, + 0x49, + 0x3e, + 0x37, + 0x2c, + 0x25, + 0x1a, + 0x13, + 0x08, + 0x01, + 0xe6, + 0xef, + 0xf4, + 0xfd, + 0xc2, + 0xcb, + 0xd0, + 0xd9, + 0xae, + 0xa7, + 0xbc, + 0xb5, + 0x8a, + 0x83, + 0x98, + 0x91, + 0x4d, + 0x44, + 0x5f, + 0x56, + 0x69, + 0x60, + 0x7b, + 0x72, + 0x05, + 0x0c, + 0x17, + 0x1e, + 0x21, + 0x28, + 0x33, + 0x3a, + 0xdd, + 0xd4, + 0xcf, + 0xc6, + 0xf9, + 0xf0, + 0xeb, + 0xe2, + 0x95, + 0x9c, + 0x87, + 0x8e, + 0xb1, + 0xb8, + 0xa3, + 0xaa, + 0xec, + 0xe5, + 0xfe, + 0xf7, + 0xc8, + 0xc1, + 0xda, + 0xd3, + 0xa4, + 0xad, + 0xb6, + 0xbf, + 0x80, + 0x89, + 0x92, + 0x9b, + 0x7c, + 0x75, + 0x6e, + 0x67, + 0x58, + 0x51, + 0x4a, + 0x43, + 0x34, + 0x3d, + 0x26, + 0x2f, + 0x10, + 0x19, + 0x02, + 0x0b, + 0xd7, + 0xde, + 0xc5, + 0xcc, + 0xf3, + 0xfa, + 0xe1, + 0xe8, + 0x9f, + 0x96, + 0x8d, + 0x84, + 0xbb, + 0xb2, + 0xa9, + 0xa0, + 0x47, + 0x4e, + 0x55, + 0x5c, + 0x63, + 0x6a, + 0x71, + 0x78, + 0x0f, + 0x06, + 0x1d, + 0x14, + 0x2b, + 0x22, + 0x39, + 0x30, + 0x9a, + 0x93, + 0x88, + 0x81, + 0xbe, + 0xb7, + 0xac, + 0xa5, + 0xd2, + 0xdb, + 0xc0, + 0xc9, + 0xf6, + 0xff, + 0xe4, + 0xed, + 0x0a, + 0x03, + 0x18, + 0x11, + 0x2e, + 0x27, + 0x3c, + 0x35, + 0x42, + 0x4b, + 0x50, + 0x59, + 0x66, + 0x6f, + 0x74, + 0x7d, + 0xa1, + 0xa8, + 0xb3, + 0xba, + 0x85, + 0x8c, + 0x97, + 0x9e, + 0xe9, + 0xe0, + 0xfb, + 0xf2, + 0xcd, + 0xc4, + 0xdf, + 0xd6, + 0x31, + 0x38, + 0x23, + 0x2a, + 0x15, + 0x1c, + 0x07, + 0x0e, + 0x79, + 0x70, + 0x6b, + 0x62, + 0x5d, + 0x54, + 0x4f, + 0x46, }; /** @@ -152,22 +1592,262 @@ public class AES { * the MixColums step during decryption. */ private static final int[] MULT11 = { - 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69, - 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, - 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, - 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, - 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, - 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, - 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, - 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, - 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e, - 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e, - 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, - 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, - 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, - 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, - 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, - 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3 + 0x00, + 0x0b, + 0x16, + 0x1d, + 0x2c, + 0x27, + 0x3a, + 0x31, + 0x58, + 0x53, + 0x4e, + 0x45, + 0x74, + 0x7f, + 0x62, + 0x69, + 0xb0, + 0xbb, + 0xa6, + 0xad, + 0x9c, + 0x97, + 0x8a, + 0x81, + 0xe8, + 0xe3, + 0xfe, + 0xf5, + 0xc4, + 0xcf, + 0xd2, + 0xd9, + 0x7b, + 0x70, + 0x6d, + 0x66, + 0x57, + 0x5c, + 0x41, + 0x4a, + 0x23, + 0x28, + 0x35, + 0x3e, + 0x0f, + 0x04, + 0x19, + 0x12, + 0xcb, + 0xc0, + 0xdd, + 0xd6, + 0xe7, + 0xec, + 0xf1, + 0xfa, + 0x93, + 0x98, + 0x85, + 0x8e, + 0xbf, + 0xb4, + 0xa9, + 0xa2, + 0xf6, + 0xfd, + 0xe0, + 0xeb, + 0xda, + 0xd1, + 0xcc, + 0xc7, + 0xae, + 0xa5, + 0xb8, + 0xb3, + 0x82, + 0x89, + 0x94, + 0x9f, + 0x46, + 0x4d, + 0x50, + 0x5b, + 0x6a, + 0x61, + 0x7c, + 0x77, + 0x1e, + 0x15, + 0x08, + 0x03, + 0x32, + 0x39, + 0x24, + 0x2f, + 0x8d, + 0x86, + 0x9b, + 0x90, + 0xa1, + 0xaa, + 0xb7, + 0xbc, + 0xd5, + 0xde, + 0xc3, + 0xc8, + 0xf9, + 0xf2, + 0xef, + 0xe4, + 0x3d, + 0x36, + 0x2b, + 0x20, + 0x11, + 0x1a, + 0x07, + 0x0c, + 0x65, + 0x6e, + 0x73, + 0x78, + 0x49, + 0x42, + 0x5f, + 0x54, + 0xf7, + 0xfc, + 0xe1, + 0xea, + 0xdb, + 0xd0, + 0xcd, + 0xc6, + 0xaf, + 0xa4, + 0xb9, + 0xb2, + 0x83, + 0x88, + 0x95, + 0x9e, + 0x47, + 0x4c, + 0x51, + 0x5a, + 0x6b, + 0x60, + 0x7d, + 0x76, + 0x1f, + 0x14, + 0x09, + 0x02, + 0x33, + 0x38, + 0x25, + 0x2e, + 0x8c, + 0x87, + 0x9a, + 0x91, + 0xa0, + 0xab, + 0xb6, + 0xbd, + 0xd4, + 0xdf, + 0xc2, + 0xc9, + 0xf8, + 0xf3, + 0xee, + 0xe5, + 0x3c, + 0x37, + 0x2a, + 0x21, + 0x10, + 0x1b, + 0x06, + 0x0d, + 0x64, + 0x6f, + 0x72, + 0x79, + 0x48, + 0x43, + 0x5e, + 0x55, + 0x01, + 0x0a, + 0x17, + 0x1c, + 0x2d, + 0x26, + 0x3b, + 0x30, + 0x59, + 0x52, + 0x4f, + 0x44, + 0x75, + 0x7e, + 0x63, + 0x68, + 0xb1, + 0xba, + 0xa7, + 0xac, + 0x9d, + 0x96, + 0x8b, + 0x80, + 0xe9, + 0xe2, + 0xff, + 0xf4, + 0xc5, + 0xce, + 0xd3, + 0xd8, + 0x7a, + 0x71, + 0x6c, + 0x67, + 0x56, + 0x5d, + 0x40, + 0x4b, + 0x22, + 0x29, + 0x34, + 0x3f, + 0x0e, + 0x05, + 0x18, + 0x13, + 0xca, + 0xc1, + 0xdc, + 0xd7, + 0xe6, + 0xed, + 0xf0, + 0xfb, + 0x92, + 0x99, + 0x84, + 0x8f, + 0xbe, + 0xb5, + 0xa8, + 0xa3, }; /** @@ -175,22 +1855,262 @@ public class AES { * the MixColums step during decryption. */ private static final int[] MULT13 = { - 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b, - 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, - 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, - 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, - 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, - 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, - 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, - 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, - 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91, - 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41, - 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, - 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, - 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, - 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, - 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, - 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 + 0x00, + 0x0d, + 0x1a, + 0x17, + 0x34, + 0x39, + 0x2e, + 0x23, + 0x68, + 0x65, + 0x72, + 0x7f, + 0x5c, + 0x51, + 0x46, + 0x4b, + 0xd0, + 0xdd, + 0xca, + 0xc7, + 0xe4, + 0xe9, + 0xfe, + 0xf3, + 0xb8, + 0xb5, + 0xa2, + 0xaf, + 0x8c, + 0x81, + 0x96, + 0x9b, + 0xbb, + 0xb6, + 0xa1, + 0xac, + 0x8f, + 0x82, + 0x95, + 0x98, + 0xd3, + 0xde, + 0xc9, + 0xc4, + 0xe7, + 0xea, + 0xfd, + 0xf0, + 0x6b, + 0x66, + 0x71, + 0x7c, + 0x5f, + 0x52, + 0x45, + 0x48, + 0x03, + 0x0e, + 0x19, + 0x14, + 0x37, + 0x3a, + 0x2d, + 0x20, + 0x6d, + 0x60, + 0x77, + 0x7a, + 0x59, + 0x54, + 0x43, + 0x4e, + 0x05, + 0x08, + 0x1f, + 0x12, + 0x31, + 0x3c, + 0x2b, + 0x26, + 0xbd, + 0xb0, + 0xa7, + 0xaa, + 0x89, + 0x84, + 0x93, + 0x9e, + 0xd5, + 0xd8, + 0xcf, + 0xc2, + 0xe1, + 0xec, + 0xfb, + 0xf6, + 0xd6, + 0xdb, + 0xcc, + 0xc1, + 0xe2, + 0xef, + 0xf8, + 0xf5, + 0xbe, + 0xb3, + 0xa4, + 0xa9, + 0x8a, + 0x87, + 0x90, + 0x9d, + 0x06, + 0x0b, + 0x1c, + 0x11, + 0x32, + 0x3f, + 0x28, + 0x25, + 0x6e, + 0x63, + 0x74, + 0x79, + 0x5a, + 0x57, + 0x40, + 0x4d, + 0xda, + 0xd7, + 0xc0, + 0xcd, + 0xee, + 0xe3, + 0xf4, + 0xf9, + 0xb2, + 0xbf, + 0xa8, + 0xa5, + 0x86, + 0x8b, + 0x9c, + 0x91, + 0x0a, + 0x07, + 0x10, + 0x1d, + 0x3e, + 0x33, + 0x24, + 0x29, + 0x62, + 0x6f, + 0x78, + 0x75, + 0x56, + 0x5b, + 0x4c, + 0x41, + 0x61, + 0x6c, + 0x7b, + 0x76, + 0x55, + 0x58, + 0x4f, + 0x42, + 0x09, + 0x04, + 0x13, + 0x1e, + 0x3d, + 0x30, + 0x27, + 0x2a, + 0xb1, + 0xbc, + 0xab, + 0xa6, + 0x85, + 0x88, + 0x9f, + 0x92, + 0xd9, + 0xd4, + 0xc3, + 0xce, + 0xed, + 0xe0, + 0xf7, + 0xfa, + 0xb7, + 0xba, + 0xad, + 0xa0, + 0x83, + 0x8e, + 0x99, + 0x94, + 0xdf, + 0xd2, + 0xc5, + 0xc8, + 0xeb, + 0xe6, + 0xf1, + 0xfc, + 0x67, + 0x6a, + 0x7d, + 0x70, + 0x53, + 0x5e, + 0x49, + 0x44, + 0x0f, + 0x02, + 0x15, + 0x18, + 0x3b, + 0x36, + 0x21, + 0x2c, + 0x0c, + 0x01, + 0x16, + 0x1b, + 0x38, + 0x35, + 0x22, + 0x2f, + 0x64, + 0x69, + 0x7e, + 0x73, + 0x50, + 0x5d, + 0x4a, + 0x47, + 0xdc, + 0xd1, + 0xc6, + 0xcb, + 0xe8, + 0xe5, + 0xf2, + 0xff, + 0xb4, + 0xb9, + 0xae, + 0xa3, + 0x80, + 0x8d, + 0x9a, + 0x97, }; /** @@ -198,22 +2118,262 @@ public class AES { * the MixColums step during decryption. */ private static final int[] MULT14 = { - 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a, - 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, - 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, - 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, - 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, - 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, - 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, - 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, - 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b, - 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb, - 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0, - 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, - 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, - 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, - 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, - 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d + 0x00, + 0x0e, + 0x1c, + 0x12, + 0x38, + 0x36, + 0x24, + 0x2a, + 0x70, + 0x7e, + 0x6c, + 0x62, + 0x48, + 0x46, + 0x54, + 0x5a, + 0xe0, + 0xee, + 0xfc, + 0xf2, + 0xd8, + 0xd6, + 0xc4, + 0xca, + 0x90, + 0x9e, + 0x8c, + 0x82, + 0xa8, + 0xa6, + 0xb4, + 0xba, + 0xdb, + 0xd5, + 0xc7, + 0xc9, + 0xe3, + 0xed, + 0xff, + 0xf1, + 0xab, + 0xa5, + 0xb7, + 0xb9, + 0x93, + 0x9d, + 0x8f, + 0x81, + 0x3b, + 0x35, + 0x27, + 0x29, + 0x03, + 0x0d, + 0x1f, + 0x11, + 0x4b, + 0x45, + 0x57, + 0x59, + 0x73, + 0x7d, + 0x6f, + 0x61, + 0xad, + 0xa3, + 0xb1, + 0xbf, + 0x95, + 0x9b, + 0x89, + 0x87, + 0xdd, + 0xd3, + 0xc1, + 0xcf, + 0xe5, + 0xeb, + 0xf9, + 0xf7, + 0x4d, + 0x43, + 0x51, + 0x5f, + 0x75, + 0x7b, + 0x69, + 0x67, + 0x3d, + 0x33, + 0x21, + 0x2f, + 0x05, + 0x0b, + 0x19, + 0x17, + 0x76, + 0x78, + 0x6a, + 0x64, + 0x4e, + 0x40, + 0x52, + 0x5c, + 0x06, + 0x08, + 0x1a, + 0x14, + 0x3e, + 0x30, + 0x22, + 0x2c, + 0x96, + 0x98, + 0x8a, + 0x84, + 0xae, + 0xa0, + 0xb2, + 0xbc, + 0xe6, + 0xe8, + 0xfa, + 0xf4, + 0xde, + 0xd0, + 0xc2, + 0xcc, + 0x41, + 0x4f, + 0x5d, + 0x53, + 0x79, + 0x77, + 0x65, + 0x6b, + 0x31, + 0x3f, + 0x2d, + 0x23, + 0x09, + 0x07, + 0x15, + 0x1b, + 0xa1, + 0xaf, + 0xbd, + 0xb3, + 0x99, + 0x97, + 0x85, + 0x8b, + 0xd1, + 0xdf, + 0xcd, + 0xc3, + 0xe9, + 0xe7, + 0xf5, + 0xfb, + 0x9a, + 0x94, + 0x86, + 0x88, + 0xa2, + 0xac, + 0xbe, + 0xb0, + 0xea, + 0xe4, + 0xf6, + 0xf8, + 0xd2, + 0xdc, + 0xce, + 0xc0, + 0x7a, + 0x74, + 0x66, + 0x68, + 0x42, + 0x4c, + 0x5e, + 0x50, + 0x0a, + 0x04, + 0x16, + 0x18, + 0x32, + 0x3c, + 0x2e, + 0x20, + 0xec, + 0xe2, + 0xf0, + 0xfe, + 0xd4, + 0xda, + 0xc8, + 0xc6, + 0x9c, + 0x92, + 0x80, + 0x8e, + 0xa4, + 0xaa, + 0xb8, + 0xb6, + 0x0c, + 0x02, + 0x10, + 0x1e, + 0x34, + 0x3a, + 0x28, + 0x26, + 0x7c, + 0x72, + 0x60, + 0x6e, + 0x44, + 0x4a, + 0x58, + 0x56, + 0x37, + 0x39, + 0x2b, + 0x25, + 0x0f, + 0x01, + 0x13, + 0x1d, + 0x47, + 0x49, + 0x5b, + 0x55, + 0x7f, + 0x71, + 0x63, + 0x6d, + 0xd7, + 0xd9, + 0xcb, + 0xc5, + 0xef, + 0xe1, + 0xf3, + 0xfd, + 0xa7, + 0xa9, + 0xbb, + 0xb5, + 0x9f, + 0x91, + 0x83, + 0x8d, }; /** @@ -235,7 +2395,9 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { // apply S-Box to all 8-Bit Substrings for (int i = 0; i < 4; i++) { - StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2)); + StringBuilder currentByteBits = new StringBuilder( + rBytes.substring(i * 2, (i + 1) * 2) + ); int currentByte = Integer.parseInt(currentByteBits.toString(), 16); currentByte = SBOX[currentByte]; @@ -245,7 +2407,8 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { currentByte = currentByte ^ RCON[rconCounter]; } - currentByteBits = new StringBuilder(Integer.toHexString(currentByte)); + currentByteBits = + new StringBuilder(Integer.toHexString(currentByte)); // Add zero padding while (currentByteBits.length() < 2) { @@ -253,7 +2416,12 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { } // replace bytes in original string - rBytes = new StringBuilder(rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2)); + rBytes = + new StringBuilder( + rBytes.substring(0, i * 2) + + currentByteBits + + rBytes.substring((i + 1) * 2) + ); } // t = new BigInteger(rBytes, 16); @@ -279,26 +2447,32 @@ public static BigInteger[] keyExpansion(BigInteger initialKey) { new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), - new BigInteger("0"),}; + new BigInteger("0"), + }; // initialize rcon iteration int rconCounter = 1; for (int i = 1; i < 11; i++) { - // get the previous 32 bits the key - BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); + BigInteger t = + roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); // split previous key into 8-bit segments BigInteger[] prevKey = { roundKeys[i - 1].remainder(new BigInteger("100000000", 16)), - roundKeys[i - 1] - .remainder(new BigInteger("10000000000000000", 16)) - .divide(new BigInteger("100000000", 16)), - roundKeys[i - 1] - .remainder(new BigInteger("1000000000000000000000000", 16)) - .divide(new BigInteger("10000000000000000", 16)), - roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),}; + roundKeys[i - 1].remainder( + new BigInteger("10000000000000000", 16) + ) + .divide(new BigInteger("100000000", 16)), + roundKeys[i - 1].remainder( + new BigInteger("1000000000000000000000000", 16) + ) + .divide(new BigInteger("10000000000000000", 16)), + roundKeys[i - 1].divide( + new BigInteger("1000000000000000000000000", 16) + ), + }; // run schedule core t = scheduleCore(t, rconCounter); @@ -326,7 +2500,6 @@ public static BigInteger[] keyExpansion(BigInteger initialKey) { * @return array of 8-bit integers */ public static int[] splitBlockIntoCells(BigInteger block) { - int[] cells = new int[16]; StringBuilder blockBits = new StringBuilder(block.toString(2)); @@ -352,10 +2525,11 @@ public static int[] splitBlockIntoCells(BigInteger block) { * @return block of merged cells */ public static BigInteger mergeCellsIntoBlock(int[] cells) { - StringBuilder blockBits = new StringBuilder(); for (int i = 0; i < 16; i++) { - StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i])); + StringBuilder cellBits = new StringBuilder( + Integer.toBinaryString(cells[i]) + ); // Append leading 0 for full "8-bit" strings while (cellBits.length() < 8) { @@ -371,7 +2545,10 @@ public static BigInteger mergeCellsIntoBlock(int[] cells) { /** * @return ciphertext XOR key */ - public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { + public static BigInteger addRoundKey( + BigInteger ciphertext, + BigInteger key + ) { return ciphertext.xor(key); } @@ -382,7 +2559,6 @@ public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { * @return subtraction Output */ public static BigInteger subBytes(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); for (int i = 0; i < 16; i++) { @@ -399,7 +2575,6 @@ public static BigInteger subBytes(BigInteger ciphertext) { * @return subtraction Output */ public static BigInteger subBytesDec(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); for (int i = 0; i < 16; i++) { @@ -483,17 +2658,25 @@ public static BigInteger shiftRowsDec(BigInteger ciphertext) { * Applies the Rijndael MixColumns to the input and returns the result. */ public static BigInteger mixColumns(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); int[] outputCells = new int[16]; for (int i = 0; i < 4; i++) { - int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]}; - - outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; - outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; - outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; - outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; + int[] row = { + cells[i * 4], + cells[i * 4 + 1], + cells[i * 4 + 2], + cells[i * 4 + 3], + }; + + outputCells[i * 4] = + MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; + outputCells[i * 4 + 1] = + row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; + outputCells[i * 4 + 2] = + row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; + outputCells[i * 4 + 3] = + MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; } return mergeCellsIntoBlock(outputCells); } @@ -503,17 +2686,37 @@ public static BigInteger mixColumns(BigInteger ciphertext) { * returns the result. */ public static BigInteger mixColumnsDec(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); int[] outputCells = new int[16]; for (int i = 0; i < 4; i++) { - int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]}; - - outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]]; - outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]]; - outputCells[i * 4 + 2] = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]]; - outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]]; + int[] row = { + cells[i * 4], + cells[i * 4 + 1], + cells[i * 4 + 2], + cells[i * 4 + 3], + }; + + outputCells[i * 4] = + MULT14[row[0]] ^ + MULT11[row[1]] ^ + MULT13[row[2]] ^ + MULT9[row[3]]; + outputCells[i * 4 + 1] = + MULT9[row[0]] ^ + MULT14[row[1]] ^ + MULT11[row[2]] ^ + MULT13[row[3]]; + outputCells[i * 4 + 2] = + MULT13[row[0]] ^ + MULT9[row[1]] ^ + MULT14[row[2]] ^ + MULT11[row[3]]; + outputCells[i * 4 + 3] = + MULT11[row[0]] ^ + MULT13[row[1]] ^ + MULT9[row[2]] ^ + MULT14[row[3]]; } return mergeCellsIntoBlock(outputCells); } @@ -554,7 +2757,6 @@ public static BigInteger encrypt(BigInteger plainText, BigInteger key) { * @return decryptedText */ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { - BigInteger[] roundKeys = keyExpansion(key); // Invert final round @@ -577,34 +2779,46 @@ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { } public static void main(String[] args) { - try (Scanner input = new Scanner(System.in)) { - System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :"); + System.out.println( + "Enter (e) letter for encrpyt or (d) letter for decrypt :" + ); char choice = input.nextLine().charAt(0); String in; switch (choice) { case 'E', 'e' -> { - System.out.println("Choose a plaintext block (128-Bit Integer in base 16):"); + System.out.println( + "Choose a plaintext block (128-Bit Integer in base 16):" + ); in = input.nextLine(); BigInteger plaintext = new BigInteger(in, 16); - System.out.println("Choose a Key (128-Bit Integer in base 16):"); + System.out.println( + "Choose a Key (128-Bit Integer in base 16):" + ); in = input.nextLine(); BigInteger encryptionKey = new BigInteger(in, 16); System.out.println( - "The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); + "The encrypted message is: \n" + + encrypt(plaintext, encryptionKey).toString(16) + ); } case 'D', 'd' -> { - System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):"); + System.out.println( + "Enter your ciphertext block (128-Bit Integer in base 16):" + ); in = input.nextLine(); BigInteger ciphertext = new BigInteger(in, 16); - System.out.println("Choose a Key (128-Bit Integer in base 16):"); + System.out.println( + "Choose a Key (128-Bit Integer in base 16):" + ); in = input.nextLine(); BigInteger decryptionKey = new BigInteger(in, 16); System.out.println( - "The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); + "The deciphered message is:\n" + + decrypt(ciphertext, decryptionKey).toString(16) + ); } - default -> - System.out.println("** End **"); + default -> System.out.println("** End **"); } } } diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index 81fa79cc90f4..b8fa9081531c 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -1,8 +1,8 @@ package com.thealgorithms.ciphers; -import javax.crypto.*; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import javax.crypto.*; /** * This example program shows how AES encryption and decryption can be done in @@ -26,8 +26,12 @@ public static void main(String[] args) throws Exception { String decryptedText = decryptText(cipherText, secKey); System.out.println("Original Text:" + plainText); - System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); - System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); + System.out.println( + "AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()) + ); + System.out.println( + "Encrypted Text (Hex Form):" + bytesToHex(cipherText) + ); System.out.println("Descrypted Text:" + decryptedText); } @@ -38,7 +42,8 @@ public static void main(String[] args) throws Exception { * @return secKey (Secret key that we encrypt using it) * @throws NoSuchAlgorithmException (from KeyGenrator) */ - public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { + public static SecretKey getSecretEncryptionKey() + throws NoSuchAlgorithmException { KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); aesKeyGenerator.init(128); // The AES key size in number of bits return aesKeyGenerator.generateKey(); @@ -55,8 +60,7 @@ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException * @throws IllegalBlockSizeException (from Cipher) */ public static byte[] encryptText(String plainText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, - IllegalBlockSizeException, BadPaddingException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); @@ -69,8 +73,7 @@ public static byte[] encryptText(String plainText, SecretKey secKey) * @return plainText */ public static String decryptText(byte[] byteCipherText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, - IllegalBlockSizeException, BadPaddingException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.DECRYPT_MODE, secKey); diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java index d08c50533fd7..a6fe0ab9290f 100644 --- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java @@ -15,10 +15,9 @@ static String encryptMessage(char[] msg) { {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { - cipher = cipher - + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); - } else // else simply append space character - { + cipher = + cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); + } else { // else simply append space character cipher += msg[i]; } } @@ -46,10 +45,12 @@ static String decryptCipher(String cipher) { {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher.charAt(i) != ' ') { - msg = msg + (char) (((a_inv - * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); - } else //else simply append space character - { + msg = + msg + + (char) ( + ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A' + ); + } else { //else simply append space character msg += cipher.charAt(i); } } @@ -66,7 +67,8 @@ public static void main(String[] args) { System.out.println("Encrypted Message is : " + cipherText); // Calling Decryption function - System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); - + System.out.println( + "Decrypted Message is: " + decryptCipher(cipherText) + ); } } diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index f855956f35cd..7e74cc6dab3e 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -1,235 +1,1075 @@ package com.thealgorithms.ciphers; /* - * Java program for Blowfish Algorithm + * Java program for Blowfish Algorithm * Wikipedia: https://en.wikipedia.org/wiki/Blowfish_(cipher) - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class Blowfish { - - //Initializing substitution boxes - String S[][] - = { { "d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed", - "6a267e96", "ba7c9045", "f12c7f99", "24a19947", "b3916cf7", - "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3", - "f4933d7e", "0d95748f", "728eb658", "718bcd58", "82154aee", - "7b54a41d", "c25a59b5", "9c30d539", "2af26013", "c5d1b023", - "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e", - "6c9e0e8b", "b01e8a3e", "d71577c1", "bd314b27", "78af2fda", - "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440", - "55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af", - "7c72e993", "b3ee1411", "636fbc2a", "2ba9c55d", "741831f6", - "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381", - "28958677", "3b8f4898", "6b4bb9af", "c4bfe81b", "66282193", - "61d809cc", "fb21a991", "487cac60", "5dec8032", "ef845d5d", - "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5", - "0f6d6ff3", "83f44239", "2e0b4482", "a4842004", "69c8f04a", - "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0", - "6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c", - "137a3be4", "ba3bf050", "7efb2a98", "a1f1651d", "39af0176", - "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3", - "3b8b5ebe", "e06f75d8", "85c12073", "401a449f", "56c16aa6", - "4ed3aa62", "363f7706", "1bfedf72", "429b023d", "37d0d724", - "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b", - "25d479d8", "f6e8def7", "e3fe501a", "b6794c3b", "976ce0bd", - "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463", - "68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f", - "9b30952c", "cc814544", "af5ebd09", "bee3d004", "de334afd", - "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39", - "b9d3fbdb", "5579c0bd", "1a60320a", "d6a100c6", "402c7279", - "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8", "3c7516df", - "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760", - "53317b48", "3e00df82", "9e5c57bb", "ca6f8ca0", "1a87562e", - "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573", - "695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98", - "fd2183b8", "4afcb56c", "2dd1d35b", "9a53e479", "b6f84565", - "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341", - "cee4c6e8", "ef20cada", "36774c01", "d07e9efe", "2bf11fb4", - "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0", "d08ed1d0", - "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64", - "8888b812", "900df01c", "4fad5ea0", "688fc31c", "d1cff191", - "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1", - "e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0", - "fd13e0b7", "7cc43b81", "d2ada8d9", "165fa266", "80957705", - "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5", - "fb9d35cf", "ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49", - "00250e2d", "2071b35e", "226800bb", "57b8e0af", "2464369b", - "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f", - "207d5ba2", "02e5b9c5", "83260376", "6295cfa9", "11c81968", - "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915", - "d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5", - "571be91f", "f296ec6b", "2a0dd915", "b6636521", "e7b9f9b6", - "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799", - "6e85076a" }, - { "4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0", - "49a7df7d", "9cee60b8", "8fedb266", "ecaa8c71", "699a17ff", - "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340", - "e4183a3e", "3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6", - "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1", "4cdd2086", - "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9", - "3c971814", "6b6a70a1", "687f3584", "52a0e286", "b79c5305", - "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8", - "b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a", - "3cb574b2", "25837a58", "dc0921bd", "d19113f9", "7ca92ff6", - "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634", - "9af3dda7", "a9446146", "0fd0030e", "ecc8c73e", "a4751e41", - "e238cd99", "3bea0e2f", "3280bba1", "183eb331", "4e548b38", - "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79", - "5679b072", "bcaf89af", "de9a771f", "d9930810", "b38bae12", - "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87", - "7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a", - "db851dfa", "63094366", "c464c3d2", "ef1c1847", "3215d908", - "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002", - "133ae4dd", "71dff89e", "10314e55", "81ac77d6", "5f11199b", - "043556f1", "d7a3c76b", "3c11183b", "5924a509", "f28fe6ed", - "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1", - "860e5e0a", "5a3e2ab3", "771fe71c", "4e3d06fa", "2965dcb9", - "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a", - "c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7", - "361d2b3d", "1939260f", "19c27960", "5223a708", "f71312b6", - "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1", - "018cff28", "c332ddef", "be6c5aa5", "65582185", "68ab9802", - "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84", "1521b628", - "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96", - "0334fe1e", "aa0363cf", "b5735c90", "4c70a239", "d59e9e0b", - "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e", - "648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32", - "3c2ab4b3", "319ee9d5", "c021b8f7", "9b540b19", "875fa099", - "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f", - "16681281", "0e358829", "c7e61fd6", "96dedfa1", "7858ba99", - "57f584a5", "1b227263", "9b83c3ff", "1ac24696", "cdb30aeb", - "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea", - "fe28ed61", "ee7c3c73", "5d4a14d9", "e864b7e3", "42105d14", - "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0", - "c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e", - "86854dc7", "e44b476a", "3d816250", "cf62a1f2", "5b8d2646", - "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b", - "5692b285", "095bbf00", "ad19489d", "1462b174", "23820e00", - "58428d2a", "0c55f5ea", "1dadf43e", "233f7061", "3372f092", - "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460", - "4085f2a7", "ce77326e", "a6078084", "19f8509e", "e8efd855", - "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc", - "9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3", - "105588cd", "675fda79", "e3674340", "c5c43465", "713e38d8", - "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b", - "db83adf7" }, - { "e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7", - "7602d4f7", "bcf46b2e", "d4a20068", "d4082471", "3320f46a", - "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74", - "bf8b8840", "4d95fc1d", "96b591af", "70f4ddd3", "66a02f45", - "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504", "96eb27b3", - "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4", - "0a2c86da", "e9b66dfb", "68dc1462", "d7486900", "680ec0a4", - "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6", - "aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35", - "d9f385b9", "ee39d7ab", "3b124e8b", "1dc9faf7", "4b6d1856", - "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7", - "ca7820fb", "fb0af54e", "d8feb397", "454056ac", "ba489527", - "55533a3a", "20838d87", "fe6ba9b7", "d096954b", "55a867bc", - "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9", - "5ef47e1c", "9029317c", "fdf8e802", "04272f70", "80bb155c", - "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc", - "07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb", - "d59bc0d1", "f2bcc18f", "41113564", "257b7834", "602a9c60", - "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1", - "cad18115", "6b2395e0", "333e92e1", "3b240b62", "eebeb922", - "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728", "d0127845", - "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa", - "c39dfd27", "f33e8d1e", "0a476341", "992eff74", "3a6f6eab", - "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d", - "c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7", - "cc00ffa3", "b5390f92", "690fed0b", "667b9ffb", "cedb7d9c", - "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf", - "763bd6eb", "37392eb3", "cc115979", "8026e297", "f42e312d", - "6842ada7", "c66a2b3b", "12754ccc", "782ef11c", "6a124237", - "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa", - "3d25bdd8", "e2e1c3c9", "44421659", "0a121386", "d90cec6e", - "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe", - "9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346", - "f6381fb0", "7745ae04", "d736fccc", "83426b33", "f01eab71", - "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299", - "bf582e61", "4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2", - "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9", "7aeb2661", - "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770", - "8cd55591", "c902de4c", "b90bace1", "bb8205d0", "11a86248", - "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633", - "e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d", - "0ba5a4df", "a186f20f", "2868f169", "dcb7da83", "573906fe", - "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4", - "0de6d027", "9af88c27", "773f8641", "c3604c06", "61a806b5", - "f0177a28", "c0f586e0", "006058aa", "30dc7d62", "11e69ed7", - "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de", - "ebfc7da1", "ce591d76", "6f05e409", "4b7c0188", "39720a3d", - "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc", - "ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e", - "b161e6f8", "a28514d9", "6c51133c", "6fd5c7e7", "56e14ec4", - "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e", - "406000e0" }, - { "3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e", - "4fa33742", "d3822740", "99bc9bbe", "d5118e9d", "bf0f7315", - "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be", - "6a366eb4", "5748ab2f", "bc946e79", "c6a376d2", "6549c2c8", - "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6", "2939bbdb", - "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a", - "63ef8ce2", "9a86ee22", "c089c2b8", "43242ef6", "a51e03aa", - "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6", - "2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3", - "f752f7da", "3f046f69", "77fa0a59", "80e4a915", "87b08601", - "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9", - "022b8b51", "96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28", - "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c", "e029ac71", - "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc", - "f8d56629", "79132e28", "785f0191", "ed756055", "f7960e44", - "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd", - "c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b", - "1e6321f5", "f59c66fb", "26dcf319", "7533d928", "b155fdf5", - "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167", - "ccad925f", "4de81751", "3830dc8e", "379d5862", "9320f991", - "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32", "a8b6e37e", - "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224", - "69852dfd", "09072166", "b39a460a", "6445c0dd", "586cdecf", - "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb", - "dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8", - "fa6484bb", "8d6612ae", "bf3c6f47", "d29be463", "542f5d9e", - "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671", - "af537d5d", "4040cb08", "4eb4e2cc", "34d2466a", "0115af84", - "e1b00428", "95983a1d", "06b89fb4", "ce6ea048", "6f3f3b82", - "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc", - "bb3a792b", "344525bd", "a08839e1", "51ce794b", "2f32c9b7", - "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7", - "1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a", - "c6913667", "8df9317c", "e0b12b4f", "f79e59b7", "43f5bb3a", - "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71", - "9b941525", "fae59361", "ceb69ceb", "c2a86459", "12baa8d1", - "b6c1075e", "e3056a0c", "10d25065", "cb03a442", "e0ec6e0e", - "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df", - "d3a0342b", "8971f21e", "1b0a7441", "4ba3348c", "c5be7120", - "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d", - "e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166", - "fd2c1d05", "848fd2c5", "f6fb2299", "f523f357", "a6327623", - "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697", - "88d273cc", "de966292", "81b949d0", "4c50901b", "71c65614", - "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a", "c9aa53fd", - "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222", - "b6cbcf7c", "cd769c2b", "53113ec0", "1640e3d3", "38abbd60", - "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060", - "85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c", - "02fb8a8c", "01c36ae4", "d6ebe1f9", "90d4f869", "a65cdea0", - "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3", - "3ac372e6" } }; - //Initializing subkeys with digits of pi - String P[] = { "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", - "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377", - "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", - "b5470917", "9216d5d9", "8979fb1b" }; + //Initializing substitution boxes + String S[][] = { + { + "d1310ba6", + "98dfb5ac", + "2ffd72db", + "d01adfb7", + "b8e1afed", + "6a267e96", + "ba7c9045", + "f12c7f99", + "24a19947", + "b3916cf7", + "0801f2e2", + "858efc16", + "636920d8", + "71574e69", + "a458fea3", + "f4933d7e", + "0d95748f", + "728eb658", + "718bcd58", + "82154aee", + "7b54a41d", + "c25a59b5", + "9c30d539", + "2af26013", + "c5d1b023", + "286085f0", + "ca417918", + "b8db38ef", + "8e79dcb0", + "603a180e", + "6c9e0e8b", + "b01e8a3e", + "d71577c1", + "bd314b27", + "78af2fda", + "55605c60", + "e65525f3", + "aa55ab94", + "57489862", + "63e81440", + "55ca396a", + "2aab10b6", + "b4cc5c34", + "1141e8ce", + "a15486af", + "7c72e993", + "b3ee1411", + "636fbc2a", + "2ba9c55d", + "741831f6", + "ce5c3e16", + "9b87931e", + "afd6ba33", + "6c24cf5c", + "7a325381", + "28958677", + "3b8f4898", + "6b4bb9af", + "c4bfe81b", + "66282193", + "61d809cc", + "fb21a991", + "487cac60", + "5dec8032", + "ef845d5d", + "e98575b1", + "dc262302", + "eb651b88", + "23893e81", + "d396acc5", + "0f6d6ff3", + "83f44239", + "2e0b4482", + "a4842004", + "69c8f04a", + "9e1f9b5e", + "21c66842", + "f6e96c9a", + "670c9c61", + "abd388f0", + "6a51a0d2", + "d8542f68", + "960fa728", + "ab5133a3", + "6eef0b6c", + "137a3be4", + "ba3bf050", + "7efb2a98", + "a1f1651d", + "39af0176", + "66ca593e", + "82430e88", + "8cee8619", + "456f9fb4", + "7d84a5c3", + "3b8b5ebe", + "e06f75d8", + "85c12073", + "401a449f", + "56c16aa6", + "4ed3aa62", + "363f7706", + "1bfedf72", + "429b023d", + "37d0d724", + "d00a1248", + "db0fead3", + "49f1c09b", + "075372c9", + "80991b7b", + "25d479d8", + "f6e8def7", + "e3fe501a", + "b6794c3b", + "976ce0bd", + "04c006ba", + "c1a94fb6", + "409f60c4", + "5e5c9ec2", + "196a2463", + "68fb6faf", + "3e6c53b5", + "1339b2eb", + "3b52ec6f", + "6dfc511f", + "9b30952c", + "cc814544", + "af5ebd09", + "bee3d004", + "de334afd", + "660f2807", + "192e4bb3", + "c0cba857", + "45c8740f", + "d20b5f39", + "b9d3fbdb", + "5579c0bd", + "1a60320a", + "d6a100c6", + "402c7279", + "679f25fe", + "fb1fa3cc", + "8ea5e9f8", + "db3222f8", + "3c7516df", + "fd616b15", + "2f501ec8", + "ad0552ab", + "323db5fa", + "fd238760", + "53317b48", + "3e00df82", + "9e5c57bb", + "ca6f8ca0", + "1a87562e", + "df1769db", + "d542a8f6", + "287effc3", + "ac6732c6", + "8c4f5573", + "695b27b0", + "bbca58c8", + "e1ffa35d", + "b8f011a0", + "10fa3d98", + "fd2183b8", + "4afcb56c", + "2dd1d35b", + "9a53e479", + "b6f84565", + "d28e49bc", + "4bfb9790", + "e1ddf2da", + "a4cb7e33", + "62fb1341", + "cee4c6e8", + "ef20cada", + "36774c01", + "d07e9efe", + "2bf11fb4", + "95dbda4d", + "ae909198", + "eaad8e71", + "6b93d5a0", + "d08ed1d0", + "afc725e0", + "8e3c5b2f", + "8e7594b7", + "8ff6e2fb", + "f2122b64", + "8888b812", + "900df01c", + "4fad5ea0", + "688fc31c", + "d1cff191", + "b3a8c1ad", + "2f2f2218", + "be0e1777", + "ea752dfe", + "8b021fa1", + "e5a0cc0f", + "b56f74e8", + "18acf3d6", + "ce89e299", + "b4a84fe0", + "fd13e0b7", + "7cc43b81", + "d2ada8d9", + "165fa266", + "80957705", + "93cc7314", + "211a1477", + "e6ad2065", + "77b5fa86", + "c75442f5", + "fb9d35cf", + "ebcdaf0c", + "7b3e89a0", + "d6411bd3", + "ae1e7e49", + "00250e2d", + "2071b35e", + "226800bb", + "57b8e0af", + "2464369b", + "f009b91e", + "5563911d", + "59dfa6aa", + "78c14389", + "d95a537f", + "207d5ba2", + "02e5b9c5", + "83260376", + "6295cfa9", + "11c81968", + "4e734a41", + "b3472dca", + "7b14a94a", + "1b510052", + "9a532915", + "d60f573f", + "bc9bc6e4", + "2b60a476", + "81e67400", + "08ba6fb5", + "571be91f", + "f296ec6b", + "2a0dd915", + "b6636521", + "e7b9f9b6", + "ff34052e", + "c5855664", + "53b02d5d", + "a99f8fa1", + "08ba4799", + "6e85076a", + }, + { + "4b7a70e9", + "b5b32944", + "db75092e", + "c4192623", + "ad6ea6b0", + "49a7df7d", + "9cee60b8", + "8fedb266", + "ecaa8c71", + "699a17ff", + "5664526c", + "c2b19ee1", + "193602a5", + "75094c29", + "a0591340", + "e4183a3e", + "3f54989a", + "5b429d65", + "6b8fe4d6", + "99f73fd6", + "a1d29c07", + "efe830f5", + "4d2d38e6", + "f0255dc1", + "4cdd2086", + "8470eb26", + "6382e9c6", + "021ecc5e", + "09686b3f", + "3ebaefc9", + "3c971814", + "6b6a70a1", + "687f3584", + "52a0e286", + "b79c5305", + "aa500737", + "3e07841c", + "7fdeae5c", + "8e7d44ec", + "5716f2b8", + "b03ada37", + "f0500c0d", + "f01c1f04", + "0200b3ff", + "ae0cf51a", + "3cb574b2", + "25837a58", + "dc0921bd", + "d19113f9", + "7ca92ff6", + "94324773", + "22f54701", + "3ae5e581", + "37c2dadc", + "c8b57634", + "9af3dda7", + "a9446146", + "0fd0030e", + "ecc8c73e", + "a4751e41", + "e238cd99", + "3bea0e2f", + "3280bba1", + "183eb331", + "4e548b38", + "4f6db908", + "6f420d03", + "f60a04bf", + "2cb81290", + "24977c79", + "5679b072", + "bcaf89af", + "de9a771f", + "d9930810", + "b38bae12", + "dccf3f2e", + "5512721f", + "2e6b7124", + "501adde6", + "9f84cd87", + "7a584718", + "7408da17", + "bc9f9abc", + "e94b7d8c", + "ec7aec3a", + "db851dfa", + "63094366", + "c464c3d2", + "ef1c1847", + "3215d908", + "dd433b37", + "24c2ba16", + "12a14d43", + "2a65c451", + "50940002", + "133ae4dd", + "71dff89e", + "10314e55", + "81ac77d6", + "5f11199b", + "043556f1", + "d7a3c76b", + "3c11183b", + "5924a509", + "f28fe6ed", + "97f1fbfa", + "9ebabf2c", + "1e153c6e", + "86e34570", + "eae96fb1", + "860e5e0a", + "5a3e2ab3", + "771fe71c", + "4e3d06fa", + "2965dcb9", + "99e71d0f", + "803e89d6", + "5266c825", + "2e4cc978", + "9c10b36a", + "c6150eba", + "94e2ea78", + "a5fc3c53", + "1e0a2df4", + "f2f74ea7", + "361d2b3d", + "1939260f", + "19c27960", + "5223a708", + "f71312b6", + "ebadfe6e", + "eac31f66", + "e3bc4595", + "a67bc883", + "b17f37d1", + "018cff28", + "c332ddef", + "be6c5aa5", + "65582185", + "68ab9802", + "eecea50f", + "db2f953b", + "2aef7dad", + "5b6e2f84", + "1521b628", + "29076170", + "ecdd4775", + "619f1510", + "13cca830", + "eb61bd96", + "0334fe1e", + "aa0363cf", + "b5735c90", + "4c70a239", + "d59e9e0b", + "cbaade14", + "eecc86bc", + "60622ca7", + "9cab5cab", + "b2f3846e", + "648b1eaf", + "19bdf0ca", + "a02369b9", + "655abb50", + "40685a32", + "3c2ab4b3", + "319ee9d5", + "c021b8f7", + "9b540b19", + "875fa099", + "95f7997e", + "623d7da8", + "f837889a", + "97e32d77", + "11ed935f", + "16681281", + "0e358829", + "c7e61fd6", + "96dedfa1", + "7858ba99", + "57f584a5", + "1b227263", + "9b83c3ff", + "1ac24696", + "cdb30aeb", + "532e3054", + "8fd948e4", + "6dbc3128", + "58ebf2ef", + "34c6ffea", + "fe28ed61", + "ee7c3c73", + "5d4a14d9", + "e864b7e3", + "42105d14", + "203e13e0", + "45eee2b6", + "a3aaabea", + "db6c4f15", + "facb4fd0", + "c742f442", + "ef6abbb5", + "654f3b1d", + "41cd2105", + "d81e799e", + "86854dc7", + "e44b476a", + "3d816250", + "cf62a1f2", + "5b8d2646", + "fc8883a0", + "c1c7b6a3", + "7f1524c3", + "69cb7492", + "47848a0b", + "5692b285", + "095bbf00", + "ad19489d", + "1462b174", + "23820e00", + "58428d2a", + "0c55f5ea", + "1dadf43e", + "233f7061", + "3372f092", + "8d937e41", + "d65fecf1", + "6c223bdb", + "7cde3759", + "cbee7460", + "4085f2a7", + "ce77326e", + "a6078084", + "19f8509e", + "e8efd855", + "61d99735", + "a969a7aa", + "c50c06c2", + "5a04abfc", + "800bcadc", + "9e447a2e", + "c3453484", + "fdd56705", + "0e1e9ec9", + "db73dbd3", + "105588cd", + "675fda79", + "e3674340", + "c5c43465", + "713e38d8", + "3d28f89e", + "f16dff20", + "153e21e7", + "8fb03d4a", + "e6e39f2b", + "db83adf7", + }, + { + "e93d5a68", + "948140f7", + "f64c261c", + "94692934", + "411520f7", + "7602d4f7", + "bcf46b2e", + "d4a20068", + "d4082471", + "3320f46a", + "43b7d4b7", + "500061af", + "1e39f62e", + "97244546", + "14214f74", + "bf8b8840", + "4d95fc1d", + "96b591af", + "70f4ddd3", + "66a02f45", + "bfbc09ec", + "03bd9785", + "7fac6dd0", + "31cb8504", + "96eb27b3", + "55fd3941", + "da2547e6", + "abca0a9a", + "28507825", + "530429f4", + "0a2c86da", + "e9b66dfb", + "68dc1462", + "d7486900", + "680ec0a4", + "27a18dee", + "4f3ffea2", + "e887ad8c", + "b58ce006", + "7af4d6b6", + "aace1e7c", + "d3375fec", + "ce78a399", + "406b2a42", + "20fe9e35", + "d9f385b9", + "ee39d7ab", + "3b124e8b", + "1dc9faf7", + "4b6d1856", + "26a36631", + "eae397b2", + "3a6efa74", + "dd5b4332", + "6841e7f7", + "ca7820fb", + "fb0af54e", + "d8feb397", + "454056ac", + "ba489527", + "55533a3a", + "20838d87", + "fe6ba9b7", + "d096954b", + "55a867bc", + "a1159a58", + "cca92963", + "99e1db33", + "a62a4a56", + "3f3125f9", + "5ef47e1c", + "9029317c", + "fdf8e802", + "04272f70", + "80bb155c", + "05282ce3", + "95c11548", + "e4c66d22", + "48c1133f", + "c70f86dc", + "07f9c9ee", + "41041f0f", + "404779a4", + "5d886e17", + "325f51eb", + "d59bc0d1", + "f2bcc18f", + "41113564", + "257b7834", + "602a9c60", + "dff8e8a3", + "1f636c1b", + "0e12b4c2", + "02e1329e", + "af664fd1", + "cad18115", + "6b2395e0", + "333e92e1", + "3b240b62", + "eebeb922", + "85b2a20e", + "e6ba0d99", + "de720c8c", + "2da2f728", + "d0127845", + "95b794fd", + "647d0862", + "e7ccf5f0", + "5449a36f", + "877d48fa", + "c39dfd27", + "f33e8d1e", + "0a476341", + "992eff74", + "3a6f6eab", + "f4f8fd37", + "a812dc60", + "a1ebddf8", + "991be14c", + "db6e6b0d", + "c67b5510", + "6d672c37", + "2765d43b", + "dcd0e804", + "f1290dc7", + "cc00ffa3", + "b5390f92", + "690fed0b", + "667b9ffb", + "cedb7d9c", + "a091cf0b", + "d9155ea3", + "bb132f88", + "515bad24", + "7b9479bf", + "763bd6eb", + "37392eb3", + "cc115979", + "8026e297", + "f42e312d", + "6842ada7", + "c66a2b3b", + "12754ccc", + "782ef11c", + "6a124237", + "b79251e7", + "06a1bbe6", + "4bfb6350", + "1a6b1018", + "11caedfa", + "3d25bdd8", + "e2e1c3c9", + "44421659", + "0a121386", + "d90cec6e", + "d5abea2a", + "64af674e", + "da86a85f", + "bebfe988", + "64e4c3fe", + "9dbc8057", + "f0f7c086", + "60787bf8", + "6003604d", + "d1fd8346", + "f6381fb0", + "7745ae04", + "d736fccc", + "83426b33", + "f01eab71", + "b0804187", + "3c005e5f", + "77a057be", + "bde8ae24", + "55464299", + "bf582e61", + "4e58f48f", + "f2ddfda2", + "f474ef38", + "8789bdc2", + "5366f9c3", + "c8b38e74", + "b475f255", + "46fcd9b9", + "7aeb2661", + "8b1ddf84", + "846a0e79", + "915f95e2", + "466e598e", + "20b45770", + "8cd55591", + "c902de4c", + "b90bace1", + "bb8205d0", + "11a86248", + "7574a99e", + "b77f19b6", + "e0a9dc09", + "662d09a1", + "c4324633", + "e85a1f02", + "09f0be8c", + "4a99a025", + "1d6efe10", + "1ab93d1d", + "0ba5a4df", + "a186f20f", + "2868f169", + "dcb7da83", + "573906fe", + "a1e2ce9b", + "4fcd7f52", + "50115e01", + "a70683fa", + "a002b5c4", + "0de6d027", + "9af88c27", + "773f8641", + "c3604c06", + "61a806b5", + "f0177a28", + "c0f586e0", + "006058aa", + "30dc7d62", + "11e69ed7", + "2338ea63", + "53c2dd94", + "c2c21634", + "bbcbee56", + "90bcb6de", + "ebfc7da1", + "ce591d76", + "6f05e409", + "4b7c0188", + "39720a3d", + "7c927c24", + "86e3725f", + "724d9db9", + "1ac15bb4", + "d39eb8fc", + "ed545578", + "08fca5b5", + "d83d7cd3", + "4dad0fc4", + "1e50ef5e", + "b161e6f8", + "a28514d9", + "6c51133c", + "6fd5c7e7", + "56e14ec4", + "362abfce", + "ddc6c837", + "d79a3234", + "92638212", + "670efa8e", + "406000e0", + }, + { + "3a39ce37", + "d3faf5cf", + "abc27737", + "5ac52d1b", + "5cb0679e", + "4fa33742", + "d3822740", + "99bc9bbe", + "d5118e9d", + "bf0f7315", + "d62d1c7e", + "c700c47b", + "b78c1b6b", + "21a19045", + "b26eb1be", + "6a366eb4", + "5748ab2f", + "bc946e79", + "c6a376d2", + "6549c2c8", + "530ff8ee", + "468dde7d", + "d5730a1d", + "4cd04dc6", + "2939bbdb", + "a9ba4650", + "ac9526e8", + "be5ee304", + "a1fad5f0", + "6a2d519a", + "63ef8ce2", + "9a86ee22", + "c089c2b8", + "43242ef6", + "a51e03aa", + "9cf2d0a4", + "83c061ba", + "9be96a4d", + "8fe51550", + "ba645bd6", + "2826a2f9", + "a73a3ae1", + "4ba99586", + "ef5562e9", + "c72fefd3", + "f752f7da", + "3f046f69", + "77fa0a59", + "80e4a915", + "87b08601", + "9b09e6ad", + "3b3ee593", + "e990fd5a", + "9e34d797", + "2cf0b7d9", + "022b8b51", + "96d5ac3a", + "017da67d", + "d1cf3ed6", + "7c7d2d28", + "1f9f25cf", + "adf2b89b", + "5ad6b472", + "5a88f54c", + "e029ac71", + "e019a5e6", + "47b0acfd", + "ed93fa9b", + "e8d3c48d", + "283b57cc", + "f8d56629", + "79132e28", + "785f0191", + "ed756055", + "f7960e44", + "e3d35e8c", + "15056dd4", + "88f46dba", + "03a16125", + "0564f0bd", + "c3eb9e15", + "3c9057a2", + "97271aec", + "a93a072a", + "1b3f6d9b", + "1e6321f5", + "f59c66fb", + "26dcf319", + "7533d928", + "b155fdf5", + "03563482", + "8aba3cbb", + "28517711", + "c20ad9f8", + "abcc5167", + "ccad925f", + "4de81751", + "3830dc8e", + "379d5862", + "9320f991", + "ea7a90c2", + "fb3e7bce", + "5121ce64", + "774fbe32", + "a8b6e37e", + "c3293d46", + "48de5369", + "6413e680", + "a2ae0810", + "dd6db224", + "69852dfd", + "09072166", + "b39a460a", + "6445c0dd", + "586cdecf", + "1c20c8ae", + "5bbef7dd", + "1b588d40", + "ccd2017f", + "6bb4e3bb", + "dda26a7e", + "3a59ff45", + "3e350a44", + "bcb4cdd5", + "72eacea8", + "fa6484bb", + "8d6612ae", + "bf3c6f47", + "d29be463", + "542f5d9e", + "aec2771b", + "f64e6370", + "740e0d8d", + "e75b1357", + "f8721671", + "af537d5d", + "4040cb08", + "4eb4e2cc", + "34d2466a", + "0115af84", + "e1b00428", + "95983a1d", + "06b89fb4", + "ce6ea048", + "6f3f3b82", + "3520ab82", + "011a1d4b", + "277227f8", + "611560b1", + "e7933fdc", + "bb3a792b", + "344525bd", + "a08839e1", + "51ce794b", + "2f32c9b7", + "a01fbac9", + "e01cc87e", + "bcc7d1f6", + "cf0111c3", + "a1e8aac7", + "1a908749", + "d44fbd9a", + "d0dadecb", + "d50ada38", + "0339c32a", + "c6913667", + "8df9317c", + "e0b12b4f", + "f79e59b7", + "43f5bb3a", + "f2d519ff", + "27d9459c", + "bf97222c", + "15e6fc2a", + "0f91fc71", + "9b941525", + "fae59361", + "ceb69ceb", + "c2a86459", + "12baa8d1", + "b6c1075e", + "e3056a0c", + "10d25065", + "cb03a442", + "e0ec6e0e", + "1698db3b", + "4c98a0be", + "3278e964", + "9f1f9532", + "e0d392df", + "d3a0342b", + "8971f21e", + "1b0a7441", + "4ba3348c", + "c5be7120", + "c37632d8", + "df359f8d", + "9b992f2e", + "e60b6f47", + "0fe3f11d", + "e54cda54", + "1edad891", + "ce6279cf", + "cd3e7e6f", + "1618b166", + "fd2c1d05", + "848fd2c5", + "f6fb2299", + "f523f357", + "a6327623", + "93a83531", + "56cccd02", + "acf08162", + "5a75ebb5", + "6e163697", + "88d273cc", + "de966292", + "81b949d0", + "4c50901b", + "71c65614", + "e6c6c7bd", + "327a140a", + "45e1d006", + "c3f27b9a", + "c9aa53fd", + "62a80f00", + "bb25bfe2", + "35bdd2f6", + "71126905", + "b2040222", + "b6cbcf7c", + "cd769c2b", + "53113ec0", + "1640e3d3", + "38abbd60", + "2547adf0", + "ba38209c", + "f746ce76", + "77afa1c5", + "20756060", + "85cbfe4e", + "8ae88dd8", + "7aaaf9b0", + "4cf9aa7e", + "1948c25c", + "02fb8a8c", + "01c36ae4", + "d6ebe1f9", + "90d4f869", + "a65cdea0", + "3f09252d", + "c208e69f", + "b74e6132", + "ce77e25b", + "578fdfe3", + "3ac372e6", + }, + }; - //Initializing modVal to 2^32 - long modVal = 4294967296L; - + //Initializing subkeys with digits of pi + String P[] = { + "243f6a88", + "85a308d3", + "13198a2e", + "03707344", + "a4093822", + "299f31d0", + "082efa98", + "ec4e6c89", + "452821e6", + "38d01377", + "be5466cf", + "34e90c6c", + "c0ac29b7", + "c97c50dd", + "3f84d5b5", + "b5470917", + "9216d5d9", + "8979fb1b", + }; + + //Initializing modVal to 2^32 + long modVal = 4294967296L; /** * This method returns binary representation of the hexadecimal number passed as parameter @@ -237,25 +1077,22 @@ public class Blowfish { * @param hex Number for which binary representation is required * @return String object which is a binary representation of the hex number passed as parameter */ - private String hexToBin(String hex) - { - String binary = ""; - Long num; - String binary4B; - int n = hex.length(); - for (int i = 0; i < n; i++) { - - num = Long.parseUnsignedLong( - hex.charAt(i) + "", 16); - binary4B = Long.toBinaryString(num); + private String hexToBin(String hex) { + String binary = ""; + Long num; + String binary4B; + int n = hex.length(); + for (int i = 0; i < n; i++) { + num = Long.parseUnsignedLong(hex.charAt(i) + "", 16); + binary4B = Long.toBinaryString(num); - binary4B = "0000" + binary4B; + binary4B = "0000" + binary4B; - binary4B = binary4B.substring(binary4B.length() - 4); - binary += binary4B; - } - return binary; - } + binary4B = binary4B.substring(binary4B.length() - 4); + binary += binary4B; + } + return binary; + } /** * This method returns hexadecimal representation of the binary number passed as parameter @@ -263,107 +1100,94 @@ private String hexToBin(String hex) * @param binary Number for which hexadecimal representation is required * @return String object which is a hexadecimal representation of the binary number passed as parameter */ - private String binToHex(String binary) - { + private String binToHex(String binary) { + long num = Long.parseUnsignedLong(binary, 2); + String hex = Long.toHexString(num); + while (hex.length() < (binary.length() / 4)) hex = "0" + hex; - long num = Long.parseUnsignedLong(binary, 2); - String hex = Long.toHexString(num); - while (hex.length() < (binary.length() / 4)) - hex = "0" + hex; - - return hex; - } + return hex; + } /** * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters - * + * * @param String a and b are string objects which will be XORed and are to be of same length * @return String object obtained by XOR operation on String a and String b * */ - private String xor(String a, String b) - { - a = hexToBin(a); - b = hexToBin(b); - String ans = ""; - for (int i = 0; i < a.length(); i++) - ans += (char)(((a.charAt(i) - '0') - ^ (b.charAt(i) - '0')) - + '0'); - ans = binToHex(ans); - return ans; - } + private String xor(String a, String b) { + a = hexToBin(a); + b = hexToBin(b); + String ans = ""; + for (int i = 0; i < a.length(); i++) ans += + (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); + ans = binToHex(ans); + return ans; + } /** - * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32 + * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32 * * @param String a and b are hexadecimal numbers * @return String object which is a is addition that is then moded with 2^32 of hex numbers passed as parameters */ - private String addBin(String a, String b) - { - String ans = ""; - long n1 = Long.parseUnsignedLong(a, 16); - long n2 = Long.parseUnsignedLong(b, 16); - n1 = (n1 + n2) % modVal; - ans = Long.toHexString(n1); - ans = "00000000" + ans; - return ans.substring(ans.length() - 8); - } + private String addBin(String a, String b) { + String ans = ""; + long n1 = Long.parseUnsignedLong(a, 16); + long n2 = Long.parseUnsignedLong(b, 16); + n1 = (n1 + n2) % modVal; + ans = Long.toHexString(n1); + ans = "00000000" + ans; + return ans.substring(ans.length() - 8); + } - /*F-function splits the 32-bit input into four 8-bit quarters + /*F-function splits the 32-bit input into four 8-bit quarters and uses the quarters as input to the S-boxes. The S-boxes accept 8-bit input and produce 32-bit output. The outputs are added modulo 232 and XORed to produce the final 32-bit output */ - private String f(String plainText) - { - String a[] = new String[4]; - String ans = ""; - for (int i = 0; i < 8; i += 2) { - //column number for S-box is a 8-bit value - long col - = Long.parseUnsignedLong( - hexToBin( - plainText - .substring(i, i + 2)), - 2); - a[i / 2] = S[i / 2][(int)col]; - } - ans = addBin(a[0], a[1]); - ans = xor(ans, a[2]); - ans = addBin(ans, a[3]); - return ans; - } - - //generate subkeys - private void keyGenerate(String key) - { - int j = 0; - for (int i = 0; i < P.length; i++) { + private String f(String plainText) { + String a[] = new String[4]; + String ans = ""; + for (int i = 0; i < 8; i += 2) { + //column number for S-box is a 8-bit value + long col = Long.parseUnsignedLong( + hexToBin(plainText.substring(i, i + 2)), + 2 + ); + a[i / 2] = S[i / 2][(int) col]; + } + ans = addBin(a[0], a[1]); + ans = xor(ans, a[2]); + ans = addBin(ans, a[3]); + return ans; + } - //XOR-ing 32-bit parts of the key with initial subkeys - P[i] = xor(P[i], key.substring(j, j + 8)); + //generate subkeys + private void keyGenerate(String key) { + int j = 0; + for (int i = 0; i < P.length; i++) { + //XOR-ing 32-bit parts of the key with initial subkeys + P[i] = xor(P[i], key.substring(j, j + 8)); - j = (j + 8) % key.length(); - } - } + j = (j + 8) % key.length(); + } + } - //round function - private String round(int time, String plainText) - { - String left, right; - left = plainText.substring(0, 8); - right = plainText.substring(8, 16); - left = xor(left, P[time]); + //round function + private String round(int time, String plainText) { + String left, right; + left = plainText.substring(0, 8); + right = plainText.substring(8, 16); + left = xor(left, P[time]); - //output from F function - String fOut = f(left); + //output from F function + String fOut = f(left); - right = xor(fOut, right); + right = xor(fOut, right); - //swap left and right - return right + left; - } + //swap left and right + return right + left; + } /** * This method returns cipher text for the plaintext passed as the first parameter generated @@ -373,22 +1197,20 @@ private String round(int time, String plainText) * @param String key is the key which is to be used for generating cipher text * @return String cipherText is the encrypted value */ - String encrypt(String plainText, String key) - { - //generating key - keyGenerate(key); - - for (int i = 0; i < 16; i++) - plainText = round(i, plainText); + String encrypt(String plainText, String key) { + //generating key + keyGenerate(key); + + for (int i = 0; i < 16; i++) plainText = round(i, plainText); + + //postprocessing + String right = plainText.substring(0, 8); + String left = plainText.substring(8, 16); + right = xor(right, P[16]); + left = xor(left, P[17]); + return left + right; + } - //postprocessing - String right = plainText.substring(0, 8); - String left = plainText.substring(8, 16); - right = xor(right, P[16]); - left = xor(left, P[17]); - return left + right; - } - /** * This method returns plaintext for the ciphertext passed as the first parameter decoded * using the key passed as the second parameter @@ -397,14 +1219,12 @@ String encrypt(String plainText, String key) * @param String key is the key which is to be used for generating cipher text * @return String plainText is the decrypted text */ - String decrypt(String cipherText,String key) - { - //generating key - keyGenerate(key); - - for (int i = 17; i > 1; i--) - cipherText = round(i, cipherText); - + String decrypt(String cipherText, String key) { + //generating key + keyGenerate(key); + + for (int i = 17; i > 1; i--) cipherText = round(i, cipherText); + //postprocessing String right = cipherText.substring(0, 8); String left = cipherText.substring(8, 16); @@ -412,5 +1232,4 @@ String decrypt(String cipherText,String key) left = xor(left, P[0]); return left + right; } - } diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java index bc2fd369d13d..63316b649132 100644 --- a/src/main/java/com/thealgorithms/ciphers/Caesar.java +++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java @@ -25,21 +25,16 @@ public static String encode(String message, int shift) { final int length = message.length(); for (int i = 0; i < length; i++) { - // int current = message.charAt(i); //using char to shift characters because ascii // is in-order latin alphabet char current = message.charAt(i); // Java law : char + int = char if (IsCapitalLatinLetter(current)) { - current += shift; encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters - } else if (IsSmallLatinLetter(current)) { - current += shift; encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters - } else { encoded.append(current); } @@ -62,15 +57,11 @@ public static String decode(String encryptedMessage, int shift) { for (int i = 0; i < length; i++) { char current = encryptedMessage.charAt(i); if (IsCapitalLatinLetter(current)) { - current -= shift; decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters - } else if (IsSmallLatinLetter(current)) { - current -= shift; decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters - } else { decoded.append(current); } @@ -91,12 +82,13 @@ private static boolean IsCapitalLatinLetter(char c) { private static boolean IsSmallLatinLetter(char c) { return c >= 'a' && c <= 'z'; } + /** * @return string array which contains all the possible decoded combination. */ public static String[] bruteforce(String encryptedMessage) { String[] listOfAllTheAnswers = new String[27]; - for (int i=0; i<=26; i++) { + for (int i = 0; i <= 26; i++) { listOfAllTheAnswers[i] = decode(encryptedMessage, i); } @@ -117,24 +109,32 @@ public static void main(String[] args) { System.out.println("Please enter the shift number"); shift = input.nextInt() % 26; System.out.println( - "ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle + "ENCODED MESSAGE IS \n" + encode(message, shift) + ); // send our function to handle break; case 'D': case 'd': System.out.println("Please enter the shift number"); shift = input.nextInt() % 26; - System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); + System.out.println( + "DECODED MESSAGE IS \n" + decode(message, shift) + ); break; case 'B': case 'b': String[] listOfAllTheAnswers = bruteforce(message); - for (int i =0; i<=26; i++) { - System.out.println("FOR SHIFT " + String.valueOf(i) + " decoded message is " + listOfAllTheAnswers[i]); + for (int i = 0; i <= 26; i++) { + System.out.println( + "FOR SHIFT " + + String.valueOf(i) + + " decoded message is " + + listOfAllTheAnswers[i] + ); } default: System.out.println("default case"); } - + input.close(); } } diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java index 4c699a28eba0..35f15e587d2f 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -12,8 +12,9 @@ public class ColumnarTranspositionCipher { private static String keyword; private static Object[][] table; private static String abecedarium; - public static final String ABECEDARIUM - = "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; + public static final String ABECEDARIUM = + "abcdefghijklmnopqrstuvwxyzABCDEFG" + + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; private static final String ENCRYPTION_FIELD = "≈"; private static final char ENCRYPTION_FIELD_CHAR = '≈'; @@ -49,9 +50,14 @@ public static String encrpyter(String word, String keyword) { * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ - public static String encrpyter(String word, String keyword, String abecedarium) { + public static String encrpyter( + String word, + String keyword, + String abecedarium + ) { ColumnarTranspositionCipher.keyword = keyword; - ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); + ColumnarTranspositionCipher.abecedarium = + Objects.requireNonNullElse(abecedarium, ABECEDARIUM); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); StringBuilder wordEncrypted = new StringBuilder(); @@ -114,7 +120,9 @@ private static Object[][] tableBuilder(String word) { * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { - if (word.length() / keyword.length() > word.length() / keyword.length()) { + if ( + word.length() / keyword.length() > word.length() / keyword.length() + ) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); @@ -139,12 +147,22 @@ private static Object[] findElements() { private static Object[][] sortTable(Object[][] table) { Object[][] tableSorted = new Object[table.length][table[0].length]; for (int i = 0; i < tableSorted.length; i++) { - System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); + System.arraycopy( + table[i], + 0, + tableSorted[i], + 0, + tableSorted[i].length + ); } for (int i = 0; i < tableSorted[0].length; i++) { for (int j = i + 1; j < tableSorted[0].length; j++) { if ((int) tableSorted[0][i] > (int) table[0][j]) { - Object[] column = getColumn(tableSorted, tableSorted.length, i); + Object[] column = getColumn( + tableSorted, + tableSorted.length, + i + ); switchColumns(tableSorted, j, i, column); } } @@ -164,7 +182,11 @@ private static Object[] getColumn(Object[][] table, int rows, int column) { } private static void switchColumns( - Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { + Object[][] table, + int firstColumnIndex, + int secondColumnIndex, + Object[] columnToSwitch + ) { for (int i = 0; i < table.length; i++) { table[i][secondColumnIndex] = table[i][firstColumnIndex]; table[i][firstColumnIndex] = columnToSwitch[i]; @@ -195,13 +217,22 @@ private static void showTable() { public static void main(String[] args) { String keywordForExample = "asd215"; - String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; - System.out.println("### Example of Columnar Transposition Cipher ###\n"); + String wordBeingEncrypted = + "This is a test of the Columnar Transposition Cipher"; + System.out.println( + "### Example of Columnar Transposition Cipher ###\n" + ); System.out.println("Word being encryped ->>> " + wordBeingEncrypted); System.out.println( - "Word encrypted ->>> " - + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample)); - System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()); + "Word encrypted ->>> " + + ColumnarTranspositionCipher.encrpyter( + wordBeingEncrypted, + keywordForExample + ) + ); + System.out.println( + "Word decryped ->>> " + ColumnarTranspositionCipher.decrypter() + ); System.out.println("\n### Encrypted Table ###"); showTable(); } diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index 5566b07e63f6..f989502ed6d2 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -29,7 +29,7 @@ static void encrypt(String message) { } } //check if det = 0 - validateDeterminant(keyMatrix,matrixSize); + validateDeterminant(keyMatrix, matrixSize); int[][] messageVector = new int[matrixSize][1]; String CipherText = ""; @@ -76,7 +76,7 @@ static void decrypt(String message) { } } //check if det = 0 - validateDeterminant(keyMatrix,n); + validateDeterminant(keyMatrix, n); //solving for the required plaintext message int[][] messageVector = new int[n][1]; @@ -155,9 +155,11 @@ static void hillCipher(String message) { } } - static void validateDeterminant(int[][] keyMatrix, int n){ + static void validateDeterminant(int[][] keyMatrix, int n) { if (determinant(keyMatrix, n) % 26 == 0) { - System.out.println("Invalid key, as determinant = 0. Program Terminated"); + System.out.println( + "Invalid key, as determinant = 0. Program Terminated" + ); return; } } @@ -169,4 +171,4 @@ public static void main(String[] args) { String message = userInput.nextLine(); hillCipher(message); } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/ciphers/Polybius.java b/src/main/java/com/thealgorithms/ciphers/Polybius.java index a787870da46b..30eba49807f7 100644 --- a/src/main/java/com/thealgorithms/ciphers/Polybius.java +++ b/src/main/java/com/thealgorithms/ciphers/Polybius.java @@ -15,12 +15,12 @@ public class Polybius { private static final char[][] key = { - // 0 1 2 3 4 - /* 0 */ {'A', 'B', 'C', 'D', 'E'}, - /* 1 */ {'F', 'G', 'H', 'I', 'J'}, - /* 2 */ {'K', 'L', 'M', 'N', 'O'}, - /* 3 */ {'P', 'Q', 'R', 'S', 'T'}, - /* 4 */ {'V', 'W', 'X', 'Y', 'Z'} + // 0 1 2 3 4 + /* 0 */{ 'A', 'B', 'C', 'D', 'E' }, + /* 1 */{ 'F', 'G', 'H', 'I', 'J' }, + /* 2 */{ 'K', 'L', 'M', 'N', 'O' }, + /* 3 */{ 'P', 'Q', 'R', 'S', 'T' }, + /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' }, }; private static String findLocationByCharacter(final char character) { @@ -49,11 +49,11 @@ public static String encrypt(final String plaintext) { public static String decrypt(final String ciphertext) { final char[] chars = ciphertext.toCharArray(); final StringBuilder plaintext = new StringBuilder(); - for(int i = 0; i < chars.length; i+=2) { + for (int i = 0; i < chars.length; i += 2) { int pozitionX = Character.getNumericValue(chars[i]); int pozitionY = Character.getNumericValue(chars[i + 1]); plaintext.append(key[pozitionX][pozitionY]); } return plaintext.toString(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java index 39683b3e79b3..e2a33e035e16 100644 --- a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java @@ -68,5 +68,4 @@ public static void main(String args[]) { System.out.println(plaintext); sc.close(); } - } diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index 27b4b457f5bb..abab01361e3b 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -1,8 +1,8 @@ package com.thealgorithms.ciphers; -import javax.swing.*; import java.math.BigInteger; import java.security.SecureRandom; +import javax.swing.*; /** * @author Nguyen Duy Tiep on 23-Oct-17. @@ -10,14 +10,21 @@ public final class RSA { public static void main(String[] args) { - RSA rsa = new RSA(1024); - String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); + String text1 = JOptionPane.showInputDialog( + "Enter a message to encrypt :" + ); String ciphertext = rsa.encrypt(text1); - JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); - - JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); + JOptionPane.showMessageDialog( + null, + "Your encrypted message : " + ciphertext + ); + + JOptionPane.showMessageDialog( + null, + "Your message after decrypt : " + rsa.decrypt(ciphertext) + ); } private BigInteger modulus, privateKey, publicKey; @@ -30,7 +37,8 @@ public RSA(int bits) { * @return encrypted message */ public synchronized String encrypt(String message) { - return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus) + .toString(); } /** @@ -44,7 +52,10 @@ public synchronized BigInteger encrypt(BigInteger message) { * @return plain message */ public synchronized String decrypt(String encryptedMessage) { - return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); + return new String( + (new BigInteger(encryptedMessage)).modPow(privateKey, modulus) + .toByteArray() + ); } /** @@ -63,7 +74,8 @@ public synchronized void generateKeys(int bits) { BigInteger q = new BigInteger(bits / 2, 100, r); modulus = p.multiply(q); - BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); + BigInteger m = + (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); publicKey = new BigInteger("3"); diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java index 56e5baf38447..8fd7744c82bd 100644 --- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java @@ -84,9 +84,11 @@ public static String decode(String encryptedMessage, String cipherSmall) { } public static void main(String[] args) { - String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb"); + String a = encode( + "defend the east wall of the castle", + "phqgiumeaylnofdxjkrcvstzwb" + ); String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb"); System.out.println(b); } - } diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubstitutionCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubstitutionCipher.java index ac68c7a4a907..4795638d38f3 100644 --- a/src/main/java/com/thealgorithms/ciphers/SimpleSubstitutionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubstitutionCipher.java @@ -85,7 +85,10 @@ public static String decode(String encryptedMessage, String cipherSmall) { * TODO remove main and make JUnit Testing */ public static void main(String[] args) { - String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb"); + String a = encode( + "defend the east wall of the castle", + "phqgiumeaylnofdxjkrcvstzwb" + ); String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb"); System.out.println(b); } diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java index ced26792cd5b..47e5aff7d7d4 100644 --- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java +++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java @@ -9,17 +9,27 @@ public class Vigenere { public static String encrypt(final String message, final String key) { - StringBuilder result = new StringBuilder(); for (int i = 0, j = 0; i < message.length(); i++) { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); - + result.append( + (char) ( + (c + key.toUpperCase().charAt(j) - 2 * 'A') % + 26 + + 'A' + ) + ); } else { - result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); + result.append( + (char) ( + (c + key.toLowerCase().charAt(j) - 2 * 'a') % + 26 + + 'a' + ) + ); } } else { result.append(c); @@ -33,14 +43,20 @@ public static String decrypt(final String message, final String key) { StringBuilder result = new StringBuilder(); for (int i = 0, j = 0; i < message.length(); i++) { - char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); - + result.append( + (char) ( + 'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26 + ) + ); } else { - result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); + result.append( + (char) ( + 'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26 + ) + ); } } else { result.append(c); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index 01a3e665f5d5..b7d36db5c809 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java @@ -4,21 +4,22 @@ // https://en.wikipedia.org/wiki/A5/1 public class A5Cipher { + private final A5KeyStreamGenerator keyStreamGenerator; private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something - public A5Cipher( BitSet sessionKey, BitSet frameCounter ) { + public A5Cipher(BitSet sessionKey, BitSet frameCounter) { keyStreamGenerator = new A5KeyStreamGenerator(); - keyStreamGenerator.initialize( sessionKey, frameCounter ); + keyStreamGenerator.initialize(sessionKey, frameCounter); } - public BitSet encrypt( BitSet plainTextBits ) { + public BitSet encrypt(BitSet plainTextBits) { // create a copy - var result = new BitSet( KEY_STREAM_LENGTH ); - result.xor( plainTextBits ); + var result = new BitSet(KEY_STREAM_LENGTH); + result.xor(plainTextBits); var key = keyStreamGenerator.getNextKeyStream(); - result.xor( key ); + result.xor(key); return result; } @@ -26,5 +27,4 @@ public BitSet encrypt( BitSet plainTextBits ) { public void resetCounter() { keyStreamGenerator.reInitialize(); } - } diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java index 4232c66fde2d..7788efc17774 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -4,6 +4,7 @@ // TODO: raise exceptions for improper use public class A5KeyStreamGenerator extends CompositeLFSR { + private BitSet initialFrameCounter; private BitSet frameCounter; private BitSet sessionKey; @@ -11,32 +12,35 @@ public class A5KeyStreamGenerator extends CompositeLFSR { private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something @Override - public void initialize( BitSet sessionKey, BitSet frameCounter ) { + public void initialize(BitSet sessionKey, BitSet frameCounter) { this.sessionKey = sessionKey; this.frameCounter = (BitSet) frameCounter.clone(); this.initialFrameCounter = (BitSet) frameCounter.clone(); registers.clear(); - LFSR lfsr1 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } ); - LFSR lfsr2 = new LFSR( 22, 10, new int[]{ 20, 21 } ); - LFSR lfsr3 = new LFSR( 23, 10, new int[]{ 7, 20, 21, 22 } ); - registers.add( lfsr1 ); - registers.add( lfsr2 ); - registers.add( lfsr3 ); - registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) ); + LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 }); + LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 }); + registers.add(lfsr1); + registers.add(lfsr2); + registers.add(lfsr3); + registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter)); } public void reInitialize() { - this.initialize( sessionKey, initialFrameCounter ); + this.initialize(sessionKey, initialFrameCounter); } public BitSet getNextKeyStream() { - for ( int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle ) - this.clock(); - - BitSet result = new BitSet( KEY_STREAM_LENGTH ); - for ( int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle ) { + for ( + int cycle = 1; + cycle <= INITIAL_CLOCKING_CYCLES; + ++cycle + ) this.clock(); + + BitSet result = new BitSet(KEY_STREAM_LENGTH); + for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) { boolean outputBit = this.clock(); - result.set( cycle - 1, outputBit ); + result.set(cycle - 1, outputBit); } reInitializeRegisters(); @@ -45,10 +49,10 @@ public BitSet getNextKeyStream() { private void reInitializeRegisters() { incrementFrameCounter(); - registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) ); + registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter)); } private void incrementFrameCounter() { - Utils.increment( frameCounter, FRAME_COUNTER_LENGTH ); + Utils.increment(frameCounter, FRAME_COUNTER_LENGTH); } } diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java index e830f5dbbdd4..050657166e77 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java @@ -6,6 +6,7 @@ import java.util.TreeMap; public abstract class CompositeLFSR implements BaseLFSR { + protected final List registers = new ArrayList<>(); /** @@ -16,20 +17,24 @@ public abstract class CompositeLFSR implements BaseLFSR { public boolean clock() { boolean majorityBit = getMajorityBit(); boolean result = false; - for ( var register : registers ) { + for (var register : registers) { result ^= register.getLastBit(); - if ( register.getClockBit() == majorityBit ) - register.clock(); + if (register.getClockBit() == majorityBit) register.clock(); } return result; } private boolean getMajorityBit() { Map bitCount = new TreeMap<>(); - bitCount.put( false, 0 ); - bitCount.put( true, 0 ); + bitCount.put(false, 0); + bitCount.put(true, 0); - registers.forEach( lfsr -> bitCount.put( lfsr.getClockBit(), bitCount.get( lfsr.getClockBit() ) + 1 ) ); - return bitCount.get( false ) <= bitCount.get( true ); + registers.forEach(lfsr -> + bitCount.put( + lfsr.getClockBit(), + bitCount.get(lfsr.getClockBit()) + 1 + ) + ); + return bitCount.get(false) <= bitCount.get(true); } } diff --git a/src/main/java/com/thealgorithms/ciphers/a5/LFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/LFSR.java index 3fdf08cbb3d8..dc42ae0a7a5e 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/LFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/LFSR.java @@ -3,71 +3,72 @@ import java.util.BitSet; public class LFSR implements BaseLFSR { + private final BitSet register; private final int length; private final int clockBitIndex; private final int[] tappingBitsIndices; - public LFSR( int length, int clockBitIndex, int[] tappingBitsIndices ) { + public LFSR(int length, int clockBitIndex, int[] tappingBitsIndices) { this.length = length; this.clockBitIndex = clockBitIndex; this.tappingBitsIndices = tappingBitsIndices; - register = new BitSet( length ); + register = new BitSet(length); } @Override - public void initialize( BitSet sessionKey, BitSet frameCounter ) { + public void initialize(BitSet sessionKey, BitSet frameCounter) { register.clear(); - clock( sessionKey, SESSION_KEY_LENGTH ); - clock( frameCounter, FRAME_COUNTER_LENGTH ); + clock(sessionKey, SESSION_KEY_LENGTH); + clock(frameCounter, FRAME_COUNTER_LENGTH); } - private void clock( BitSet key, int keyLength ) { + private void clock(BitSet key, int keyLength) { // We start from reverse because LFSR 0 index is the left most bit // while key 0 index is right most bit, so we reverse it - for ( int i = keyLength - 1; i >= 0; --i ) { - var newBit = key.get( i ) ^ xorTappingBits(); - pushBit( newBit ); + for (int i = keyLength - 1; i >= 0; --i) { + var newBit = key.get(i) ^ xorTappingBits(); + pushBit(newBit); } } @Override public boolean clock() { - return pushBit( xorTappingBits() ); + return pushBit(xorTappingBits()); } public boolean getClockBit() { - return register.get( clockBitIndex ); + return register.get(clockBitIndex); } - public boolean get( int bitIndex ) { - return register.get( bitIndex ); + public boolean get(int bitIndex) { + return register.get(bitIndex); } public boolean getLastBit() { - return register.get( length - 1 ); + return register.get(length - 1); } private boolean xorTappingBits() { boolean result = false; - for ( int i : tappingBitsIndices ) { - result ^= register.get( i ); + for (int i : tappingBitsIndices) { + result ^= register.get(i); } return result; } - private boolean pushBit( boolean bit ) { + private boolean pushBit(boolean bit) { boolean discardedBit = rightShift(); - register.set( 0, bit ); + register.set(0, bit); return discardedBit; } private boolean rightShift() { - boolean discardedBit = get( length - 1 ); - for ( int i = length - 1; i > 0; --i ) { - register.set( i, get( i - 1 ) ); + boolean discardedBit = get(length - 1); + for (int i = length - 1; i > 0; --i) { + register.set(i, get(i - 1)); } - register.set( 0, false ); + register.set(0, false); return discardedBit; } diff --git a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java index 96bf0fc1e6d9..b9220d11f868 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java @@ -7,15 +7,16 @@ import java.util.BitSet; public class Utils { - public static boolean increment( BitSet bits, int size ) { + + public static boolean increment(BitSet bits, int size) { int i = size - 1; - while ( i >= 0 && bits.get( i ) ) { - bits.set( i--, false );/*from w w w . j a v a 2s .c o m*/ + while (i >= 0 && bits.get(i)) { + bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/ } - if ( i < 0 ) { + if (i < 0) { return false; } - bits.set( i, true ); + bits.set(i, true); return true; } } diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java index 5c0722e0d4c3..25d9ded3b458 100644 --- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java @@ -31,7 +31,12 @@ public static void main(String[] args) { System.out.print("Enter number: "); n = in.next(); System.out.print( - "Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); + "Enter beginning base (between " + + MINIMUM_BASE + + " and " + + MAXIMUM_BASE + + "): " + ); b1 = in.nextInt(); if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { System.out.println("Invalid base!"); @@ -42,7 +47,12 @@ public static void main(String[] args) { continue; } System.out.print( - "Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); + "Enter end base (between " + + MINIMUM_BASE + + " and " + + MAXIMUM_BASE + + "): " + ); b2 = in.nextInt(); if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { System.out.println("Invalid base!"); @@ -63,8 +73,42 @@ public static void main(String[] args) { */ public static boolean validForBase(String n, int base) { char[] validDigits = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', - 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', }; // digitsForBase contains all the valid digits for the base given char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); diff --git a/src/main/java/com/thealgorithms/conversions/AnytoAny.java b/src/main/java/com/thealgorithms/conversions/AnytoAny.java index 3eed1fce0fa6..052d6dba6953 100644 --- a/src/main/java/com/thealgorithms/conversions/AnytoAny.java +++ b/src/main/java/com/thealgorithms/conversions/AnytoAny.java @@ -1,6 +1,7 @@ package com.thealgorithms.conversions; import java.util.Scanner; + // given a source number , source base, destination base, this code can give you the destination // number. // sn ,sb,db ---> ()dn . this is what we have to do . diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java index 8ef4737b17c3..df547ffb5610 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java @@ -11,7 +11,9 @@ public class DecimalToAnyBase { public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in) + ); System.out.println("Enter the decimal input below: "); int decInput = Integer.parseInt(br.readLine()); System.out.println(); @@ -22,7 +24,13 @@ public static void main(String[] args) throws Exception { System.out.println("Decimal Input" + " is: " + decInput); System.out.println( - "Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); + "Value of " + + decInput + + " in base " + + base + + " is: " + + convertToAnyBase(decInput, base) + ); br.close(); } diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java index 35cec4079ed6..7bd67123de33 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java @@ -24,7 +24,9 @@ public static void main(String args[]) { public static void conventionalConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf("Conventional conversion.%n Enter the decimal number: "); + System.out.printf( + "Conventional conversion.%n Enter the decimal number: " + ); n = input.nextInt(); while (n != 0) { d = n % 2; diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java b/src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java index 83129406cf29..3564acbe568c 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java @@ -7,7 +7,22 @@ class DecimalToHexaDecimal { private static final int numberOfBitsInAHalfByte = 4; private static final int halfByte = 0x0F; private static final char[] hexDigits = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', }; // Returns the hex value of the dec entered in the parameter. diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java index 92057c953b60..ccbab30f070e 100644 --- a/src/main/java/com/thealgorithms/conversions/HexToOct.java +++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java @@ -61,9 +61,7 @@ public static void main(String args[]) { hexadecnum = scan.nextLine(); // first convert hexadecimal to decimal - decnum - = hex2decimal( - hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in + decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in // variable decnum // convert decimal to octal diff --git a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java index ef070ae7986a..fde142067204 100644 --- a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java @@ -22,9 +22,20 @@ public String completeDigits(String binNum) { } public static void main(String[] args) { - // Testing Numbers: - String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; + String[] hexNums = { + "1", + "A1", + "ef", + "BA", + "AA", + "BB", + "19", + "01", + "02", + "03", + "04", + }; HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); for (String num : hexNums) { diff --git a/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java b/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java index 53c07d58c4fd..b81cfd773d75 100644 --- a/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java +++ b/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java @@ -9,10 +9,36 @@ */ public class IntegerToRoman { - private static int[] allArabianRomanNumbers - = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - private static String[] allRomanNumbers - = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + private static int[] allArabianRomanNumbers = new int[] { + 1000, + 900, + 500, + 400, + 100, + 90, + 50, + 40, + 10, + 9, + 5, + 4, + 1, + }; + private static String[] allRomanNumbers = new String[] { + "M", + "CM", + "D", + "CD", + "C", + "XC", + "L", + "XL", + "X", + "IX", + "V", + "IV", + "I", + }; // Value must be > 0 public static String integerToRoman(int num) { diff --git a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java index 978adee4b7db..be8b43375cc2 100644 --- a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java +++ b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java @@ -32,7 +32,6 @@ public static void main(String args[]) { * @return The decimal number */ public static int convertOctalToDecimal(String inputOctal) { - try { // Actual conversion of Octal to Decimal: Integer outputDecimal = Integer.parseInt(inputOctal, 8); diff --git a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java index f757ef4e9aca..b1755b8a0aca 100644 --- a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java +++ b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java @@ -47,7 +47,6 @@ public static String decimalToHex(int d) { } public static void main(String args[]) { - Scanner input = new Scanner(System.in); System.out.print("Enter the Octal number: "); // Take octal number as input from user in a string diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java index 81e28919d368..4fad34ec8844 100644 --- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java +++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java @@ -19,30 +19,69 @@ public static void main(String[] args) { // Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html // Test hsvToRgb-method - assert Arrays.equals(hsvToRgb(0, 0, 0), new int[]{0, 0, 0}); - assert Arrays.equals(hsvToRgb(0, 0, 1), new int[]{255, 255, 255}); - assert Arrays.equals(hsvToRgb(0, 1, 1), new int[]{255, 0, 0}); - assert Arrays.equals(hsvToRgb(60, 1, 1), new int[]{255, 255, 0}); - assert Arrays.equals(hsvToRgb(120, 1, 1), new int[]{0, 255, 0}); - assert Arrays.equals(hsvToRgb(240, 1, 1), new int[]{0, 0, 255}); - assert Arrays.equals(hsvToRgb(300, 1, 1), new int[]{255, 0, 255}); - assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[]{64, 128, 128}); - assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[]{193, 196, 224}); - assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[]{128, 32, 80}); + assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 }); + assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 }); + assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 }); + assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 }); + assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 }); + assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 }); + assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 }); + assert Arrays.equals( + hsvToRgb(180, 0.5, 0.5), + new int[] { 64, 128, 128 } + ); + assert Arrays.equals( + hsvToRgb(234, 0.14, 0.88), + new int[] { 193, 196, 224 } + ); + assert Arrays.equals( + hsvToRgb(330, 0.75, 0.5), + new int[] { 128, 32, 80 } + ); // Test rgbToHsv-method // approximate-assertions needed because of small deviations due to converting between // int-values and double-values. - assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[]{0, 0, 0}); - assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[]{0, 0, 1}); - assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[]{0, 1, 1}); - assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[]{60, 1, 1}); - assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[]{120, 1, 1}); - assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[]{240, 1, 1}); - assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[]{300, 1, 1}); - assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[]{180, 0.5, 0.5}); - assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[]{234, 0.14, 0.88}); - assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[]{330, 0.75, 0.5}); + assert approximatelyEqualHsv( + rgbToHsv(0, 0, 0), + new double[] { 0, 0, 0 } + ); + assert approximatelyEqualHsv( + rgbToHsv(255, 255, 255), + new double[] { 0, 0, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(255, 0, 0), + new double[] { 0, 1, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(255, 255, 0), + new double[] { 60, 1, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(0, 255, 0), + new double[] { 120, 1, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(0, 0, 255), + new double[] { 240, 1, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(255, 0, 255), + new double[] { 300, 1, 1 } + ); + assert approximatelyEqualHsv( + rgbToHsv(64, 128, 128), + new double[] { 180, 0.5, 0.5 } + ); + assert approximatelyEqualHsv( + rgbToHsv(193, 196, 224), + new double[] { 234, 0.14, 0.88 } + ); + assert approximatelyEqualHsv( + rgbToHsv(128, 32, 80), + new double[] { 330, 0.75, 0.5 } + ); } /** @@ -55,23 +94,35 @@ public static void main(String[] args) { */ public static int[] hsvToRgb(double hue, double saturation, double value) { if (hue < 0 || hue > 360) { - throw new IllegalArgumentException("hue should be between 0 and 360"); + throw new IllegalArgumentException( + "hue should be between 0 and 360" + ); } if (saturation < 0 || saturation > 1) { - throw new IllegalArgumentException("saturation should be between 0 and 1"); + throw new IllegalArgumentException( + "saturation should be between 0 and 1" + ); } if (value < 0 || value > 1) { - throw new IllegalArgumentException("value should be between 0 and 1"); + throw new IllegalArgumentException( + "value should be between 0 and 1" + ); } double chroma = value * saturation; double hueSection = hue / 60; - double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1)); + double secondLargestComponent = + chroma * (1 - Math.abs(hueSection % 2 - 1)); double matchValue = value - chroma; - return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); + return getRgbBySection( + hueSection, + chroma, + matchValue, + secondLargestComponent + ); } /** @@ -84,15 +135,21 @@ public static int[] hsvToRgb(double hue, double saturation, double value) { */ public static double[] rgbToHsv(int red, int green, int blue) { if (red < 0 || red > 255) { - throw new IllegalArgumentException("red should be between 0 and 255"); + throw new IllegalArgumentException( + "red should be between 0 and 255" + ); } if (green < 0 || green > 255) { - throw new IllegalArgumentException("green should be between 0 and 255"); + throw new IllegalArgumentException( + "green should be between 0 and 255" + ); } if (blue < 0 || blue > 255) { - throw new IllegalArgumentException("blue should be between 0 and 255"); + throw new IllegalArgumentException( + "blue should be between 0 and 255" + ); } double dRed = (double) red / 255; @@ -115,7 +172,7 @@ public static double[] rgbToHsv(int red, int green, int blue) { hue = (hue + 360) % 360; - return new double[]{hue, saturation, value}; + return new double[] { hue, saturation, value }; } private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { @@ -127,7 +184,11 @@ private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { } private static int[] getRgbBySection( - double hueSection, double chroma, double matchValue, double secondLargestComponent) { + double hueSection, + double chroma, + double matchValue, + double secondLargestComponent + ) { int red; int green; int blue; @@ -158,7 +219,7 @@ private static int[] getRgbBySection( blue = convertToInt(secondLargestComponent + matchValue); } - return new int[]{red, green, blue}; + return new int[] { red, green, blue }; } private static int convertToInt(double input) { diff --git a/src/main/java/com/thealgorithms/conversions/RomanToInteger.java b/src/main/java/com/thealgorithms/conversions/RomanToInteger.java index 77b35b257891..fddb56232c58 100644 --- a/src/main/java/com/thealgorithms/conversions/RomanToInteger.java +++ b/src/main/java/com/thealgorithms/conversions/RomanToInteger.java @@ -4,8 +4,7 @@ public class RomanToInteger { - private static Map map - = new HashMap() { + private static Map map = new HashMap() { /** * */ private static final long serialVersionUID = 87605733047260530L; @@ -20,6 +19,7 @@ public class RomanToInteger { put('M', 1000); } }; + // Roman Number = Roman Numerals /** @@ -29,7 +29,6 @@ public class RomanToInteger { * @return integer */ public static int romanToInt(String A) { - A = A.toUpperCase(); char prev = ' '; diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java index 0929496a1fe6..af26cc056f1a 100644 --- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java +++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java @@ -29,13 +29,40 @@ public static void main(String args[]) { * @return String */ public static String convertTurkishToLatin(String param) { - char[] turkishChars - = new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E}; - char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'}; + char[] turkishChars = new char[] { + 0x131, + 0x130, + 0xFC, + 0xDC, + 0xF6, + 0xD6, + 0x15F, + 0x15E, + 0xE7, + 0xC7, + 0x11F, + 0x11E, + }; + char[] latinChars = new char[] { + 'i', + 'I', + 'u', + 'U', + 'o', + 'O', + 's', + 'S', + 'c', + 'C', + 'g', + 'G', + }; for (int i = 0; i < turkishChars.length; i++) { - param - = param.replaceAll( - new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]})); + param = + param.replaceAll( + new String(new char[] { turkishChars[i] }), + new String(new char[] { latinChars[i] }) + ); } return param; } diff --git a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java index 71ad0e42ff0c..db85afa18c81 100644 --- a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java +++ b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java @@ -1,6 +1,5 @@ package com.thealgorithms.datastructures.bloomfilter; - import java.util.BitSet; public class BloomFilter { @@ -23,14 +22,14 @@ private void insertHash() { } public void insert(T key) { - for (Hash hash : hashFunctions){ + for (Hash hash : hashFunctions) { int position = hash.compute(key) % bitArray.size(); bitArray.set(position); } } public boolean contains(T key) { - for (Hash hash : hashFunctions){ + for (Hash hash : hashFunctions) { int position = hash.compute(key) % bitArray.size(); if (!bitArray.get(position)) { return false; @@ -43,21 +42,20 @@ private class Hash { int index; - public Hash(int index){ + public Hash(int index) { this.index = index; } - public int compute(T key){ + public int compute(T key) { return index * asciiString(String.valueOf(key)); } - private int asciiString(String word){ + private int asciiString(String word) { int number = 0; - for (int i=0;i 0) { - result = Character.valueOf(_buffer[getTrueIndex(_read_index)]); _readable_data.decrementAndGet(); _read_index++; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java index 92e24150579e..01ba5e25005a 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java @@ -7,141 +7,136 @@ * Java program for LFU Cache (https://en.wikipedia.org/wiki/Least_frequently_used) * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ -public class LFUCache { +public class LFUCache { - private class Node { - private K key; - private V value; - private int frequency; - private Node previous; - private Node next; + private class Node { - public Node(K key, V value, int frequency) { - this.key = key; - this.value = value; - this.frequency = frequency; - } - } + private K key; + private V value; + private int frequency; + private Node previous; + private Node next; - private Node head; - private Node tail; - private Map map = null; - private Integer capacity; - private static final int DEFAULT_CAPACITY = 100; - - public LFUCache() { - this.capacity = DEFAULT_CAPACITY; - } + public Node(K key, V value, int frequency) { + this.key = key; + this.value = value; + this.frequency = frequency; + } + } + + private Node head; + private Node tail; + private Map map = null; + private Integer capacity; + private static final int DEFAULT_CAPACITY = 100; + + public LFUCache() { + this.capacity = DEFAULT_CAPACITY; + } + + public LFUCache(Integer capacity) { + this.capacity = capacity; + this.map = new HashMap<>(); + } - public LFUCache(Integer capacity) { - this.capacity = capacity; - this.map = new HashMap<>(); - } - /** * This method returns value present in the cache corresponding to the key passed as parameter * - * @param key for which value is to be retrieved + * @param key for which value is to be retrieved * @returns object corresponding to the key passed as parameter, returns null if key is not present in the cache */ - public V get(K key) { - if(this.map.get(key) == null) { - return null; - } + public V get(K key) { + if (this.map.get(key) == null) { + return null; + } - Node node = map.get(key); - removeNode(node); - node.frequency += 1; - addNodeWithUpdatedFrequency(node); + Node node = map.get(key); + removeNode(node); + node.frequency += 1; + addNodeWithUpdatedFrequency(node); - return node.value; - } + return node.value; + } /** * This method stores key and value in the cache * * @param key which is to be stored in the cache - * @param value which is to be stored in the cache + * @param value which is to be stored in the cache */ - public void put(K key, V value) { - if(map.containsKey(key)) { - Node node = map.get(key); - node.value = value; - node.frequency += 1; - removeNode(node); - addNodeWithUpdatedFrequency(node); - } - else { - if(map.size() >= capacity) { - map.remove(this.head.key); - removeNode(head); - } - Node node = new Node(key,value,1); - addNodeWithUpdatedFrequency(node); - map.put(key, node); - } - } + public void put(K key, V value) { + if (map.containsKey(key)) { + Node node = map.get(key); + node.value = value; + node.frequency += 1; + removeNode(node); + addNodeWithUpdatedFrequency(node); + } else { + if (map.size() >= capacity) { + map.remove(this.head.key); + removeNode(head); + } + Node node = new Node(key, value, 1); + addNodeWithUpdatedFrequency(node); + map.put(key, node); + } + } /** * This method stores the node in the cache with updated frequency * - * @param Node node which is to be updated in the cache + * @param Node node which is to be updated in the cache */ - private void addNodeWithUpdatedFrequency(Node node) { - if(tail != null && head != null) { - Node temp = this.head; - while(temp != null) { - if(temp.frequency > node.frequency) { - if(temp==head) { - node.next = temp; - temp.previous = node; - this.head = node; - break; - } - else { - node.next = temp; - node.previous = temp.previous; - temp.previous.next = node; - node.previous = temp.previous; - break; - } - } - else { - temp = temp.next; - if(temp == null) { - tail.next = node; - node.previous = tail; - node.next = null; - tail = node; - break; - } - } - } - } - else { - tail = node; - head = tail; - } - } + private void addNodeWithUpdatedFrequency(Node node) { + if (tail != null && head != null) { + Node temp = this.head; + while (temp != null) { + if (temp.frequency > node.frequency) { + if (temp == head) { + node.next = temp; + temp.previous = node; + this.head = node; + break; + } else { + node.next = temp; + node.previous = temp.previous; + temp.previous.next = node; + node.previous = temp.previous; + break; + } + } else { + temp = temp.next; + if (temp == null) { + tail.next = node; + node.previous = tail; + node.next = null; + tail = node; + break; + } + } + } + } else { + tail = node; + head = tail; + } + } /** - * This method removes node from the cache - * - * @param Node node which is to be removed in the cache + * This method removes node from the cache + * + * @param Node node which is to be removed in the cache */ - private void removeNode(Node node) { - if(node.previous != null) { - node.previous.next = node.next; - } - else { - this.head = node.next; - } + private void removeNode(Node node) { + if (node.previous != null) { + node.previous.next = node.next; + } else { + this.head = node.next; + } - if(node.next != null) { - node.next.previous = node.previous; - } - else { - this.tail = node.previous; - } - } + if (node.next != null) { + node.next.previous = node.previous; + } else { + this.tail = node.previous; + } + } } diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java index fcb7d975bdb4..976a4fef1c29 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java @@ -126,10 +126,14 @@ static final class Entry { private I key; private J value; - public Entry() { - } - - public Entry(Entry preEntry, Entry nextEntry, I key, J value) { + public Entry() {} + + public Entry( + Entry preEntry, + Entry nextEntry, + I key, + J value + ) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java index 30f914968c3b..fc55c4e4d730 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java @@ -124,10 +124,14 @@ static final class Entry { private I key; private J value; - public Entry() { - } - - public Entry(Entry preEntry, Entry nextEntry, I key, J value) { + public Entry() {} + + public Entry( + Entry preEntry, + Entry nextEntry, + I key, + J value + ) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java b/src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java index 281b0cb202bb..cf26fce78088 100644 --- a/src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java +++ b/src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java @@ -6,8 +6,6 @@ public Node MakeSet(T x) { return new Node(x); } - ; - public Node FindSet(Node node) { if (node != node.parent) { node.parent = FindSet(node.parent); diff --git a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java index fb7783575e57..1b6dd0c5470f 100644 --- a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java +++ b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java @@ -44,7 +44,8 @@ public DynamicArray() { */ public void add(final E element) { if (this.size == this.elements.length) { - this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); + this.elements = + Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); } this.elements[this.size] = element; @@ -83,7 +84,8 @@ public E remove(final int index) { fastRemove(this.elements, index); if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) { - this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); + this.elements = + Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); } return oldElement; } @@ -114,7 +116,13 @@ private void fastRemove(final Object[] elements, final int index) { final int newSize = this.size - 1; if (newSize > index) { - System.arraycopy(elements, index + 1, elements, index, newSize - index); + System.arraycopy( + elements, + index + 1, + elements, + index, + newSize - index + ); } elements[this.size = newSize] = null; @@ -136,7 +144,9 @@ private int newCapacity(int capacity) { */ @Override public String toString() { - return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); + return Arrays.toString( + Arrays.stream(this.elements).filter(Objects::nonNull).toArray() + ); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java index 44f5eadaab1c..fe01cecde42e 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java @@ -8,6 +8,7 @@ public class A_Star { private static class Graph { + // Graph's structure can be changed only applying changes to this class. private ArrayList> graph; @@ -26,8 +27,10 @@ private ArrayList getNeighbours(int from) { // Graph is bidirectional, for just one direction remove second instruction of this method. private void addEdge(Edge edge) { - this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); - this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); + this.graph.get(edge.getFrom()) + .add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); + this.graph.get(edge.getTo()) + .add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); } } @@ -63,7 +66,11 @@ private static class PathAndDistance { private ArrayList path; // list of visited nodes in this path. private int estimated; // heuristic value associated to the last node od the path (current node). - public PathAndDistance(int distance, ArrayList path, int estimated) { + public PathAndDistance( + int distance, + ArrayList path, + int estimated + ) { this.distance = distance; this.path = path; this.estimated = estimated; @@ -84,16 +91,24 @@ public int getEstimated() { private void printSolution() { if (this.path != null) { System.out.println( - "Optimal path: " + this.path + ", distance: " + this.distance); + "Optimal path: " + + this.path + + ", distance: " + + this.distance + ); } else { - System.out.println("There is no path available to connect the points"); + System.out.println( + "There is no path available to connect the points" + ); } } } private static void initializeGraph(Graph graph, ArrayList data) { for (int i = 0; i < data.size(); i += 4) { - graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); + graph.addEdge( + new Edge(data.get(i), data.get(i + 1), data.get(i + 2)) + ); } /* .x. node @@ -127,30 +142,146 @@ private static void initializeGraph(Graph graph, ArrayList data) { public static void main(String[] args) { // heuristic function optimistic values int[] heuristic = { - 366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374 + 366, + 0, + 160, + 242, + 161, + 178, + 77, + 151, + 226, + 244, + 241, + 234, + 380, + 98, + 193, + 253, + 329, + 80, + 199, + 374, }; Graph graph = new Graph(20); - ArrayList graphData - = new ArrayList<>( - Arrays.asList( - 0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, - null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, - 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, - 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, - 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); + ArrayList graphData = new ArrayList<>( + Arrays.asList( + 0, + 19, + 75, + null, + 0, + 15, + 140, + null, + 0, + 16, + 118, + null, + 19, + 12, + 71, + null, + 12, + 15, + 151, + null, + 16, + 9, + 111, + null, + 9, + 10, + 70, + null, + 10, + 3, + 75, + null, + 3, + 2, + 120, + null, + 2, + 14, + 146, + null, + 2, + 13, + 138, + null, + 2, + 6, + 115, + null, + 15, + 14, + 80, + null, + 15, + 5, + 99, + null, + 14, + 13, + 97, + null, + 5, + 1, + 211, + null, + 13, + 1, + 101, + null, + 6, + 1, + 160, + null, + 1, + 17, + 85, + null, + 17, + 7, + 98, + null, + 7, + 4, + 86, + null, + 17, + 18, + 142, + null, + 18, + 8, + 92, + null, + 8, + 11, + 87 + ) + ); initializeGraph(graph, graphData); PathAndDistance solution = aStar(3, 1, graph, heuristic); solution.printSolution(); } - public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { + public static PathAndDistance aStar( + int from, + int to, + Graph graph, + int[] heuristic + ) { // nodes are prioritised by the less value of the current distance of their paths, and the // estimated value // given by the heuristic function to reach the destination point from the current point. - PriorityQueue queue - = new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); + PriorityQueue queue = new PriorityQueue<>( + Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())) + ); // dummy data to start the algorithm from the beginning point queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0)); @@ -159,26 +290,33 @@ public static PathAndDistance aStar(int from, int to, Graph graph, int[] heurist PathAndDistance currentData = new PathAndDistance(-1, null, -1); while (!queue.isEmpty() && !solutionFound) { currentData = queue.poll(); // first in the queue, best node so keep exploring. - int currentPosition - = currentData.getPath().get(currentData.getPath().size() - 1); // current node. + int currentPosition = currentData + .getPath() + .get(currentData.getPath().size() - 1); // current node. if (currentPosition == to) { solutionFound = true; } else { for (Edge edge : graph.getNeighbours(currentPosition)) { if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles - ArrayList updatedPath = new ArrayList<>(currentData.getPath()); + ArrayList updatedPath = new ArrayList<>( + currentData.getPath() + ); updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance, // and the heuristic function value associated to that path. queue.add( - new PathAndDistance( - currentData.getDistance() + edge.getWeight(), - updatedPath, - heuristic[edge.getTo()])); + new PathAndDistance( + currentData.getDistance() + edge.getWeight(), + updatedPath, + heuristic[edge.getTo()] + ) + ); } } } } - return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); + return (solutionFound) + ? currentData + : new PathAndDistance(-1, null, -1); // Out of while loop, if there is a solution, the current Data stores the optimal path, and its // distance } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index 2a86dec2c6c3..ac0898e10a30 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -3,7 +3,7 @@ import java.util.*; class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have -start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/ { +start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{ int vertex, edge; private Edge edges[]; @@ -37,8 +37,7 @@ public Edge(int a, int b, int c) { * @param i Current vertex under consideration */ void printPath(int p[], int i) { - if (p[i] == -1) // Found the path back to parent - { + if (p[i] == -1) { // Found the path back to parent return; } printPath(p, p[i]); @@ -50,10 +49,7 @@ public static void main(String args[]) { obj.go(); } - public void - go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and - // shows distance to all vertices - { + public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and Scanner sc = new Scanner(System.in); // Grab scanner object for user input int i, v, e, u, ve, w, j, neg = 0; System.out.println("Enter no. of vertices and edges please"); @@ -67,8 +63,7 @@ public static void main(String args[]) { w = sc.nextInt(); arr[i] = new Edge(u, ve, w); } - int dist[] - = new int[v]; // Distance array for holding the finalized shortest path distance between source + int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source // and all vertices int p[] = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { @@ -78,8 +73,10 @@ public static void main(String args[]) { p[0] = -1; for (i = 0; i < v - 1; i++) { for (j = 0; j < e; j++) { - if ((int) dist[arr[j].u] != Integer.MAX_VALUE - && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + if ( + (int) dist[arr[j].u] != Integer.MAX_VALUE && + dist[arr[j].v] > dist[arr[j].u] + arr[j].w + ) { dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update p[arr[j].v] = arr[j].u; } @@ -87,14 +84,16 @@ public static void main(String args[]) { } // Final cycle for negative checking for (j = 0; j < e; j++) { - if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + if ( + (int) dist[arr[j].u] != Integer.MAX_VALUE && + dist[arr[j].v] > dist[arr[j].u] + arr[j].w + ) { neg = 1; System.out.println("Negative cycle"); break; } } - if (neg == 0) // Go ahead and show results of computation - { + if (neg == 0) { // Go ahead and show results of computation System.out.println("Distances are: "); for (i = 0; i < v; i++) { System.out.println(i + " " + dist[i]); @@ -114,15 +113,9 @@ public static void main(String args[]) { * @param end Ending vertex * @param Edge Array of edges */ - public void show( - int source, - int end, - Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should - // be created by using addEdge() method and passed by calling getEdgeArray() method - { + public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should int i, j, v = vertex, e = edge, neg = 0; - double dist[] - = new double[v]; // Distance array for holding the finalized shortest path distance between source + double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source // and all vertices int p[] = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { @@ -132,8 +125,10 @@ public void show( p[source] = -1; for (i = 0; i < v - 1; i++) { for (j = 0; j < e; j++) { - if ((int) dist[arr[j].u] != Integer.MAX_VALUE - && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + if ( + (int) dist[arr[j].u] != Integer.MAX_VALUE && + dist[arr[j].v] > dist[arr[j].u] + arr[j].w + ) { dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update p[arr[j].v] = arr[j].u; } @@ -141,14 +136,16 @@ public void show( } // Final cycle for negative checking for (j = 0; j < e; j++) { - if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + if ( + (int) dist[arr[j].u] != Integer.MAX_VALUE && + dist[arr[j].v] > dist[arr[j].u] + arr[j].w + ) { neg = 1; System.out.println("Negative cycle"); break; } } - if (neg == 0) // Go ahead and show results of computaion - { + if (neg == 0) { // Go ahead and show results of computaion System.out.println("Distance is: " + dist[end]); System.out.println("Path followed:"); System.out.print(source + " "); @@ -162,8 +159,7 @@ public void show( * @param y End vertex * @param z Weight */ - public void addEdge(int x, int y, int z) // Adds unidirectional edge - { + public void addEdge(int x, int y, int z) { // Adds unidirectional edge edges[index++] = new Edge(x, y, z); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java index 7985bcb04e03..5d484d187eea 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java @@ -16,7 +16,12 @@ */ public class BipartiteGrapfDFS { - private static boolean bipartite(int V, ArrayList> adj, int[] color, int node) { + private static boolean bipartite( + int V, + ArrayList> adj, + int[] color, + int node + ) { if (color[node] == -1) { color[node] = 1; } @@ -33,7 +38,10 @@ private static boolean bipartite(int V, ArrayList> adj, int[] return true; } - public static boolean isBipartite(int V, ArrayList> adj) { + public static boolean isBipartite( + int V, + ArrayList> adj + ) { // Code here int[] color = new int[V + 1]; Arrays.fill(color, -1); @@ -49,7 +57,9 @@ public static boolean isBipartite(int V, ArrayList> adj) { } public static void main(String[] args) throws IOException { - BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader read = new BufferedReader( + new InputStreamReader(System.in) + ); int t = Integer.parseInt(read.readLine().trim()); while (t-- > 0) { String[] S = read.readLine().trim().split(" "); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java index b0add255f59a..306abd7e39df 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java @@ -137,7 +137,11 @@ public static void main(String[] args) { graphInts.addEdge(8, 10); graphInts.addEdge(10, 8); - System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); - System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); + System.out.println( + "Amount of different char-graphs: " + graphChars.countGraphs() + ); + System.out.println( + "Amount of different int-graphs: " + graphInts.countGraphs() + ); } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java index 5d5bd3c7469c..3d6e8a51ebd6 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java @@ -24,7 +24,9 @@ public Cycle() { visited[i] = false; } - System.out.println("Enter the details of each edges "); + System.out.println( + "Enter the details of each edges " + ); for (int i = 0; i < edges; i++) { int start, end; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java index e852b5ebba51..928516d2ba54 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java @@ -40,13 +40,17 @@ void dijkstra(int graph[][], int src) { dist[src] = 0; for (int c = 0; c < k - 1; c++) { - int u = minDist(dist, Set); Set[u] = true; for (int v = 0; v < k; v++) { - if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { + if ( + !Set[v] && + graph[u][v] != 0 && + dist[u] != Integer.MAX_VALUE && + dist[u] + graph[u][v] < dist[v] + ) { dist[v] = dist[u] + graph[u][v]; } } @@ -56,21 +60,21 @@ void dijkstra(int graph[][], int src) { } public static void main(String[] args) { - int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0}, - {4, 0, 8, 0, 0, 0, 0, 11, 0}, - {0, 8, 0, 7, 0, 4, 0, 0, 2}, - {0, 0, 7, 0, 9, 14, 0, 0, 0}, - {0, 0, 0, 9, 0, 10, 0, 0, 0}, - {0, 0, 4, 14, 10, 0, 2, 0, 0}, - {0, 0, 0, 0, 0, 2, 0, 1, 6}, - {8, 11, 0, 0, 0, 0, 1, 0, 7}, - {0, 0, 2, 0, 0, 0, 6, 7, 0}}; + int graph[][] = new int[][] { + { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 }, + }; dijkstras t = new dijkstras(); t.dijkstra(graph, 0); - }//main - -}//djikstras - + } //main +} //djikstras /* OUTPUT : Vertex Distance diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index 6a3eb41e9424..ab9ef7352cbc 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -9,31 +9,42 @@ public class FloydWarshall { public static final int INFINITY = 999; public FloydWarshall(int numberofvertices) { - DistanceMatrix - = new int[numberofvertices + 1][numberofvertices - + 1]; // stores the value of distance from all the possible path form the source + DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source // vertex to destination vertex // The matrix is initialized with 0's by default this.numberofvertices = numberofvertices; } - public void floydwarshall( - int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex - { + public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex for (int source = 1; source <= numberofvertices; source++) { - for (int destination = 1; destination <= numberofvertices; destination++) { - DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; + for ( + int destination = 1; + destination <= numberofvertices; + destination++ + ) { + DistanceMatrix[source][destination] = + AdjacencyMatrix[source][destination]; } } - for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { + for ( + int intermediate = 1; + intermediate <= numberofvertices; + intermediate++ + ) { for (int source = 1; source <= numberofvertices; source++) { - for (int destination = 1; destination <= numberofvertices; destination++) { - if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] - < DistanceMatrix[source][destination]) // if the new distance calculated is less then the earlier shortest - // calculated distance it get replaced as new shortest distance - { + for ( + int destination = 1; + destination <= numberofvertices; + destination++ + ) { + if ( + DistanceMatrix[source][intermediate] + + DistanceMatrix[intermediate][destination] < DistanceMatrix[source][destination] - = DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination]; + ) { // calculated distance it get replaced as new shortest distance // if the new distance calculated is less then the earlier shortest + DistanceMatrix[source][destination] = + DistanceMatrix[source][intermediate] + + DistanceMatrix[intermediate][destination]; } } } @@ -44,7 +55,11 @@ public void floydwarshall( System.out.println(); for (int source = 1; source <= numberofvertices; source++) { System.out.print(source + "\t"); - for (int destination = 1; destination <= numberofvertices; destination++) { + for ( + int destination = 1; + destination <= numberofvertices; + destination++ + ) { System.out.print(DistanceMatrix[source][destination] + "\t"); } System.out.println(); @@ -55,10 +70,15 @@ public static void main(String... arg) { Scanner scan = new Scanner(System.in); System.out.println("Enter the number of vertices"); int numberOfVertices = scan.nextInt(); - int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; + int[][] adjacencyMatrix = new int[numberOfVertices + + 1][numberOfVertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int source = 1; source <= numberOfVertices; source++) { - for (int destination = 1; destination <= numberOfVertices; destination++) { + for ( + int destination = 1; + destination <= numberOfVertices; + destination++ + ) { adjacencyMatrix[source][destination] = scan.nextInt(); if (source == destination) { adjacencyMatrix[source][destination] = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java index e0f373bf0610..68bc5074ca9e 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java @@ -12,33 +12,32 @@ public class HamiltonianCycle { /** * Find hamiltonian cycle for given graph G(V,E) - * @param graph Adjacency matrix of a graph G(V, E) + * @param graph Adjacency matrix of a graph G(V, E) * for which hamiltonian path is to be found - * @return Array containing hamiltonian cycle + * @return Array containing hamiltonian cycle * else returns 1D array with value -1. */ - public int[] findHamiltonianCycle(int[][] graph){ + public int[] findHamiltonianCycle(int[][] graph) { this.V = graph.length; - this.cycle = new int[this.V+1]; + this.cycle = new int[this.V + 1]; //Initialize path array with -1 value - for(int i=0 ; i topSortOrder() { } return answer; - } } @@ -134,7 +133,6 @@ ArrayList topSortOrder() { public class KahnsAlgorithm { public static void main(String[] args) { - //Graph definition and initialization AdjacencyList graph = new AdjacencyList<>(); graph.addEdge("a", "b"); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index a0856c819511..5d326576ffec 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -30,7 +30,12 @@ public Edge(int from, int to, int weight) { } } - private static void addEdge(HashSet[] graph, int from, int to, int weight) { + private static void addEdge( + HashSet[] graph, + int from, + int to, + int weight + ) { graph[from].add(new Edge(from, to, weight)); } @@ -53,7 +58,9 @@ public static void main(String[] args) { System.out.println("Initial Graph: "); for (int i = 0; i < graph.length; i++) { for (Edge edge : graph[i]) { - System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + System.out.println( + i + " <-- weight " + edge.weight + " --> " + edge.to + ); } } @@ -63,7 +70,9 @@ public static void main(String[] args) { System.out.println("\nMinimal Graph: "); for (int i = 0; i < solGraph.length; i++) { for (Edge edge : solGraph[i]) { - System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + System.out.println( + i + " <-- weight " + edge.weight + " --> " + edge.to + ); } } } @@ -74,7 +83,9 @@ public HashSet[] kruskal(HashSet[] graph) { // captain of i, stores the set with all the connected nodes to i HashSet[] connectedGroups = new HashSet[nodes]; HashSet[] minGraph = new HashSet[nodes]; - PriorityQueue edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); + PriorityQueue edges = new PriorityQueue<>( + (Comparator.comparingInt(edge -> edge.weight)) + ); for (int i = 0; i < nodes; i++) { minGraph[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>(); @@ -87,12 +98,18 @@ public HashSet[] kruskal(HashSet[] graph) { while (connectedElements != nodes && !edges.isEmpty()) { Edge edge = edges.poll(); // This if avoids cycles - if (!connectedGroups[captain[edge.from]].contains(edge.to) - && !connectedGroups[captain[edge.to]].contains(edge.from)) { + if ( + !connectedGroups[captain[edge.from]].contains(edge.to) && + !connectedGroups[captain[edge.to]].contains(edge.from) + ) { // merge sets of the captains of each point connected by the edge - connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); + connectedGroups[captain[edge.from]].addAll( + connectedGroups[captain[edge.to]] + ); // update captains of the elements merged - connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); + connectedGroups[captain[edge.from]].forEach(i -> + captain[i] = captain[edge.from] + ); // add Edge to minimal graph addEdge(minGraph, edge.from, edge.to, edge.weight); // count how many elements have been merged diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java index 49b9a41e9768..90386230b95a 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java @@ -1,9 +1,9 @@ package com.thealgorithms.datastructures.graphs; -import java.util.List; -import java.util.Queue; import java.util.ArrayList; import java.util.LinkedList; +import java.util.List; +import java.util.Queue; /** * Implementation of a graph in a matrix form Also known as an adjacency matrix @@ -71,7 +71,9 @@ class AdjacencyMatrixGraph { public AdjacencyMatrixGraph(int givenNumberOfVertices) { this.setNumberOfVertices(givenNumberOfVertices); this.setNumberOfEdges(0); - this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); + this.setAdjacency( + new int[givenNumberOfVertices][givenNumberOfVertices] + ); for (int i = 0; i < givenNumberOfVertices; i++) { for (int j = 0; j < givenNumberOfVertices; j++) { this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; @@ -101,7 +103,7 @@ public int numberOfVertices() { * Updates the number of edges in the graph * * @param newNumberOfEdges - * + * */ private void setNumberOfEdges(int newNumberOfEdges) { this._numberOfEdges = newNumberOfEdges; @@ -249,7 +251,11 @@ public List depthFirstOrder(int startVertex) { * has been visited * @param orderList the list to add vertices to as they are visited */ - private void depthFirstOrder(int currentVertex, boolean[] visited, List orderList) { + private void depthFirstOrder( + int currentVertex, + boolean[] visited, + List orderList + ) { // If this vertex has already been visited, do nothing and return if (visited[currentVertex]) { return; @@ -262,9 +268,11 @@ private void depthFirstOrder(int currentVertex, boolean[] visited, List // Get the adjacency array for this vertex int[] adjacent = _adjacency[currentVertex]; - for (int i = 0; i < adjacent.length; i++) // If an edge exists between the currentVertex and the vertex - // we are considering exploring, recurse on it - { + for ( + int i = 0; + i < adjacent.length; + i++ + ) { // we are considering exploring, recurse on it // If an edge exists between the currentVertex and the vertex if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) { depthFirstOrder(i, visited, orderList); } @@ -310,12 +318,14 @@ public List breadthFirstOrder(int startVertex) { orderList.add(currentVertex); visited[currentVertex] = true; - // Get the adjacency array for the currentVertex and + // Get the adjacency array for the currentVertex and // check each node int[] adjacent = _adjacency[currentVertex]; - for (int vertex = 0; vertex < adjacent.length; vertex++) // If an edge exists between the current vertex and the - // vertex we are considering exploring, we add it to the queue - { + for ( + int vertex = 0; + vertex < adjacent.length; + vertex++ + ) { // vertex we are considering exploring, we add it to the queue // If an edge exists between the current vertex and the if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) { queue.add(vertex); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java index 80bb1025a4b9..4365f721436f 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java @@ -5,6 +5,7 @@ * matrix representation of the graph */ class PrimMST { + // Number of vertices in the graph private static final int V = 5; @@ -30,7 +31,9 @@ int minKey(int key[], Boolean mstSet[]) { void printMST(int parent[], int n, int graph[][]) { System.out.println("Edge Weight"); for (int i = 1; i < V; i++) { - System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]); + System.out.println( + parent[i] + " - " + i + " " + graph[i][parent[i]] + ); } } @@ -69,11 +72,17 @@ void primMST(int graph[][]) { // Update key value and parent index of the adjacent // vertices of the picked vertex. Consider only those // vertices which are not yet included in MST - for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m - // mstSet[v] is false for vertices not yet included in MST - // Update the key only if graph[u][v] is smaller than key[v] + for ( + int v = 0; + v < V; + v++ + ) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m { - if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { + if ( + graph[u][v] != 0 && + mstSet[v] == false && + graph[u][v] < key[v] + ) { parent[v] = u; key[v] = graph[u][v]; } @@ -94,9 +103,13 @@ public static void main(String[] args) { (3)-------(4) 9 */ PrimMST t = new PrimMST(); - int graph[][] - = new int[][]{ - {0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0},}; + int graph[][] = new int[][] { + { 0, 2, 0, 6, 0 }, + { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, + { 6, 8, 0, 0, 9 }, + { 0, 5, 7, 9, 0 }, + }; // Print the solution t.primMST(graph); diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java index 5b20e56f3123..5a1ab7b6174b 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java @@ -5,6 +5,7 @@ // implementation of generic hashmaps using array of Linked Lists public class GenericHashMapUsingArray { + private int size; // n (total number of key-value pairs) private LinkedList[] buckets; // N = buckets.length private float lf = 0.75f; @@ -13,6 +14,7 @@ public GenericHashMapUsingArray() { initBuckets(16); size = 0; } + // load factor = 0.75 means if we need to add 100 items and we have added // 75, then adding 76th item it will double the size, copy all elements // & then add 76th item. @@ -114,6 +116,7 @@ public boolean containsKey(K key) { } public class Node { + K key; V value; diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java index 1702b3b28e2f..e45d827afec7 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java @@ -4,6 +4,7 @@ import java.util.LinkedList; public class GenericHashMapUsingArrayList { + ArrayList> buckets; private float lf = 0.5f; private int size; @@ -100,6 +101,7 @@ public String toString() { } private class Node { + K key; V val; @@ -108,5 +110,4 @@ public Node(K key, V val) { this.val = val; } } - } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java index eeb018577f7e..a7f1cbf14b37 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -1,6 +1,5 @@ package com.thealgorithms.datastructures.hashmap.hashing; - import java.lang.Math; import java.util.Objects; @@ -71,19 +70,26 @@ public void insertKey2HashTable(int key) { int hash, loopCounter = 0; if (isFull()) { - System.out.println("Hash table is full, lengthening & rehashing table"); + System.out.println( + "Hash table is full, lengthening & rehashing table" + ); reHashTableIncreasesTableSize(); } if (checkTableContainsKey(key)) { - throw new IllegalArgumentException("Key already inside, no duplicates allowed"); + throw new IllegalArgumentException( + "Key already inside, no duplicates allowed" + ); } while (loopCounter <= thresh) { loopCounter++; hash = hashFunction1(key); - if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) { + if ( + (buckets[hash] == null) || + Objects.equals(buckets[hash], AVAILABLE) + ) { buckets[hash] = wrappedInt; size++; checkLoadFactor(); @@ -110,7 +116,9 @@ public void insertKey2HashTable(int key) { buckets[hash] = wrappedInt; wrappedInt = temp; } - System.out.println("Infinite loop occurred, lengthening & rehashing table"); + System.out.println( + "Infinite loop occurred, lengthening & rehashing table" + ); reHashTableIncreasesTableSize(); insertKey2HashTable(key); } @@ -132,7 +140,6 @@ public void reHashTableIncreasesTableSize() { this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2; } - /** * deletes a key from the hash map and adds an available placeholder * @@ -157,7 +164,9 @@ public void deleteKeyFromHashTable(int key) { size--; return; } - throw new IllegalArgumentException("Key " + key + " already inside, no duplicates allowed"); + throw new IllegalArgumentException( + "Key " + key + " already inside, no duplicates allowed" + ); } /** @@ -168,7 +177,9 @@ public void displayHashtable() { if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) { System.out.println("Bucket " + i + ": Empty"); } else { - System.out.println("Bucket " + i + ": " + buckets[i].toString()); + System.out.println( + "Bucket " + i + ": " + buckets[i].toString() + ); } } System.out.println(); @@ -191,20 +202,32 @@ public int findKeyInTable(int key) { if (Objects.equals(buckets[hash], wrappedInt)) return hash; hash = hashFunction2(key); - if (!Objects.equals(buckets[hash], wrappedInt)) - throw new IllegalArgumentException("Key " + key + " not found in table"); - else { + if ( + !Objects.equals(buckets[hash], wrappedInt) + ) throw new IllegalArgumentException( + "Key " + key + " not found in table" + ); else { return hash; } } + /** * checks if key is inside without any output other than returned boolean. * * @param key the desired key to be found * @return int the index where the key is located */ - public boolean checkTableContainsKey(int key){ - return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key)); + public boolean checkTableContainsKey(int key) { + return ( + ( + buckets[hashFunction1(key)] != null && + buckets[hashFunction1(key)].equals(key) + ) || + ( + buckets[hashFunction2(key)] != null && + buckets[hashFunction2(key)] == key + ) + ); } /** @@ -214,7 +237,10 @@ public boolean checkTableContainsKey(int key){ public double checkLoadFactor() { double factor = (double) size / tableSize; if (factor > .7) { - System.out.printf("Load factor is %.2f , rehashing table\n", factor); + System.out.printf( + "Load factor is %.2f , rehashing table\n", + factor + ); reHashTableIncreasesTableSize(); } return factor; @@ -250,5 +276,8 @@ public boolean isEmpty() { } return response; } - public int getNumberOfKeysInTable(){return size;} + + public int getNumberOfKeysInTable() { + return size; + } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapLinearProbing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapLinearProbing.java index 8d950311e18b..c8ed333a5595 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapLinearProbing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapLinearProbing.java @@ -107,7 +107,9 @@ public void displayHashtable() { if (buckets[i] == null || buckets[i] == AVAILABLE) { System.out.println("Bucket " + i + ": Empty"); } else { - System.out.println("Bucket " + i + ": " + buckets[i].toString()); + System.out.println( + "Bucket " + i + ": " + buckets[i].toString() + ); } } } @@ -133,8 +135,7 @@ public int findHash(int key) { buckets[hash] = AVAILABLE; return hash; } - } catch (Exception E) { - } + } catch (Exception E) {} if (hash + 1 < hsize) { hash++; @@ -159,7 +160,9 @@ private void lengthenTable() { public void checkLoadFactor() { double factor = (double) size / hsize; if (factor > .7) { - System.out.println("Load factor is " + factor + ", lengthening table"); + System.out.println( + "Load factor is " + factor + ", lengthening table" + ); lengthenTable(); } else { System.out.println("Load factor is " + factor); diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java index b10c3c874a51..f89f9204299b 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java @@ -15,7 +15,9 @@ public class Intersection { public static List intersection(int[] arr1, int[] arr2) { - if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) { + if ( + arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0 + ) { return Collections.emptyList(); } Map cnt = new HashMap<>(16); @@ -32,7 +34,5 @@ public static List intersection(int[] arr1, int[] arr2) { return res; } - private Intersection() { - - } + private Intersection() {} } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java index 7a2a54ae6d3e..f6aa18b4c60b 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java @@ -5,7 +5,6 @@ public class Main { public static void main(String[] args) { - int choice, key; HashMap h = new HashMap(7); @@ -21,27 +20,31 @@ public static void main(String[] args) { choice = In.nextInt(); switch (choice) { - case 1: { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertHash(key); - break; - } - case 2: { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteHash(key); - break; - } - case 3: { - System.out.println("Print table"); - h.displayHashtable(); - break; - } - case 4: { - In.close(); - return; - } + case 1: + { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertHash(key); + break; + } + case 2: + { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteHash(key); + break; + } + case 3: + { + System.out.println("Print table"); + h.displayHashtable(); + break; + } + case 4: + { + In.close(); + return; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java index d38ff7d0cc36..90ff839c7ce1 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java @@ -3,8 +3,8 @@ import java.util.Scanner; public class MainCuckooHashing { - public static void main(String[] args) { + public static void main(String[] args) { int choice, key; HashMapCuckooHashing h = new HashMapCuckooHashing(7); @@ -24,41 +24,59 @@ public static void main(String[] args) { choice = In.nextInt(); switch (choice) { - case 1: { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertKey2HashTable(key); - break; - } - case 2: { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteKeyFromHashTable(key); - break; - } - case 3: { - System.out.println("Print table:\n"); - h.displayHashtable(); - break; - } - case 4: { - In.close(); - return; - } - case 5: { - System.out.println("Enter the Key to find and print: "); - key = In.nextInt(); - System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n"); - break; - } - case 6: { - System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor()); - break; - } - case 7: { - h.reHashTableIncreasesTableSize(); - break; - } + case 1: + { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertKey2HashTable(key); + break; + } + case 2: + { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteKeyFromHashTable(key); + break; + } + case 3: + { + System.out.println("Print table:\n"); + h.displayHashtable(); + break; + } + case 4: + { + In.close(); + return; + } + case 5: + { + System.out.println( + "Enter the Key to find and print: " + ); + key = In.nextInt(); + System.out.println( + "Key: " + + key + + " is at index: " + + h.findKeyInTable(key) + + "\n" + ); + break; + } + case 6: + { + System.out.printf( + "Load factor is: %.2f\n", + h.checkLoadFactor() + ); + break; + } + case 7: + { + h.reHashTableIncreasesTableSize(); + break; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainLinearProbing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainLinearProbing.java index 1a987db59d27..bd75d171adf4 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainLinearProbing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainLinearProbing.java @@ -5,7 +5,6 @@ public class MainLinearProbing { public static void main(String[] args) { - int choice, key; HashMapLinearProbing h = new HashMapLinearProbing(7); @@ -23,37 +22,47 @@ public static void main(String[] args) { choice = In.nextInt(); switch (choice) { - case 1: { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertHash(key); - break; - } - case 2: { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteHash(key); - break; - } - case 3: { - System.out.println("Print table"); - h.displayHashtable(); - break; - } - case 4: { - In.close(); - return; - } - case 5: { - System.out.println("Enter the Key to find and print: "); - key = In.nextInt(); - System.out.println("Key: " + key + " is at index: " + h.findHash(key)); - break; - } - case 6: { - h.checkLoadFactor(); - break; - } + case 1: + { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertHash(key); + break; + } + case 2: + { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteHash(key); + break; + } + case 3: + { + System.out.println("Print table"); + h.displayHashtable(); + break; + } + case 4: + { + In.close(); + return; + } + case 5: + { + System.out.println( + "Enter the Key to find and print: " + ); + key = In.nextInt(); + System.out.println( + "Key: " + key + " is at index: " + h.findHash(key) + ); + break; + } + case 6: + { + h.checkLoadFactor(); + break; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index 2236f6741fd1..3359ccb5e70c 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -1,6 +1,5 @@ package com.thealgorithms.datastructures.heaps; - public class FibonacciHeap { private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2; @@ -48,7 +47,7 @@ public boolean empty() { * $ret = the HeapNode we inserted */ public HeapNode insert(int key) { - HeapNode toInsert = new HeapNode(key); //creates the node + HeapNode toInsert = new HeapNode(key); //creates the node if (this.empty()) { this.min = toInsert; } else { //tree is not empty @@ -142,9 +141,12 @@ public int size() { */ public int[] countersRep() { if (this.empty()) { - return new int[0]; ///return an empty array + return new int[0]; ///return an empty array } - int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; //creates the array + int[] rankArray = new int[(int) Math.floor( + Math.log(this.size()) / Math.log(GOLDEN_RATIO) + ) + + 1]; //creates the array rankArray[this.min.rank]++; HeapNode curr = this.min.next; while (curr != this.min) { @@ -161,8 +163,8 @@ public int[] countersRep() { * @post (numOfnodes = = $prev numOfnodes - 1) */ public void delete(HeapNode x) { - this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1) - this.deleteMin(); //delete it + this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1) + this.deleteMin(); //delete it } /** @@ -174,7 +176,7 @@ public void delete(HeapNode x) { private void decreaseKey(HeapNode x, int delta) { int newKey = x.getKey() - delta; x.key = newKey; - if (x.isRoot()) {//no parent to x + if (x.isRoot()) { //no parent to x this.updateMin(x); return; } @@ -229,7 +231,7 @@ private void updateMin(HeapNode posMin) { * @post (numOfnodes == $prev numOfnodes) */ private void cascadingCuts(HeapNode curr) { - if (!curr.isMarked()) { //stop the recursion + if (!curr.isMarked()) { //stop the recursion curr.mark(); if (!curr.isRoot()) this.markedHeapNoodesCounter++; return; @@ -257,7 +259,7 @@ private void cut(HeapNode curr) { if (curr.parent.child == curr) { //we should change the parent's child if (curr.next == curr) { //curr do not have brothers curr.parent.child = null; - } else {//curr have brothers + } else { //curr have brothers curr.parent.child = curr.next; } } @@ -272,7 +274,6 @@ private void cut(HeapNode curr) { totalCuts++; } - /* * */ @@ -285,7 +286,10 @@ private void successiveLink(HeapNode curr) { * */ private HeapNode[] toBuckets(HeapNode curr) { - HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; + HeapNode[] buckets = new HeapNode[(int) Math.floor( + Math.log(this.size()) / Math.log(GOLDEN_RATIO) + ) + + 1]; curr.prev.next = null; HeapNode tmpCurr; while (curr != null) { @@ -347,7 +351,6 @@ private HeapNode link(HeapNode c1, HeapNode c2) { return c1; } - /** * public class HeapNode * each HeapNode belongs to a heap (Inner class) @@ -381,7 +384,6 @@ public int getKey() { return this.key; } - /* * checks whether the node is marked * $ret = true if one child has been cut @@ -397,7 +399,7 @@ private boolean isMarked() { private void mark() { if (this.isRoot()) { return; - } //check if the node is a root + } //check if the node is a root this.marked = true; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java index 194b0cd18798..2ceb86a727e9 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java @@ -2,70 +2,88 @@ import java.util.*; -public class GenericHeap >{ - ArrayList data=new ArrayList<>(); - HashMap map=new HashMap<>(); - public void add(T item) { - this.data.add(item); - map.put(item,this.data.size()-1);// - upHeapify(this.data.size()-1); - } - private void upHeapify(int ci) { - int pi=(ci-1)/2; - if(isLarger(this.data.get(ci),this.data.get(pi))>0) { - swap(pi,ci); - upHeapify(pi); - } - } - public void display() { - System.out.println(this.data); - } - public int size() { - return this.data.size(); - } - public boolean isEmpty() { - return this.size()==0; - } - public T remove() { - this.swap(0,this.size()-1); - T rv=this.data.remove(this.size()-1); - downHeapify(0); - map.remove(rv); - return rv; - } - private void downHeapify(int pi) { - int lci=2*pi+1; - int rci=2*pi+2; - int mini=pi; - if(lci0) { - mini=lci; - } - if(rci0) { - mini=rci; - } - if(mini!=pi) { - this.swap(pi,mini); - downHeapify(mini); - } - } - public T get() { - return this.data.get(0); - } - //t has higher property then return +ve - private int isLarger(T t,T o) { - return t.compareTo(o); - } - private void swap(int i,int j) { - T ith=this.data.get(i); - T jth=this.data.get(j); - this.data.set(i,jth); - this.data.set(j,ith); - map.put(ith,j); - map.put(jth,i); - } - public void updatePriority(T item) { - int index=map.get(item); - //because we enter lesser value then old vale - upHeapify(index); - } +public class GenericHeap> { + + ArrayList data = new ArrayList<>(); + HashMap map = new HashMap<>(); + + public void add(T item) { + this.data.add(item); + map.put(item, this.data.size() - 1); // + upHeapify(this.data.size() - 1); + } + + private void upHeapify(int ci) { + int pi = (ci - 1) / 2; + if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) { + swap(pi, ci); + upHeapify(pi); + } + } + + public void display() { + System.out.println(this.data); + } + + public int size() { + return this.data.size(); + } + + public boolean isEmpty() { + return this.size() == 0; + } + + public T remove() { + this.swap(0, this.size() - 1); + T rv = this.data.remove(this.size() - 1); + downHeapify(0); + map.remove(rv); + return rv; + } + + private void downHeapify(int pi) { + int lci = 2 * pi + 1; + int rci = 2 * pi + 2; + int mini = pi; + if ( + lci < this.size() && + isLarger(this.data.get(lci), this.data.get(mini)) > 0 + ) { + mini = lci; + } + if ( + rci < this.size() && + isLarger(this.data.get(rci), this.data.get(mini)) > 0 + ) { + mini = rci; + } + if (mini != pi) { + this.swap(pi, mini); + downHeapify(mini); + } + } + + public T get() { + return this.data.get(0); + } + + //t has higher property then return +ve + private int isLarger(T t, T o) { + return t.compareTo(o); + } + + private void swap(int i, int j) { + T ith = this.data.get(i); + T jth = this.data.get(j); + this.data.set(i, jth); + this.data.set(j, ith); + map.put(ith, j); + map.put(jth, i); + } + + public void updatePriority(T item) { + int index = map.get(item); + //because we enter lesser value then old vale + upHeapify(index); + } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java index da0795158cb3..63e101d9b13d 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java @@ -19,7 +19,6 @@ * @author Nicolas Renard */ public interface Heap { - /** * @return the top element in the heap, the one with lowest key for min-heap * or with the highest key for max-heap diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index 5d31a2bdc0a4..bf095706a5a5 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -122,8 +122,10 @@ public boolean equals(Object o) { return false; } HeapElement otherHeapElement = (HeapElement) o; - return (this.key == otherHeapElement.key) - && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); + return ( + (this.key == otherHeapElement.key) && + (this.additionalInfo.equals(otherHeapElement.additionalInfo)) + ); } return false; } @@ -132,7 +134,10 @@ public boolean equals(Object o) { public int hashCode() { int result = 0; result = 31 * result + (int) key; - result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); + result = + 31 * + result + + (additionalInfo != null ? additionalInfo.hashCode() : 0); return result; } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index e19d4c718702..64731fd2f5ba 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -46,7 +46,7 @@ private double getElementKey(int elementIndex) { if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) { throw new IndexOutOfBoundsException("Index out of heap range"); } - + return maxHeap.get(elementIndex - 1).getKey(); } @@ -70,22 +70,30 @@ private void toggleUp(int elementIndex) { // than any of its children's private void toggleDown(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder - = (key < getElementKey(elementIndex * 2)) - || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + boolean wrongOrder = + (key < getElementKey(elementIndex * 2)) || + (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { // Check whether it shall swap the element with its left child or its right one if any. - if ((2 * elementIndex < maxHeap.size()) - && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { + if ( + (2 * elementIndex < maxHeap.size()) && + ( + getElementKey(elementIndex * 2 + 1) > + getElementKey(elementIndex * 2) + ) + ) { swap(elementIndex, 2 * elementIndex + 1); elementIndex = 2 * elementIndex + 1; } else { swap(elementIndex, 2 * elementIndex); elementIndex = 2 * elementIndex; } - wrongOrder - = (key < getElementKey(elementIndex * 2)) - || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + wrongOrder = + (key < getElementKey(elementIndex * 2)) || + ( + key < + getElementKey(Math.min(elementIndex * 2, maxHeap.size())) + ); } } @@ -103,9 +111,10 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (maxHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + if (maxHeap.isEmpty()) try { + throw new EmptyHeapException( + "Attempt to delete an element from an empty heap" + ); } catch (EmptyHeapException e) { e.printStackTrace(); } @@ -116,13 +125,22 @@ public void deleteElement(int elementIndex) { maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); maxHeap.remove(maxHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) { + if ( + getElementKey(elementIndex) > + getElementKey((int) Math.floor(elementIndex / 2.0)) + ) { toggleUp(elementIndex); } // ... or down ? - else if (((2 * elementIndex <= maxHeap.size()) - && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) - || ((2 * elementIndex < maxHeap.size()) - && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) { + else if ( + ( + (2 * elementIndex <= maxHeap.size()) && + (getElementKey(elementIndex) < getElementKey(elementIndex * 2)) + ) || + ( + (2 * elementIndex < maxHeap.size()) && + (getElementKey(elementIndex) < getElementKey(elementIndex * 2)) + ) + ) { toggleDown(elementIndex); } } @@ -132,7 +150,9 @@ public HeapElement getElement() throws EmptyHeapException { try { return extractMax(); } catch (Exception e) { - throw new EmptyHeapException("Heap is empty. Error retrieving element"); + throw new EmptyHeapException( + "Heap is empty. Error retrieving element" + ); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index 6d5d6870ce8c..a28a8e5f1cf9 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -40,7 +40,7 @@ private double getElementKey(int elementIndex) { if ((elementIndex <= 0) || (elementIndex > minHeap.size())) { throw new IndexOutOfBoundsException("Index out of heap range"); } - + return minHeap.get(elementIndex - 1).getKey(); } @@ -64,22 +64,30 @@ private void toggleUp(int elementIndex) { // than any of its children's private void toggleDown(int elementIndex) { double key = minHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder - = (key > getElementKey(elementIndex * 2)) - || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + boolean wrongOrder = + (key > getElementKey(elementIndex * 2)) || + (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { // Check whether it shall swap the element with its left child or its right one if any. - if ((2 * elementIndex < minHeap.size()) - && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) { + if ( + (2 * elementIndex < minHeap.size()) && + ( + getElementKey(elementIndex * 2 + 1) < + getElementKey(elementIndex * 2) + ) + ) { swap(elementIndex, 2 * elementIndex + 1); elementIndex = 2 * elementIndex + 1; } else { swap(elementIndex, 2 * elementIndex); elementIndex = 2 * elementIndex; } - wrongOrder - = (key > getElementKey(elementIndex * 2)) - || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + wrongOrder = + (key > getElementKey(elementIndex * 2)) || + ( + key > + getElementKey(Math.min(elementIndex * 2, minHeap.size())) + ); } } @@ -97,9 +105,10 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (minHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + if (minHeap.isEmpty()) try { + throw new EmptyHeapException( + "Attempt to delete an element from an empty heap" + ); } catch (EmptyHeapException e) { e.printStackTrace(); } @@ -110,13 +119,22 @@ public void deleteElement(int elementIndex) { minHeap.set(elementIndex - 1, getElement(minHeap.size())); minHeap.remove(minHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) { + if ( + getElementKey(elementIndex) < + getElementKey((int) Math.floor(elementIndex / 2.0)) + ) { toggleUp(elementIndex); } // ... or down ? - else if (((2 * elementIndex <= minHeap.size()) - && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) - || ((2 * elementIndex < minHeap.size()) - && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) { + else if ( + ( + (2 * elementIndex <= minHeap.size()) && + (getElementKey(elementIndex) > getElementKey(elementIndex * 2)) + ) || + ( + (2 * elementIndex < minHeap.size()) && + (getElementKey(elementIndex) > getElementKey(elementIndex * 2)) + ) + ) { toggleDown(elementIndex); } } @@ -126,7 +144,9 @@ public HeapElement getElement() throws EmptyHeapException { try { return extractMin(); } catch (Exception e) { - throw new EmptyHeapException("Heap is empty. Error retrieving element"); + throw new EmptyHeapException( + "Heap is empty. Error retrieving element" + ); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java index 114159234aab..034e32ce9481 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java @@ -88,7 +88,10 @@ private void sink() { while (2 * k <= this.size || 2 * k + 1 <= this.size) { int minIndex; if (this.heap[2 * k] >= this.heap[k]) { - if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { + if ( + 2 * k + 1 <= this.size && + this.heap[2 * k + 1] >= this.heap[k] + ) { break; } else if (2 * k + 1 > this.size) { break; @@ -97,8 +100,14 @@ private void sink() { if (2 * k + 1 > this.size) { minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; } else { - if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { - minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; + if ( + this.heap[k] > this.heap[2 * k] || + this.heap[k] > this.heap[2 * k + 1] + ) { + minIndex = + this.heap[2 * k] < this.heap[2 * k + 1] + ? 2 * k + : 2 * k + 1; } else { minIndex = k; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java index d2303c0ff173..f5edc6c09811 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java @@ -38,7 +38,9 @@ public int getSize() { public void append(E value) { if (value == null) { // we do not want to add null elements to the list. - throw new NullPointerException("Cannot add null element to the list"); + throw new NullPointerException( + "Cannot add null element to the list" + ); } // head.next points to the last element; if (tail == null) { @@ -57,7 +59,7 @@ public String toString() { String s = "[ "; while (p != head) { s += p.value; - if (p != tail){ + if (p != tail) { s += " , "; } p = p.next; @@ -68,7 +70,9 @@ public String toString() { public E remove(int pos) { if (pos > size || pos < 0) { // catching errors - throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); + throw new IndexOutOfBoundsException( + "position cannot be greater than size or negative" + ); } // we need to keep track of the element before the element we want to remove we can see why // bellow. diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java index ac3724406798..182c8f75fe55 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java @@ -33,15 +33,14 @@ static void createLoop(Node head, int k) { } Node temp = head; int count = 1; - while (count < k) { // Traverse the list till the kth node + while (count < k) { // Traverse the list till the kth node temp = temp.next; count++; } Node connectedPoint = temp; - while (temp.next != null) // Traverse remaining nodes - { + while (temp.next != null) { // Traverse remaining nodes temp = temp.next; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java index b0149feccdd7..b3ad535c7121 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java @@ -46,12 +46,9 @@ public CursorLinkedList() { } public void printList() { - if (head != -1) { - int start = head; while (start != -1) { - T element = cursorSpace[start].element; System.out.println(element.toString()); start = cursorSpace[start].next; @@ -64,7 +61,6 @@ public void printList() { * index of the [cursorSpace] array */ public int indexOf(T element) { - Objects.requireNonNull(element); Node iterator = cursorSpace[head]; for (int i = 0; i < count; i++) { @@ -84,13 +80,10 @@ public int indexOf(T element) { * @return */ public T get(int position) { - if (position >= 0 && position < count) { - int start = head; int counter = 0; while (start != -1) { - T element = cursorSpace[start].element; if (counter == position) { return element; @@ -105,16 +98,13 @@ public T get(int position) { } public void removeByIndex(int index) { - if (index >= 0 && index < count) { - T element = get(index); remove(element); } } public void remove(T element) { - Objects.requireNonNull(element); // case element is in the head @@ -124,15 +114,14 @@ public void remove(T element) { free(head); head = temp_next; } else { // otherwise cases - int prev_index = head; int current_index = cursorSpace[prev_index].next; while (current_index != -1) { - T current_element = cursorSpace[current_index].element; if (current_element.equals(element)) { - cursorSpace[prev_index].next = cursorSpace[current_index].next; + cursorSpace[prev_index].next = + cursorSpace[current_index].next; free(current_index); break; } @@ -146,7 +135,6 @@ public void remove(T element) { } private void free(int index) { - Node os_node = cursorSpace[os]; int os_next = os_node.next; cursorSpace[os].next = index; @@ -155,7 +143,6 @@ private void free(int index) { } public void append(T element) { - Objects.requireNonNull(element); int availableIndex = alloc(); cursorSpace[availableIndex].element = element; @@ -179,7 +166,6 @@ public void append(T element) { * @return the index of the next available node */ private int alloc() { - // 1- get the index at which the os is pointing int availableNodeIndex = cursorSpace[os].next; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 36b026a161b5..88f762ba56e6 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -53,7 +53,7 @@ public DoublyLinkedList(int[] array) { throw new NullPointerException(); } for (int i : array) { - linkOperations.insertTail(i,this); + linkOperations.insertTail(i, this); } size = array.length; } @@ -136,13 +136,13 @@ public void displayLink() { public static void main(String args[]) { DoublyLinkedList myList = new DoublyLinkedList(); LinkOperations linkOperations = new LinkOperations(); - linkOperations.insertHead(13,myList); - linkOperations.insertHead(7,myList); - linkOperations.insertHead(10,myList); + linkOperations.insertHead(13, myList); + linkOperations.insertHead(7, myList); + linkOperations.insertHead(10, myList); myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> myList.displayBackwards(); - linkOperations.insertTail(11,myList); + linkOperations.insertTail(11, myList); myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> myList.displayBackwards(); @@ -154,11 +154,11 @@ public static void main(String args[]) { myList.display(); // <-- 10(head) <--> 13(tail) --> myList.displayBackwards(); - linkOperations.insertOrdered(23,myList); - linkOperations.insertOrdered(67,myList); - linkOperations.insertOrdered(3,myList); + linkOperations.insertOrdered(23, myList); + linkOperations.insertOrdered(67, myList); + linkOperations.insertOrdered(3, myList); myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> - linkOperations.insertElementByIndex(5, 1,myList); + linkOperations.insertElementByIndex(5, 1, myList); myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) --> myList.displayBackwards(); linkOperations.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) --> @@ -167,7 +167,7 @@ public static void main(String args[]) { linkOperations.clearList(); myList.display(); myList.displayBackwards(); - linkOperations.insertHead(20,myList); + linkOperations.insertHead(20, myList); myList.display(); myList.displayBackwards(); } @@ -176,7 +176,8 @@ public static void main(String args[]) { /* * This class implements the operations of the Link nodes. */ -class LinkOperations{ +class LinkOperations { + /** * Head refers to the front of the list */ @@ -196,10 +197,9 @@ class LinkOperations{ * * @param x Element to be inserted */ - public void insertHead(int x,DoublyLinkedList doublyLinkedList) { + public void insertHead(int x, DoublyLinkedList doublyLinkedList) { Link newLink = new Link(x); // Create a new link with a value attached to it - if (doublyLinkedList.isEmpty()) // Set the first element added to be the tail - { + if (doublyLinkedList.isEmpty()) { // Set the first element added to be the tail tail = newLink; } else { head.previous = newLink; // newLink <-- currenthead(head) @@ -214,7 +214,7 @@ public void insertHead(int x,DoublyLinkedList doublyLinkedList) { * * @param x Element to be inserted */ - public void insertTail(int x,DoublyLinkedList doublyLinkedList) { + public void insertTail(int x, DoublyLinkedList doublyLinkedList) { Link newLink = new Link(x); newLink.next = null; // currentTail(tail) newlink --> if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element @@ -234,15 +234,21 @@ public void insertTail(int x,DoublyLinkedList doublyLinkedList) { * @param x Element to be inserted * @param index Index(from start) at which the element x to be inserted */ - public void insertElementByIndex(int x, int index,DoublyLinkedList doublyLinkedList) { + public void insertElementByIndex( + int x, + int index, + DoublyLinkedList doublyLinkedList + ) { if (index > size) { - throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + throw new IndexOutOfBoundsException( + "Index: " + index + ", Size: " + size + ); } if (index == 0) { - insertHead(x,doublyLinkedList); + insertHead(x, doublyLinkedList); } else { if (index == size) { - insertTail(x,doublyLinkedList); + insertTail(x, doublyLinkedList); } else { Link newLink = new Link(x); Link previousLink = head; // @@ -271,8 +277,7 @@ public Link deleteHead() { if (head == null) { tail = null; } else { - head.previous - = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed } --size; return temp; @@ -309,7 +314,9 @@ public void delete(int x) { if (current != tail) { current = current.next; } else { // If we reach the tail and the element is still not found - throw new RuntimeException("The element to be deleted does not exist!"); + throw new RuntimeException( + "The element to be deleted does not exist!" + ); } } @@ -329,18 +336,17 @@ public void delete(int x) { * * @param x Element to be added */ - public void insertOrdered(int x,DoublyLinkedList doublyLinkedList) { + public void insertOrdered(int x, DoublyLinkedList doublyLinkedList) { Link newLink = new Link(x); Link current = head; - while (current != null && x > current.value) // Find the position to insert - { + while (current != null && x > current.value) { // Find the position to insert current = current.next; } if (current == head) { - insertHead(x,doublyLinkedList); + insertHead(x, doublyLinkedList); } else if (current == null) { - insertTail(x,doublyLinkedList); + insertTail(x, doublyLinkedList); } else { // Before: 1 <--> 2(current) <--> 3 newLink.previous = current.previous; // 1 <-- newLink current.previous.next = newLink; // 1 <--> newLink @@ -372,8 +378,7 @@ public void removeDuplicates(DoublyLinkedList l) { while (linkOne.next != null) { // list is present Link linkTwo = linkOne.next; // second link for comparison while (linkTwo.next != null) { - if (linkOne.value == linkTwo.value) // if there are duplicates values then - { + if (linkOne.value == linkTwo.value) { // if there are duplicates values then delete(linkTwo.value); // delete the link } linkTwo = linkTwo.next; // go to next link @@ -416,5 +421,4 @@ public void clearList() { tail = null; size = 0; } - } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java index 80b36b8e4ab1..f9a80d984cc7 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java @@ -36,7 +36,11 @@ public static void main(String[] args) { * @param listB the second list to merge * @param listC the result list after merging */ - public static void merge(List listA, List listB, List listC) { + public static void merge( + List listA, + List listB, + List listC + ) { int pa = 0; /* the index of listA */ int pb = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java index 2bee945c9db6..4ea0127f4ae0 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java @@ -12,7 +12,9 @@ public static void main(String[] args) { } assert listA.toString().equals("2->4->6->8->10"); assert listB.toString().equals("1->3->5->7->9"); - assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); + assert merge(listA, listB) + .toString() + .equals("1->2->3->4->5->6->7->8->9->10"); } /** @@ -22,7 +24,10 @@ public static void main(String[] args) { * @param listB the second sored list * @return merged sorted list */ - public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { + public static SinglyLinkedList merge( + SinglyLinkedList listA, + SinglyLinkedList listB + ) { Node headA = listA.getHead(); Node headB = listB.getHead(); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java index 9a06b4a6587f..840b935ef84a 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java @@ -18,7 +18,9 @@ public class Merge_K_SortedLinkedlist { */ Node mergeKList(Node[] a, int N) { // Min Heap - PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); + PriorityQueue min = new PriorityQueue<>( + Comparator.comparingInt(x -> x.data) + ); // adding head of all linkedList in min heap min.addAll(Arrays.asList(a).subList(0, N)); @@ -30,7 +32,6 @@ Node mergeKList(Node[] a, int N) { // merging LinkedList while (!min.isEmpty()) { - Node temp = min.poll(); curr.next = temp; curr = temp; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java index 72cacab4331f..e173da2fb4f7 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java @@ -22,7 +22,6 @@ * Step 7 : STOP */ - package com.thealgorithms.datastructures.lists; import java.util.ArrayList; @@ -30,11 +29,13 @@ import java.util.Random; public class RandomNode { + private List list; private int size; private static Random rand = new Random(); static class ListNode { + int val; ListNode next; @@ -74,8 +75,6 @@ public static void main(String[] args) { System.out.println("Random Node : " + randomNum); } } - - /** * OUTPUT : * First output : @@ -87,7 +86,6 @@ public static void main(String[] args) { * Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ - /** Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java index c6e38cebdcb3..bd3dd51ba39a 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java @@ -23,7 +23,10 @@ public static void main(String[] args) { * {@code false}. */ private boolean searchRecursion(Node node, int key) { - return node != null && (node.value == key || searchRecursion(node.next, key)); + return ( + node != null && + (node.value == key || searchRecursion(node.next, key)) + ); } @Override diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java index 0ab65b8496b8..acb17923c1ea 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java @@ -5,7 +5,7 @@ /** * https://en.wikipedia.org/wiki/Linked_list */ -public class SinglyLinkedList extends Node{ +public class SinglyLinkedList extends Node { /** * Head refer to the front of the list @@ -56,42 +56,40 @@ public boolean detectLoop() { /** * Swaps nodes of two given values a and b. - * + * */ public void swapNodes(int valueFirst, int valueSecond) { - if(valueFirst == valueSecond){ + if (valueFirst == valueSecond) { return; } - Node previousA = null ,currentA = head; - while(currentA != null && currentA.value != valueFirst){ + Node previousA = null, currentA = head; + while (currentA != null && currentA.value != valueFirst) { previousA = currentA; currentA = currentA.next; } - Node previousB = null ,currentB = head; - while(currentB != null && currentB.value != valueSecond){ + Node previousB = null, currentB = head; + while (currentB != null && currentB.value != valueSecond) { previousB = currentB; currentB = currentB.next; } /** If either of 'a' or 'b' is not present, then return */ - if(currentA == null || currentB == null){ + if (currentA == null || currentB == null) { return; } // If 'a' is not head node of list - if(previousA != null){ + if (previousA != null) { previousA.next = currentB; - } - else{ + } else { // make 'b' as the new head head = currentB; } // If 'b' is not head node of list - if(previousB != null){ + if (previousB != null) { previousB.next = currentA; - } - else{ + } else { // Make 'a' as new head head = currentA; } @@ -108,7 +106,7 @@ public void swapNodes(int valueFirst, int valueSecond) { */ Node reverseList(Node node) { Node prevNode = head; - while(prevNode.next!=node){ + while (prevNode.next != node) { prevNode = prevNode.next; } Node prev = null, curr = node, next; @@ -216,7 +214,6 @@ public String toString() { } public void deleteDuplicates() { - Node pred = head; // predecessor = the node // having sublist of its duplicates @@ -226,13 +223,14 @@ public void deleteDuplicates() { // skip all duplicates if (newHead.next != null && newHead.value == newHead.next.value) { // move till the end of duplicates sublist - while (newHead.next != null && newHead.value == newHead.next.value) { + while ( + newHead.next != null && newHead.value == newHead.next.value + ) { newHead = newHead.next; } // skip all duplicates pred.next = newHead.next; newHead = null; - // otherwise, move predecessor } // move forward @@ -301,7 +299,6 @@ public void insertNth(int data, int position) { newNode.next = cur.next; cur.next = newNode; size++; - } /** @@ -375,6 +372,7 @@ public void checkBounds(int position, int low, int high) { throw new IndexOutOfBoundsException(position + ""); } } + /** * Driver Code */ @@ -393,10 +391,15 @@ public static void main(String[] arg) { assert list.toString().equals("10->7->5->3->1"); System.out.println(list.toString()); /* Test search function */ - assert list.search(10) && list.search(5) && list.search(1) && !list.search(100); + assert list.search(10) && + list.search(5) && + list.search(1) && + !list.search(100); /* Test get function */ - assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1; + assert list.getNth(0) == 10 && + list.getNth(2) == 5 && + list.getNth(4) == 1; /* Test delete function */ list.deleteHead(); @@ -419,13 +422,14 @@ public static void main(String[] arg) { } SinglyLinkedList instance = new SinglyLinkedList(); - Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4))))); + Node head = new Node( + 0, + new Node(2, new Node(3, new Node(3, new Node(4)))) + ); instance.setHead(head); instance.deleteDuplicates(); instance.print(); - } - } /** @@ -444,8 +448,7 @@ class Node { */ Node next; - Node() { - } + Node() {} /** * Constructor @@ -466,5 +469,4 @@ class Node { this.value = value; this.next = next; } - } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java index 259406e228ac..34efde769ed9 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java @@ -189,23 +189,25 @@ public String toString() { } Collections.reverse(layers); - String result = layers.stream() - .map(layer -> { - StringBuilder acc = new StringBuilder(); - for (boolean b : layer) { - if (b) { - acc.append("[ ]"); - } else { - acc.append("---"); - } - acc.append(" "); + String result = layers + .stream() + .map(layer -> { + StringBuilder acc = new StringBuilder(); + for (boolean b : layer) { + if (b) { + acc.append("[ ]"); + } else { + acc.append("---"); } - return acc.toString(); - }) - .collect(Collectors.joining("\n")); - String positions = IntStream.range(0, sizeWithHeader - 1) - .mapToObj(i -> String.format("%3d", i)) - .collect(Collectors.joining(" ")); + acc.append(" "); + } + return acc.toString(); + }) + .collect(Collectors.joining("\n")); + String positions = IntStream + .range(0, sizeWithHeader - 1) + .mapToObj(i -> String.format("%3d", i)) + .collect(Collectors.joining(" ")); return result + String.format("%n H %s%n", positions); } @@ -296,14 +298,18 @@ public BernoulliHeightStrategy() { public BernoulliHeightStrategy(double probability) { if (probability <= 0 || probability >= 1) { - throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability); + throw new IllegalArgumentException( + "Probability should be from 0 to 1. But was: " + probability + ); } this.probability = probability; } @Override public int height(int expectedSize) { - long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability)); + long height = Math.round( + Math.log10(expectedSize) / Math.log10(1 / probability) + ); if (height > Integer.MAX_VALUE) { throw new IllegalArgumentException(); } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java index f1e99e3c0e58..18293bffe077 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java @@ -69,7 +69,6 @@ public int deQueue() { } return res; } - } public int peek() { @@ -86,7 +85,6 @@ public void deleteQueue() { System.out.println("The Queue is deleted!"); } - public static void main(String[] args) { CircularQueue cq = new CircularQueue(5); System.out.println(cq.isEmpty()); @@ -110,6 +108,5 @@ public static void main(String[] args) { System.out.println(cq.peek()); System.out.println(cq.peek()); cq.deleteQueue(); - } } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java index cf651dcee359..d44fa30f9b6a 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -121,8 +121,7 @@ public static void main(String[] args) { // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top for (int i = 3; i >= 0; i--) { - System.out.print( - myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] + System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] } // As you can see, a Priority Queue can be used as a sorting algotithm } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java index d0342d53955e..2e2b572c1054 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java @@ -28,13 +28,16 @@ class BalancedBrackets { */ public static boolean isPaired(char leftBracket, char rightBracket) { char[][] pairedBrackets = { - {'(', ')'}, - {'[', ']'}, - {'{', '}'}, - {'<', '>'} + { '(', ')' }, + { '[', ']' }, + { '{', '}' }, + { '<', '>' }, }; for (char[] pairedBracket : pairedBrackets) { - if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { + if ( + pairedBracket[0] == leftBracket && + pairedBracket[1] == rightBracket + ) { return true; } } @@ -63,7 +66,10 @@ public static boolean isBalanced(String brackets) { case ')': case ']': case '}': - if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { + if ( + bracketsStack.isEmpty() || + !isPaired(bracketsStack.pop(), bracket) + ) { return false; } break; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java index 7af1192ad581..7a76c62e8964 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java @@ -8,6 +8,7 @@ import java.util.*; public class CalculateMaxOfMin { + public static int calculateMaxOfMin(int[] a) { int n = a.length; int[] ans = new int[n]; @@ -34,4 +35,4 @@ public static int calculateMaxOfMin(int[] a) { /** * Given an integer array. The task is to find the maximum of the minimum of the * given array - */ \ No newline at end of file + */ diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java index 1a71bf6928e3..28302793977a 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java @@ -24,10 +24,30 @@ public static void main(String[] args) { private static String convert(int number, int radix) { if (radix < 2 || radix > 16) { throw new ArithmeticException( - String.format("Invalid input -> number:%d,radius:%d", number, radix)); + String.format( + "Invalid input -> number:%d,radius:%d", + number, + radix + ) + ); } char[] tables = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', }; Stack bits = new Stack<>(); do { diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java index 4b86cb499aa3..d47f5b193077 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java @@ -2,7 +2,7 @@ // 1. You are given a string exp representing an expression. // 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other. -// 3. But, some of the pair of brackets maybe extra/needless. +// 3. But, some of the pair of brackets maybe extra/needless. // 4. You are required to print true if you detect extra brackets and false otherwise. // e.g.' // ((a + b) + (c + d)) -> false @@ -25,7 +25,6 @@ public static boolean check(String str) { } st.pop(); } - } else { st.push(ch); } @@ -40,5 +39,4 @@ public static void main(String[] args) throws Exception { System.out.println(check(str)); sc.close(); } - } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java index cb19249a5e5b..9df7330d808b 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java @@ -10,7 +10,8 @@ public static void main(String[] args) throws Exception { assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6")); } - public static String infix2PostFix(String infixExpression) throws Exception { + public static String infix2PostFix(String infixExpression) + throws Exception { if (!BalancedBrackets.isBalanced(infixExpression)) { throw new Exception("invalid expression"); } @@ -27,7 +28,10 @@ public static String infix2PostFix(String infixExpression) throws Exception { } stack.pop(); } else { - while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) { + while ( + !stack.isEmpty() && + precedence(element) <= precedence(stack.peek()) + ) { output.append(stack.pop()); } stack.push(element); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java index b4a41341f54e..9cc4f0f7035c 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java @@ -1,33 +1,36 @@ -package com.thealgorithms.datastructures.stacks; - -import java.util.Stack; - -/** - * - * @author mohd rameez github.com/rameez471 - */ - -public class LargestRectangle { - public static String largestRectanglehistogram(int[] heights) { - int n = heights.length, maxArea = 0; - Stack st = new Stack<>(); - for(int i=0;i heights[i]) { - int[] tmp = st.pop(); - maxArea = Math.max(maxArea, tmp[1]*(i - tmp[0])); - start = tmp[0]; - } - st.push(new int[]{start, heights[i]}); - } - while(!st.isEmpty()) { - int[] tmp = st.pop(); - maxArea = Math.max(maxArea, tmp[1]*(n-tmp[0])); - } - return Integer.toString(maxArea); - } - public static void main(String[] args) { - assert largestRectanglehistogram(new int[]{2, 1, 5, 6, 2, 3}).equals("10"); - assert largestRectanglehistogram(new int[]{2, 4}).equals("4"); - } -} +package com.thealgorithms.datastructures.stacks; + +import java.util.Stack; + +/** + * + * @author mohd rameez github.com/rameez471 + */ + +public class LargestRectangle { + + public static String largestRectanglehistogram(int[] heights) { + int n = heights.length, maxArea = 0; + Stack st = new Stack<>(); + for (int i = 0; i < n; i++) { + int start = i; + while (!st.isEmpty() && st.peek()[1] > heights[i]) { + int[] tmp = st.pop(); + maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0])); + start = tmp[0]; + } + st.push(new int[] { start, heights[i] }); + } + while (!st.isEmpty()) { + int[] tmp = st.pop(); + maxArea = Math.max(maxArea, tmp[1] * (n - tmp[0])); + } + return Integer.toString(maxArea); + } + + public static void main(String[] args) { + assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 }) + .equals("10"); + assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4"); + } +} diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java index 74090db6bf25..ecde496c031a 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java @@ -97,10 +97,9 @@ public static int[] calculateMaxOfMin(int[] arr, int n) { } public static void main(String args[]) { - int[] arr = new int[]{10, 20, 30, 50, 10, 70, 30}; - int[] target = new int[]{70, 30, 20, 10, 10, 10, 10}; + int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 }; + int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 }; int[] res = calculateMaxOfMin(arr, arr.length); assert Arrays.equals(target, res); } - } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java index df6375b70216..2497158a20bb 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java @@ -1,6 +1,8 @@ package com.thealgorithms.datastructures.stacks; + import java.util.Arrays; import java.util.Stack; + /* Given an array "input" you need to print the first grater element for each element. For a given element x of an array, the Next Grater element of that element is the @@ -38,11 +40,9 @@ Next Grater element between (6 to n) is -1 3. If elements are left in stack after completing while loop then their Next Grater element is -1. */ - public class NextGraterElement { - - public static int[] findNextGreaterElements(int[] array) { + public static int[] findNextGreaterElements(int[] array) { if (array == null) { return array; } @@ -60,8 +60,7 @@ public static int[] findNextGreaterElements(int[] array) { return result; } - public static void main(String[] args) - { + public static void main(String[] args) { int[] input = { 2, 7, 3, 5, 4, 6, 8 }; int[] result = findNextGreaterElements(input); System.out.println(Arrays.toString(result)); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java index f74d4ac52aed..6073d4819361 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java @@ -1,8 +1,8 @@ package com.thealgorithms.datastructures.stacks; + import java.util.Arrays; import java.util.Stack; - /* Given an array "input" you need to print the first smaller element for each element to the left side of an array. For a given element x of an array, the Next Smaller element of that element is the @@ -38,8 +38,8 @@ Next smaller element between (0 , 5) is 6 */ public class NextSmallerElement { - public static int[] findNextSmallerElements(int[] array) - { + + public static int[] findNextSmallerElements(int[] array) { // base case if (array == null) { return array; @@ -60,8 +60,7 @@ public static int[] findNextSmallerElements(int[] array) return result; } - public static void main(String[] args) - { + public static void main(String[] args) { int[] input = { 2, 7, 3, 5, 4, 6, 8 }; int[] result = findNextSmallerElements(input); System.out.println(Arrays.toString(result)); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java index a492a300ab29..b4ab7860ddd0 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java @@ -50,8 +50,7 @@ public static void main(String[] args) { /** * Constructors for the NodeStack. */ - public NodeStack() { - } + public NodeStack() {} private NodeStack(Item item) { this.data = item; @@ -63,7 +62,6 @@ private NodeStack(Item item) { * @param item : value to be put on the stack. */ public void push(Item item) { - NodeStack newNs = new NodeStack(item); if (this.isEmpty()) { @@ -85,7 +83,6 @@ public void push(Item item) { * @return item : value that is returned. */ public Item pop() { - Item item = (Item) NodeStack.head.getData(); NodeStack.head.setHead(NodeStack.head.getPrevious()); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java index de6fffa14d15..6b6ce7568fb0 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java @@ -18,11 +18,8 @@ public class PostfixToInfix { - - public static boolean isOperator(char token) - { - switch(token) - { + public static boolean isOperator(char token) { + switch (token) { case '+': case '-': case '/': @@ -34,43 +31,31 @@ public static boolean isOperator(char token) return false; } - - public static boolean isValidPostfixExpression(String postfix) - { + public static boolean isValidPostfixExpression(String postfix) { /* Postfix expression length should NOT be less than 3 */ - if(postfix.length() < 3) return false; - + if (postfix.length() < 3) return false; /* First two characters should NOT be operators */ - if(isOperator(postfix.charAt(0))) return false; - if(isOperator(postfix.charAt(1))) return false; - + if (isOperator(postfix.charAt(0))) return false; + if (isOperator(postfix.charAt(1))) return false; int operandCount = 0; int operatorCount = 0; - /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */ - for(int i = 0; i < postfix.length(); i++) - { + for (int i = 0; i < postfix.length(); i++) { char token = postfix.charAt(i); - if(isOperator(token)) - { + if (isOperator(token)) { operatorCount++; - if(operatorCount >= operandCount) return false; - } - - else - { - if(operatorCount == 0) - { + if (operatorCount >= operandCount) return false; + } else { + if (operatorCount == 0) { operandCount++; continue; } - if(operandCount != operatorCount + 1) return false; - + if (operandCount != operatorCount + 1) return false; /* Operand count is set to 2 because:- * @@ -81,7 +66,6 @@ public static boolean isValidPostfixExpression(String postfix) */ operandCount = 2; - /* Reset operator count */ operatorCount = 0; } @@ -90,17 +74,13 @@ public static boolean isValidPostfixExpression(String postfix) return (operandCount == operatorCount + 1); } - - public static String getPostfixToInfix(String postfix) - { + public static String getPostfixToInfix(String postfix) { String infix = ""; - if(postfix.isEmpty()) return infix; - + if (postfix.isEmpty()) return infix; /* Validate Postfix expression before proceeding with the Infix conversion */ - if(!isValidPostfixExpression(postfix)) - { + if (!isValidPostfixExpression(postfix)) { throw new IllegalArgumentException("Invalid Postfix Expression"); } @@ -110,13 +90,10 @@ public static String getPostfixToInfix(String postfix) String operandA, operandB; char operator; - - for(int index = 0; index < postfix.length(); index++) - { + for (int index = 0; index < postfix.length(); index++) { char token = postfix.charAt(index); - if(!isOperator(token)) - { + if (!isOperator(token)) { stack.push(Character.toString(token)); continue; } @@ -141,13 +118,12 @@ public static String getPostfixToInfix(String postfix) return infix; } - - public static void main(String args[]) - { + public static void main(String args[]) { assert getPostfixToInfix("ABC+/").equals("(A/(B+C))"); assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))"); assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)"); assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))"); - assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); + assert getPostfixToInfix("AB+CD^/E*FGH+-^") + .equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index 9d253fb37d2b..7fc761b4d2c8 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -11,9 +11,10 @@ public class ReverseStack { public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - System.out.println("Enter the number of elements you wish to insert in the stack"); + System.out.println( + "Enter the number of elements you wish to insert in the stack" + ); int n = sc.nextInt(); int i; Stack stack = new Stack(); @@ -28,7 +29,6 @@ public static void main(String args[]) { System.out.print(stack.peek() + ","); stack.pop(); } - } private static void reverseStack(Stack stack) { @@ -46,11 +46,9 @@ private static void reverseStack(Stack stack) { //Insert the topmost element to the bottom of the stack insertAtBottom(stack, element); - } private static void insertAtBottom(Stack stack, int element) { - if (stack.isEmpty()) { //When stack is empty, insert the element so it will be present at the bottom of the stack stack.push(element); @@ -66,5 +64,4 @@ private static void insertAtBottom(Stack stack, int element) { stack.push(ele); } - } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java index d350bb2d5565..8f8931d1e972 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java @@ -9,7 +9,6 @@ class StackOfLinkedList { public static void main(String[] args) { - LinkedListStack stack = new LinkedListStack(); stack.push(1); stack.push(2); @@ -24,7 +23,9 @@ public static void main(String[] args) { assert stack.pop() == 5; assert stack.pop() == 4; - System.out.println("Top element of stack currently is: " + stack.peek()); + System.out.println( + "Top element of stack currently is: " + stack.peek() + ); } } @@ -119,7 +120,9 @@ public String toString() { builder.append(cur.data).append("->"); cur = cur.next; } - return builder.replace(builder.length() - 2, builder.length(), "").toString(); + return builder + .replace(builder.length() - 2, builder.length(), "") + .toString(); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java index e70abd916f0e..72fe7972d329 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java @@ -1,4 +1,3 @@ - package com.thealgorithms.datastructures.trees; /* @@ -27,111 +26,106 @@ */ +public class AVLSimple { + private class Node { -public class AVLSimple { - private class Node{ - int data; - int height; - Node left; - Node right; - Node(int data){ - this.data=data; - this.height=1; - } - - } - private Node root; - public void insert(int data) { - this.root=insert(this.root,data); - } - private Node insert(Node node,int item) { - if(node==null) { - Node add=new Node(item); - return add; - } - if(node.data>item) { - node.left=insert(node.left,item); - } - if(node.data1&&itemnode.right.data) - return leftRotate(node); - //RL case - if(bf<-1&&item1&&item>node.left.data) { - node.left=leftRotate(node.left); - return rightRotate(node); - } - - return node; - } - public void display() { - this.display(this.root); - System.out.println(this.root.height); - } - private void display (Node node) { - String str=""; - if(node.left!=null) - str+=node.left.data+"=>"; - else - str+="END=>"; - str+=node.data+""; - if(node.right!=null) - str+="<="+node.right.data; - else - str+="<=END"; - System.out.println(str); - if(node.left!=null) - display(node.left); - if(node.right!=null) - display(node.right); - } - private int height(Node node) { - if(node==null) { - return 0; - } - return node.height; - - } - private int bf(Node node) { - if(node==null) - return 0; - return height(node.left)-height(node.right); - } - - private Node rightRotate(Node c) { - Node b=c.left; - Node T3=b.right; - - b.right=c; - c.left=T3; - c.height=Math.max(height(c.left),height(c.right))+1; - b.height=Math.max(height(b.left),height(b.right))+1; - return b; - - } - private Node leftRotate(Node c) { - Node b=c.right; - Node T3=b.left; - - b.left=c; - c.right=T3; - c.height=Math.max(height(c.left),height(c.right))+1; - b.height=Math.max(height(b.left),height(b.right))+1; - return b; - - } + int data; + int height; + Node left; + Node right; + + Node(int data) { + this.data = data; + this.height = 1; + } + } + + private Node root; + + public void insert(int data) { + this.root = insert(this.root, data); + } + + private Node insert(Node node, int item) { + if (node == null) { + Node add = new Node(item); + return add; + } + if (node.data > item) { + node.left = insert(node.left, item); + } + if (node.data < item) { + node.right = insert(node.right, item); + } + node.height = Math.max(height(node.left), height(node.right)) + 1; + int bf = bf(node); + //LL case + if (bf > 1 && item < node.left.data) return rightRotate(node); + //RR case + if (bf < -1 && item > node.right.data) return leftRotate(node); + //RL case + if (bf < -1 && item < node.right.data) { + node.right = rightRotate(node.right); + return leftRotate(node); + } + //LR case + if (bf > 1 && item > node.left.data) { + node.left = leftRotate(node.left); + return rightRotate(node); + } + + return node; + } + + public void display() { + this.display(this.root); + System.out.println(this.root.height); + } + + private void display(Node node) { + String str = ""; + if (node.left != null) str += node.left.data + "=>"; else str += + "END=>"; + str += node.data + ""; + if (node.right != null) str += "<=" + node.right.data; else str += + "<=END"; + System.out.println(str); + if (node.left != null) display(node.left); + if (node.right != null) display(node.right); + } + + private int height(Node node) { + if (node == null) { + return 0; + } + return node.height; + } + + private int bf(Node node) { + if (node == null) return 0; + return height(node.left) - height(node.right); + } + + private Node rightRotate(Node c) { + Node b = c.left; + Node T3 = b.right; + + b.right = c; + c.left = T3; + c.height = Math.max(height(c.left), height(c.right)) + 1; + b.height = Math.max(height(b.left), height(b.right)) + 1; + return b; + } + + private Node leftRotate(Node c) { + Node b = c.right; + Node T3 = b.left; + b.left = c; + c.right = T3; + c.height = Math.max(height(c.left), height(c.right)) + 1; + b.height = Math.max(height(b.left), height(b.right)) + 1; + return b; + } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java index 9551c2bd9732..5549adbd29b7 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java @@ -105,7 +105,6 @@ private void rebalance(Node n) { } else { n = rotateLeftThenRight(n); } - } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) { n = rotateLeft(n); @@ -122,7 +121,6 @@ private void rebalance(Node n) { } private Node rotateLeft(Node a) { - Node b = a.right; b.parent = a.parent; @@ -149,7 +147,6 @@ private Node rotateLeft(Node a) { } private Node rotateRight(Node a) { - Node b = a.left; b.parent = a.parent; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java index 72d0f0de4f50..200a108a1c86 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java @@ -42,7 +42,9 @@ public static void main(String[] args) { tree.remove(2); assert !tree.find(2) : "2 was just deleted from BST"; tree.remove(1); - assert !tree.find(1) : "Since 1 was not present so find deleting would do no change"; + assert !tree.find( + 1 + ) : "Since 1 was not present so find deleting would do no change"; tree.add(30); tree.add(40); assert tree.find(40) : "40 was inserted but not found"; @@ -64,7 +66,7 @@ public void add(int data) { Node temp = this.root; int rightOrLeft = -1; /* Finds the proper place this node can - * be placed in according to rules of BST. + * be placed in according to rules of BST. */ while (temp != null) { if (temp.data > data) { @@ -81,18 +83,18 @@ public void add(int data) { } } /* Creates a newNode with the value passed - * Since this data doesn't already exists + * Since this data doesn't already exists */ Node newNode = new Node(data); /* If the parent node is null - * then the insertion is to be done in - * root itself. + * then the insertion is to be done in + * root itself. */ if (parent == null) { this.root = newNode; } else { /* Check if insertion is to be made in - * left or right subtree. + * left or right subtree. */ if (rightOrLeft == 0) { parent.left = newNode; @@ -112,11 +114,11 @@ public void remove(int data) { Node temp = this.root; int rightOrLeft = -1; /* Find the parent of the node and node itself - * That is to be deleted. - * parent variable store parent - * temp stores node itself. - * rightOrLeft use to keep track weather child - * is left or right subtree + * That is to be deleted. + * parent variable store parent + * temp stores node itself. + * rightOrLeft use to keep track weather child + * is left or right subtree */ while (temp != null) { if (temp.data == data) { @@ -132,7 +134,7 @@ public void remove(int data) { } } /* If temp is null than node with given value is not - * present in our tree. + * present in our tree. */ if (temp != null) { Node replacement; // used to store the new values for replacing nodes @@ -146,10 +148,10 @@ public void remove(int data) { temp.right = null; } else { /* If both left and right child are present - * we replace this nodes data with - * leftmost node's data in its right subtree - * to maintain the balance of BST. - * And then delete that node + * we replace this nodes data with + * leftmost node's data in its right subtree + * to maintain the balance of BST. + * And then delete that node */ if (temp.right.left == null) { temp.data = temp.right.data; @@ -168,7 +170,7 @@ public void remove(int data) { } } /* Change references of parent after - * deleting the child. + * deleting the child. */ if (parent == null) { this.root = replacement; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java index 4d3640fc85e7..4dd32f415f01 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java @@ -44,7 +44,9 @@ public static void main(String[] args) { tree.remove(9); assert !tree.find(9) : "9 was just deleted from BST"; tree.remove(1); - assert !tree.find(1) : "Since 1 was not present so find deleting would do no change"; + assert !tree.find( + 1 + ) : "Since 1 was not present so find deleting would do no change"; tree.add(20); tree.add(70); assert tree.find(70) : "70 was inserted but not found"; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java index 6299b1be1322..f7fecdb3fe86 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java @@ -44,7 +44,9 @@ public static void main(String[] args) { integerTree.remove(9); assert !integerTree.find(9) : "9 was just deleted from BST"; integerTree.remove(1); - assert !integerTree.find(1) : "Since 1 was not present so find deleting would do no change"; + assert !integerTree.find( + 1 + ) : "Since 1 was not present so find deleting would do no change"; integerTree.add(20); integerTree.add(70); assert integerTree.find(70) : "70 was inserted but not found"; @@ -66,7 +68,9 @@ public static void main(String[] args) { stringTree.remove("date"); assert !stringTree.find("date") : "date was just deleted from BST"; stringTree.remove("boy"); - assert !stringTree.find("boy") : "Since boy was not present so deleting would do no change"; + assert !stringTree.find( + "boy" + ) : "Since boy was not present so deleting would do no change"; stringTree.add("india"); stringTree.add("hills"); assert stringTree.find("hills") : "hills was inserted but not found"; @@ -75,7 +79,6 @@ public static void main(String[] args) { banana hills india pineapple */ stringTree.inorder(); - } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java index 6d1c166644a2..48dfe9658467 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java @@ -1,7 +1,7 @@ package com.thealgorithms.datastructures.trees; -import java.util.Queue; import java.util.LinkedList; +import java.util.Queue; /** * This entire class is used to build a Binary Tree data structure. There is the diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java index a60de7be6e2b..e953a37d1c82 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java @@ -1,7 +1,7 @@ package com.thealgorithms.datastructures.trees; -import java.util.Stack; import java.util.HashMap; +import java.util.Stack; /** * This class will check if a BinaryTree is balanced. A balanced binary tree is @@ -80,7 +80,11 @@ public boolean isBalancedRecursive(BinaryTree binaryTree) { * @param depth The current depth of the node * @param isBalanced The array of length 1 keeping track of our balance */ - private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) { + private int isBalancedRecursive( + BTNode node, + int depth, + boolean[] isBalanced + ) { // If the node is null, we should not explore it and the height is 0 // If the tree is already not balanced, might as well stop because we // can't make it balanced now! @@ -90,7 +94,11 @@ private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) { // Visit the left and right children, incrementing their depths by 1 int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced); - int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced); + int rightHeight = isBalancedRecursive( + node.right, + depth + 1, + isBalanced + ); // If the height of either of the left or right subtrees differ by more // than 1, we cannot be balanced @@ -166,7 +174,10 @@ public boolean isBalancedIterative(BinaryTree binaryTree) { // The height of the subtree containing this node is the // max of the left and right subtree heighs plus 1 - subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1); + subtreeHeights.put( + node, + Math.max(rightHeight, leftHeight) + 1 + ); // We've now visited this node, so we pop it from the stack nodeStack.pop(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java index 5fd12c99537d..e43b8c28a924 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java @@ -12,10 +12,10 @@ public class CreateBSTFromSortedArray { public static void main(String[] args) { - test(new int[]{}); - test(new int[]{1, 2, 3}); - test(new int[]{1, 2, 3, 4, 5}); - test(new int[]{1, 2, 3, 4, 5, 6, 7}); + test(new int[] {}); + test(new int[] { 1, 2, 3 }); + test(new int[] { 1, 2, 3, 4, 5 }); + test(new int[] { 1, 2, 3, 4, 5, 6, 7 }); } private static void test(int[] array) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java index bcd00776e7b9..d99d167b96fd 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java @@ -1,8 +1,8 @@ package com.thealgorithms.datastructures.trees; +import com.thealgorithms.datastructures.trees.BinaryTree.Node; import java.util.HashMap; import java.util.Map; -import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * Approach: Naive Solution: Create root node from first value present in @@ -21,17 +21,27 @@ public class CreateBinaryTreeFromInorderPreorder { public static void main(String[] args) { - test(new Integer[]{}, new Integer[]{}); // empty tree - test(new Integer[]{1}, new Integer[]{1}); // single node tree - test(new Integer[]{1, 2, 3, 4}, new Integer[]{1, 2, 3, 4}); // right skewed tree - test(new Integer[]{1, 2, 3, 4}, new Integer[]{4, 3, 2, 1}); // left skewed tree - test(new Integer[]{3, 9, 20, 15, 7}, new Integer[]{9, 3, 15, 20, 7}); // normal tree + test(new Integer[] {}, new Integer[] {}); // empty tree + test(new Integer[] { 1 }, new Integer[] { 1 }); // single node tree + test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 1, 2, 3, 4 }); // right skewed tree + test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 4, 3, 2, 1 }); // left skewed tree + test( + new Integer[] { 3, 9, 20, 15, 7 }, + new Integer[] { 9, 3, 15, 20, 7 } + ); // normal tree } - private static void test(final Integer[] preorder, final Integer[] inorder) { - System.out.println("\n===================================================="); + private static void test( + final Integer[] preorder, + final Integer[] inorder + ) { + System.out.println( + "\n====================================================" + ); System.out.println("Naive Solution..."); - BinaryTree root = new BinaryTree(createTree(preorder, inorder, 0, 0, inorder.length)); + BinaryTree root = new BinaryTree( + createTree(preorder, inorder, 0, 0, inorder.length) + ); System.out.println("Preorder Traversal: "); root.preOrder(root.getRoot()); System.out.println("\nInorder Traversal: "); @@ -43,7 +53,9 @@ private static void test(final Integer[] preorder, final Integer[] inorder) { for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } - BinaryTree optimizedRoot = new BinaryTree(createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map)); + BinaryTree optimizedRoot = new BinaryTree( + createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map) + ); System.out.println("\n\nOptimized solution..."); System.out.println("Preorder Traversal: "); optimizedRoot.preOrder(root.getRoot()); @@ -53,8 +65,13 @@ private static void test(final Integer[] preorder, final Integer[] inorder) { optimizedRoot.postOrder(root.getRoot()); } - private static Node createTree(final Integer[] preorder, final Integer[] inorder, - final int preStart, final int inStart, final int size) { + private static Node createTree( + final Integer[] preorder, + final Integer[] inorder, + final int preStart, + final int inStart, + final int size + ) { if (size == 0) { return null; } @@ -66,16 +83,33 @@ private static Node createTree(final Integer[] preorder, final Integer[] inorder } int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; - root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount); - root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, - rightNodesCount); + root.left = + createTree( + preorder, + inorder, + preStart + 1, + inStart, + leftNodesCount + ); + root.right = + createTree( + preorder, + inorder, + preStart + leftNodesCount + 1, + i + 1, + rightNodesCount + ); return root; - } - private static Node createTreeOptimized(final Integer[] preorder, final Integer[] inorder, - final int preStart, final int inStart, final int size, - final Map inorderMap) { + private static Node createTreeOptimized( + final Integer[] preorder, + final Integer[] inorder, + final int preStart, + final int inStart, + final int size, + final Map inorderMap + ) { if (size == 0) { return null; } @@ -84,11 +118,24 @@ private static Node createTreeOptimized(final Integer[] preorder, final Integer[ int i = inorderMap.get(preorder[preStart]); int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; - root.left = createTreeOptimized(preorder, inorder, preStart + 1, inStart, - leftNodesCount, inorderMap); - root.right = createTreeOptimized(preorder, inorder, preStart + leftNodesCount + 1, - i + 1, rightNodesCount, inorderMap); + root.left = + createTreeOptimized( + preorder, + inorder, + preStart + 1, + inStart, + leftNodesCount, + inorderMap + ); + root.right = + createTreeOptimized( + preorder, + inorder, + preStart + leftNodesCount + 1, + i + 1, + rightNodesCount, + inorderMap + ); return root; } - } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java index 922cd62fcb2e..9f776e6d7df4 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java @@ -35,7 +35,9 @@ private Node create_treeG(Node node, int childindx, Scanner scn) { if (node == null) { System.out.println("Enter root's data"); } else { - System.out.println("Enter data of parent of index " + node.data + " " + childindx); + System.out.println( + "Enter data of parent of index " + node.data + " " + childindx + ); } // input node = new Node(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index 61c1f935d684..cd28f93c9d56 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -34,9 +34,15 @@ public class KDTree { * @param points Array of initial points */ KDTree(Point[] points) { - if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty"); + if (points.length == 0) throw new IllegalArgumentException( + "Points array cannot be empty" + ); this.k = points[0].getDimension(); - for (Point point : points) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension"); + for (Point point : points) if ( + point.getDimension() != k + ) throw new IllegalArgumentException( + "Points must have the same dimension" + ); this.root = build(points, 0); } @@ -47,16 +53,24 @@ public class KDTree { * */ KDTree(int[][] pointsCoordinates) { - if (pointsCoordinates.length == 0) throw new IllegalArgumentException("Points array cannot be empty"); + if (pointsCoordinates.length == 0) throw new IllegalArgumentException( + "Points array cannot be empty" + ); this.k = pointsCoordinates[0].length; - Point[] points = Arrays.stream(pointsCoordinates) - .map(Point::new) - .toArray(Point[]::new); - for (Point point : points) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension"); + Point[] points = Arrays + .stream(pointsCoordinates) + .map(Point::new) + .toArray(Point[]::new); + for (Point point : points) if ( + point.getDimension() != k + ) throw new IllegalArgumentException( + "Points must have the same dimension" + ); this.root = build(points, 0); } static class Point { + int[] coordinates; public int getCoordinate(int i) { @@ -93,7 +107,7 @@ public String toString() { * * @return The comparable distance between the two points */ - static public int comparableDistance(Point p1, Point p2) { + public static int comparableDistance(Point p1, Point p2) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { int t = p1.getCoordinate(i) - p2.getCoordinate(i); @@ -111,7 +125,11 @@ static public int comparableDistance(Point p1, Point p2) { * * @return The distance between the two points */ - static public int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { + public static int comparableDistanceExceptAxis( + Point p1, + Point p2, + int axis + ) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { if (i == axis) continue; @@ -122,8 +140,8 @@ static public int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { } } - static class Node { + private Point point; private int axis; // 0 for x, 1 for y, 2 for z, etc. @@ -159,8 +177,9 @@ public int getAxis() { * @return The nearest child Node */ public Node getNearChild(Point point) { - if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) return left; - else return right; + if ( + point.getCoordinate(axis) < this.point.getCoordinate(axis) + ) return left; else return right; } /** @@ -171,8 +190,9 @@ public Node getNearChild(Point point) { * @return The farthest child Node */ public Node getFarChild(Point point) { - if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) return right; - else return left; + if ( + point.getCoordinate(axis) < this.point.getCoordinate(axis) + ) return right; else return left; } /** @@ -201,11 +221,18 @@ private Node build(Point[] points, int depth) { if (points.length == 0) return null; int axis = depth % k; if (points.length == 1) return new Node(points[0], axis); - Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis))); + Arrays.sort( + points, + Comparator.comparingInt(o -> o.getCoordinate(axis)) + ); int median = points.length >> 1; Node node = new Node(points[median], axis); node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1); - node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1); + node.right = + build( + Arrays.copyOfRange(points, median + 1, points.length), + depth + 1 + ); return node; } @@ -216,7 +243,9 @@ private Node build(Point[] points, int depth) { * */ public void insert(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension"); + if (point.getDimension() != k) throw new IllegalArgumentException( + "Point has wrong dimension" + ); root = insert(root, point, 0); } @@ -232,8 +261,9 @@ public void insert(Point point) { private Node insert(Node root, Point point, int depth) { int axis = depth % k; if (root == null) return new Node(point, axis); - if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left = insert(root.left, point, depth + 1); - else root.right = insert(root.right, point, depth + 1); + if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left = + insert(root.left, point, depth + 1); else root.right = + insert(root.right, point, depth + 1); return root; } @@ -246,7 +276,9 @@ private Node insert(Node root, Point point, int depth) { * @return The Node corresponding to the specified point */ public Optional search(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension"); + if (point.getDimension() != k) throw new IllegalArgumentException( + "Point has wrong dimension" + ); return search(root, point); } @@ -264,7 +296,6 @@ public Optional search(Node root, Point point) { return search(root.getNearChild(point), point); } - /** * Find a point with minimum value in specified axis in the KDTree * @@ -292,14 +323,15 @@ public Node findMin(Node root, int axis) { } else { Node left = findMin(root.left, axis); Node right = findMin(root.right, axis); - Node[] candidates = {left, root, right}; - return Arrays.stream(candidates) - .filter(Objects::nonNull) - .min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null); + Node[] candidates = { left, root, right }; + return Arrays + .stream(candidates) + .filter(Objects::nonNull) + .min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) + .orElse(null); } } - /** * Find a point with maximum value in specified axis in the KDTree * @@ -327,10 +359,12 @@ public Node findMax(Node root, int axis) { } else { Node left = findMax(root.left, axis); Node right = findMax(root.right, axis); - Node[] candidates = {left, root, right}; - return Arrays.stream(candidates) - .filter(Objects::nonNull) - .max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null); + Node[] candidates = { left, root, right }; + return Arrays + .stream(candidates) + .filter(Objects::nonNull) + .max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) + .orElse(null); } } @@ -340,7 +374,8 @@ public Node findMax(Node root, int axis) { * @param point the point to delete * */ public void delete(Point point) { - Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found")); + Node node = search(point) + .orElseThrow(() -> new IllegalArgumentException("Point not found")); root = delete(root, node); } @@ -365,8 +400,10 @@ private Node delete(Node root, Node node) { root.left = delete(root.left, min); } else return null; } - if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) root.left = delete(root.left, node); - else root.right = delete(root.right, node); + if ( + root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis()) + ) root.left = delete(root.left, node); else root.right = + delete(root.right, node); return root; } @@ -379,7 +416,6 @@ public Point findNearest(Point point) { return findNearest(root, point, root).point; } - /** * Finds the nearest point in a subtree to the given point. * @@ -391,11 +427,17 @@ private Node findNearest(Node root, Point point, Node nearest) { if (root == null) return nearest; if (root.point.equals(point)) return root; int distance = Point.comparableDistance(root.point, point); - int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis()); - if (distance < Point.comparableDistance(nearest.point, point)) nearest = root; + int distanceExceptAxis = Point.comparableDistanceExceptAxis( + root.point, + point, + root.getAxis() + ); + if (distance < Point.comparableDistance(nearest.point, point)) nearest = + root; nearest = findNearest(root.getNearChild(point), point, nearest); - if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) - nearest = findNearest(root.getFarChild(point), point, nearest); + if ( + distanceExceptAxis < Point.comparableDistance(nearest.point, point) + ) nearest = findNearest(root.getFarChild(point), point, nearest); return nearest; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java index 193e89d2772f..1fe83e0c0de5 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java @@ -8,7 +8,6 @@ public class LCA { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { - //The adjacency list representation of a tree: ArrayList> adj = new ArrayList<>(); @@ -22,7 +21,6 @@ public static void main(String[] args) { //Storing the given tree as an adjacency list int to, from; for (int i = 0; i < e; i++) { - to = scanner.nextInt(); from = scanner.nextInt(); @@ -44,7 +42,6 @@ public static void main(String[] args) { //Outputting the LCA System.out.println(getLCA(v1, v2, depth, parent)); - } /** @@ -56,7 +53,13 @@ public static void main(String[] args) { * @param parent An array to store parents of all vertices * @param depth An array to store depth of all vertices */ - private static void dfs(ArrayList> adj, int s, int p, int[] parent, int[] depth) { + private static void dfs( + ArrayList> adj, + int s, + int p, + int[] parent, + int[] depth + ) { for (int adjacent : adj.get(s)) { if (adjacent != p) { parent[adjacent] = s; @@ -94,7 +97,6 @@ private static int getLCA(int v1, int v2, int[] depth, int[] parent) { return v1; } } - /** * Input: * 10 diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java index fe1bf8ec41d2..a98ec9ddd86b 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java @@ -1,6 +1,7 @@ package com.thealgorithms.datastructures.trees; public class LazySegmentTree { + /** * Lazy Segment Tree * @@ -8,10 +9,12 @@ public class LazySegmentTree { * */ static class Node { + private final int start, end; // start and end of the segment represented by this node private int value; // value is the sum of all elements in the range [start, end) private int lazy; // lazied value that should be added to children nodes Node left, right; // left and right children + public Node(int start, int end, int value) { this.start = start; this.end = end; @@ -50,7 +53,11 @@ public void shift() { static Node merge(Node left, Node right) { if (left == null) return right; if (right == null) return left; - Node result = new Node(left.start, right.end, left.value + right.value); + Node result = new Node( + left.start, + right.end, + left.value + right.value + ); result.left = left; result.right = right; return result; @@ -124,7 +131,10 @@ private Node getRange(int left, int right, Node curr) { if (left <= curr.start && curr.end <= right) return curr; if (left >= curr.end || right <= curr.start) return null; curr.shift(); - return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right)); + return Node.merge( + getRange(left, right, curr.left), + getRange(left, right, curr.right) + ); } public int getRange(int left, int right) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java b/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java index c32b6653bcb0..65a0d6e10d60 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java @@ -25,7 +25,6 @@ void printLevelOrder(Node root) { Queue queue = new LinkedList(); queue.add(root); while (!queue.isEmpty()) { - /* poll() removes the present head. For more information on poll() visit http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java index 2fcfd1827d1e..a2dbeca5ebac 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java @@ -6,6 +6,7 @@ // Class for a tree node class TreeNode { + // Members int key; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java index d50eafc438b3..d7f34007fa87 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java @@ -29,7 +29,13 @@ public void printTree(Node node) { } printTree(node.left); System.out.print( - ((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); + ((node.color == R) ? " R " : " B ") + + "Key: " + + node.key + + " Parent: " + + node.p.key + + "\n" + ); printTree(node.right); } @@ -38,7 +44,13 @@ public void printTreepre(Node node) { return; } System.out.print( - ((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); + ((node.color == R) ? " R " : " B ") + + "Key: " + + node.key + + " Parent: " + + node.p.key + + "\n" + ); printTreepre(node.left); printTreepre(node.right); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java index 674c6a85385a..68154129dd1d 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java @@ -26,14 +26,21 @@ public int constructTree(int[] arr, int start, int end, int index) { } int mid = start + (end - start) / 2; - this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) - + constructTree(arr, mid + 1, end, index * 2 + 2); + this.seg_t[index] = + constructTree(arr, start, mid, index * 2 + 1) + + constructTree(arr, mid + 1, end, index * 2 + 2); return this.seg_t[index]; } /* A function which will update the value at a index i. This will be called by the update function internally*/ - private void updateTree(int start, int end, int index, int diff, int seg_index) { + private void updateTree( + int start, + int end, + int index, + int diff, + int seg_index + ) { if (index < start || index > end) { return; } @@ -58,7 +65,13 @@ public void update(int index, int value) { } /* A function to get the sum of the elements from index l to index r. This will be called internally*/ - private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) { + private int getSumTree( + int start, + int end, + int q_start, + int q_end, + int seg_index + ) { if (q_start <= start && q_end >= end) { return this.seg_t[seg_index]; } @@ -68,7 +81,10 @@ private int getSumTree(int start, int end, int q_start, int q_end, int seg_index } int mid = start + (end - start) / 2; - return getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2); + return ( + getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2) + ); } /* A function to query the sum of the subarray [start...end]*/ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java index 86cafd468909..369eaf57cc2a 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java @@ -1,6 +1,5 @@ package com.thealgorithms.datastructures.trees; - /* Author : Suraj Kumar Github : https://github.com/skmodi649 */ @@ -20,13 +19,14 @@ the inOrder() method to store the values in the arraylist, then find the size of Step 6: STOP */ - import java.util.ArrayList; // Using auxiliary array to find the random node in a given binary tree public class TreeRandomNode { + private class Node { + int item; Node left, right; @@ -70,26 +70,20 @@ public void getRandom(Node val) { // displaying the value at the generated index int random = list.get(b); System.out.println("Random Node : " + random); - } } - - /* Explanation of the Approach : (a) Form the required binary tree (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list' (c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number from the arraylist using get() method and finally display the result. */ - - /* OUTPUT : First output : Random Node : 15 Second output : Random Node : 99 */ - /* Time Complexity : O(n) Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java b/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java index 1b9555c07650..395a9ea30dcf 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java @@ -18,7 +18,7 @@ public Node(int item) { /* can give min and max value according to your code or can write a function to find min and max value of tree. */ - /* returns true if given search tree is binary + /* returns true if given search tree is binary search tree (efficient version) */ boolean isBST(Node root) { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); @@ -40,6 +40,9 @@ boolean isBSTUtil(Node node, int min, int max) { /* otherwise check the subtrees recursively tightening the min/max constraints */ // Allow only distinct values - return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); + return ( + isBSTUtil(node.left, min, node.data - 1) && + isBSTUtil(node.right, node.data + 1, max) + ); } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java index 18577fbc5c9a..f90fab52b3d1 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java @@ -60,7 +60,6 @@ private static ArrayList verticalTraversal(BinaryTree.Node root) { index.offer(0); while (!queue.isEmpty()) { - if (queue.peek().left != null) { /*Adding the left Node if it is not null and its index by subtracting 1 from it's diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java index a056c459f000..773d30743ab2 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java @@ -42,10 +42,8 @@ public static int nearestRightKey(NRKTree root, int x0) { // Go right return nearestRightKey(root.right, x0); } - } } - } class NRKTree { diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index 1575e3649bc3..7a60741d5d96 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -53,7 +53,11 @@ public LargeTreeNode(E data, LargeTreeNode parentNode) { * @param childNodes {@link Collection} of child Nodes. * @see TreeNode#TreeNode(Object, Node) */ - public LargeTreeNode(E data, LargeTreeNode parentNode, Collection> childNodes) { + public LargeTreeNode( + E data, + LargeTreeNode parentNode, + Collection> childNodes + ) { super(data, parentNode); this.childNodes = childNodes; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java index a10817830962..e6be58f5f616 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java @@ -20,8 +20,7 @@ public abstract class Node { /** * Empty constructor. */ - public Node() { - } + public Node() {} /** * Initializes the Nodes' data. diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index 215f01a6ef59..7230db73fb87 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -57,7 +57,12 @@ public SimpleTreeNode(E data, SimpleTreeNode parentNode) { * @param rightNode Value to which the nodes' right child reference will be * set. */ - public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode, SimpleTreeNode rightNode) { + public SimpleTreeNode( + E data, + SimpleTreeNode parentNode, + SimpleTreeNode leftNode, + SimpleTreeNode rightNode + ) { super(data, parentNode); this.leftNode = leftNode; this.rightNode = rightNode; diff --git a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java index 96da4b3f8546..69602811c8f9 100644 --- a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java +++ b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java @@ -6,7 +6,6 @@ * @author Podshivalov Nikita (https://github.com/nikitap492) */ public interface SearchAlgorithm { - /** * @param key is an element which should be found * @param array is an array where the element should be found diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java index 9751dce61c3f..ad0c6867e5a2 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java +++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java @@ -83,7 +83,6 @@ public Location buildLocation(double x, double y) { * @return pivot index */ public int xPartition(final Location[] a, final int first, final int last) { - Location pivot = a[last]; // pivot int i = first - 1; Location temp; // Temporarily store value for position transformation @@ -111,7 +110,6 @@ public int xPartition(final Location[] a, final int first, final int last) { * @return pivot index */ public int yPartition(final Location[] a, final int first, final int last) { - Location pivot = a[last]; // pivot int i = first - 1; Location temp; // Temporarily store value for position transformation @@ -137,8 +135,11 @@ public int yPartition(final Location[] a, final int first, final int last) { * @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/ - public void xQuickSort(final Location[] a, final int first, final int last) { - + public void xQuickSort( + final Location[] a, + final int first, + final int last + ) { if (first < last) { int q = xPartition(a, first, last); // pivot xQuickSort(a, first, q - 1); // Left @@ -153,8 +154,11 @@ public void xQuickSort(final Location[] a, final int first, final int last) { * @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/ - public void yQuickSort(final Location[] a, final int first, final int last) { - + public void yQuickSort( + final Location[] a, + final int first, + final int last + ) { if (first < last) { int q = yPartition(a, first, last); // pivot yQuickSort(a, first, q - 1); // Left @@ -170,7 +174,6 @@ public void yQuickSort(final Location[] a, final int first, final int last) { * @return minimum distance
*/ public double closestPair(final Location[] a, final int indexNum) { - Location[] divideArray = new Location[indexNum]; System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array int divideX = indexNum / 2; // Intermediate value for divide @@ -183,7 +186,13 @@ public double closestPair(final Location[] a, final int indexNum) { // divide-left array System.arraycopy(divideArray, 0, leftArray, 0, divideX); // divide-right array - System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); + System.arraycopy( + divideArray, + divideX, + rightArray, + 0, + indexNum - divideX + ); double minLeftArea; // Minimum length of left array double minRightArea; // Minimum length of right array @@ -257,7 +266,6 @@ public double closestPair(final Location[] a, final int indexNum) { * @return
*/ public double bruteForce(final Location[] arrayParam) { - double minValue = Double.MAX_VALUE; // minimum distance double length; double xGap; // Difference between x coordinates @@ -312,7 +320,6 @@ public double bruteForce(final Location[] arrayParam) { * @param args (IN Parameter)
*/ public static void main(final String[] args) { - // Input data consists of one x-coordinate and one y-coordinate ClosestPair cp = new ClosestPair(12); cp.array[0] = cp.buildLocation(2, 3); diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java index def2731ac7db..f7ba384c6fbe 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java +++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java @@ -45,7 +45,6 @@ public ArrayList getPoints() { * @see Point */ public ArrayList produceSubSkyLines(ArrayList list) { - // part where function exits flashback int size = list.size(); if (size == 1) { @@ -93,11 +92,16 @@ public ArrayList produceSubSkyLines(ArrayList list) { * @param right the skyline of the right part of points * @return left the final skyline */ - public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { - + public ArrayList produceFinalSkyLine( + ArrayList left, + ArrayList right + ) { // dominated points of ArrayList left are removed for (int i = 0; i < left.size() - 1; i++) { - if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { + if ( + left.get(i).x == left.get(i + 1).x && + left.get(i).y > left.get(i + 1).y + ) { left.remove(i); i--; } @@ -168,7 +172,10 @@ public int getY() { */ public boolean dominates(Point p1) { // checks if p1 is dominated - return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y); + return ( + (this.x < p1.x && this.y <= p1.y) || + (this.x <= p1.x && this.y < p1.y) + ); } } diff --git a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java index 579ad4d517c0..1ea4f1aefa7f 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java +++ b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java @@ -39,8 +39,7 @@ public int[][] multiply(int[][] A, int[][] B) { // Using Formulas as described in algorithm // M1:=(A1+A3)×(B1+B2) - int[][] M1 - = multiply(add(A11, A22), add(B11, B22)); + int[][] M1 = multiply(add(A11, A22), add(B11, B22)); // M2:=(A2+A4)×(B3+B4) int[][] M2 = multiply(add(A21, A22), B11); @@ -55,12 +54,10 @@ public int[][] multiply(int[][] A, int[][] B) { int[][] M5 = multiply(add(A11, A12), B22); // M6:=(A1+A2)×(B4) - int[][] M6 - = multiply(sub(A21, A11), add(B11, B12)); + int[][] M6 = multiply(sub(A21, A11), add(B11, B12)); // M7:=A4×(B3−B1) - int[][] M7 - = multiply(sub(A12, A22), add(B21, B22)); + int[][] M7 = multiply(sub(A12, A22), add(B21, B22)); // P:=M2+M3−M6−M7 int[][] C11 = add(sub(add(M1, M4), M5), M7); @@ -102,7 +99,6 @@ public int[][] sub(int[][] A, int[][] B) { // Method 3 // Function to add two matrices public int[][] add(int[][] A, int[][] B) { - int n = A.length; int[][] C = new int[n][n]; @@ -141,7 +137,9 @@ public void join(int[][] C, int[][] P, int iB, int jB) { // Method 5 // Main driver method public static void main(String[] args) { - System.out.println("Strassen Multiplication Algorithm Implementation For Matrix Multiplication :\n"); + System.out.println( + "Strassen Multiplication Algorithm Implementation For Matrix Multiplication :\n" + ); StrassenMatrixMultiplication s = new StrassenMatrixMultiplication(); @@ -151,17 +149,21 @@ public static void main(String[] args) { // Matrix A // Custom input to matrix - int[][] A = {{1, 2, 5, 4}, - {9, 3, 0, 6}, - {4, 6, 3, 1}, - {0, 2, 0, 6}}; + int[][] A = { + { 1, 2, 5, 4 }, + { 9, 3, 0, 6 }, + { 4, 6, 3, 1 }, + { 0, 2, 0, 6 }, + }; // Matrix B // Custom input to matrix - int[][] B = {{1, 0, 4, 1}, - {1, 2, 0, 2}, - {0, 3, 1, 3}, - {1, 8, 1, 2}}; + int[][] B = { + { 1, 0, 4, 1 }, + { 1, 2, 0, 2 }, + { 0, 3, 1, 3 }, + { 1, 8, 1, 2 }, + }; // Matrix C computations // Matrix C calling method to get Result diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index 6a547618cbf6..514f9e4ccac8 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -5,7 +5,7 @@ * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ public class BoundaryFill { - + /** * Get the color at the given co-odrinates of a 2D image * @@ -13,12 +13,14 @@ public class BoundaryFill { * @param x_co_ordinate The x co-ordinate of which color is to be obtained * @param y_co_ordinate The y co-ordinate of which color is to be obtained */ - public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) { - - return image[x_co_ordinate][y_co_ordinate]; - - } - + public static int getPixel( + int[][] image, + int x_co_ordinate, + int y_co_ordinate + ) { + return image[x_co_ordinate][y_co_ordinate]; + } + /** * Put the color at the given co-odrinates of a 2D image * @@ -26,12 +28,15 @@ public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) * @param x_co_ordinate The x co-ordinate at which color is to be filled * @param y_co_ordinate The y co-ordinate at which color is to be filled */ - public static void putPixel(int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) { - - image[x_co_ordinate][y_co_ordinate] = new_color; - - } - + public static void putPixel( + int[][] image, + int x_co_ordinate, + int y_co_ordinate, + int new_color + ) { + image[x_co_ordinate][y_co_ordinate] = new_color; + } + /** * Fill the 2D image with new color * @@ -41,60 +46,110 @@ public static void putPixel(int[][] image, int x_co_ordinate, int y_co_ordinate, * @param new_color The new color which to be filled in the image * @param boundary_color The old color which is to be replaced in the image */ - public static void boundaryFill(int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) { - if(x_co_ordinate >= 0 && y_co_ordinate >= 0 && getPixel(image, x_co_ordinate, y_co_ordinate) != new_color && getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) { - - putPixel(image, x_co_ordinate, y_co_ordinate, new_color); - boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color); - boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color); - boundaryFill(image, x_co_ordinate, y_co_ordinate + 1, new_color, boundary_color); - boundaryFill(image, x_co_ordinate, y_co_ordinate - 1, new_color, boundary_color); - boundaryFill(image, x_co_ordinate + 1, y_co_ordinate - 1, new_color, boundary_color); - boundaryFill(image, x_co_ordinate - 1, y_co_ordinate + 1, new_color, boundary_color); - boundaryFill(image, x_co_ordinate + 1, y_co_ordinate + 1, new_color, boundary_color); - boundaryFill(image, x_co_ordinate - 1, y_co_ordinate - 1, new_color, boundary_color); - - - } - - } - + public static void boundaryFill( + int[][] image, + int x_co_ordinate, + int y_co_ordinate, + int new_color, + int boundary_color + ) { + if ( + x_co_ordinate >= 0 && + y_co_ordinate >= 0 && + getPixel(image, x_co_ordinate, y_co_ordinate) != new_color && + getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color + ) { + putPixel(image, x_co_ordinate, y_co_ordinate, new_color); + boundaryFill( + image, + x_co_ordinate + 1, + y_co_ordinate, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate - 1, + y_co_ordinate, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate, + y_co_ordinate + 1, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate, + y_co_ordinate - 1, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate + 1, + y_co_ordinate - 1, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate - 1, + y_co_ordinate + 1, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate + 1, + y_co_ordinate + 1, + new_color, + boundary_color + ); + boundaryFill( + image, + x_co_ordinate - 1, + y_co_ordinate - 1, + new_color, + boundary_color + ); + } + } + /** * This method will print the 2D image matrix * * @param image The image to be printed on the console */ - public static void printImageArray(int[][] image) { - - for(int i=0 ; i + public static void printImageArray(int[][] image) { + for (int i = 0; i < image.length; i++) { + for (int j = 0; j < image[0].length; j++) { + System.out.print(image[i][j] + " "); + } + + System.out.println(); + } + } + + // Driver Program + public static void main(String[] args) { + //Input 2D image matrix + int[][] image = { + { 0, 0, 0, 0, 0, 0, 0 }, + { 0, 3, 3, 3, 3, 0, 0 }, + { 0, 3, 0, 0, 3, 0, 0 }, + { 0, 3, 0, 0, 3, 3, 3 }, + { 0, 3, 3, 3, 0, 0, 3 }, + { 0, 0, 0, 3, 0, 0, 3 }, + { 0, 0, 0, 3, 3, 3, 3 }, + }; + + boundaryFill(image, 2, 2, 5, 3); + + /* Output ==> * 0 0 0 0 0 0 0 0 3 3 3 3 0 0 0 3 5 5 3 0 0 @@ -103,9 +158,8 @@ public static void main(String[] args) { 0 0 0 3 5 5 3 0 0 0 3 3 3 3 * */ - - //print 2D image matrix - printImageArray(image); - } -} \ No newline at end of file + //print 2D image matrix + printImageArray(image); + } +} diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java index b4c9875427cb..4e2e25484bb8 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java @@ -29,14 +29,17 @@ static int knapSack(int W, int wt[], int val[], int n) { // (1) nth item included // (2) not included else { - return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); + return max( + val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), + knapSack(W, wt, val, n - 1) + ); } } // Driver code public static void main(String args[]) { - int val[] = new int[]{60, 100, 120}; - int wt[] = new int[]{10, 20, 30}; + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java index 8f7d9c779b5f..41bd49715721 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java @@ -22,11 +22,10 @@ public class CatalanNumber { * @return catalanArray[n] the nth Catalan number */ static long findNthCatalan(int n) { - // Array to store the results of subproblems i.e Catalan numbers from [1...n-1] long catalanArray[] = new long[n + 1]; - // Initialising C₀ = 1 and C₁ = 1 + // Initialising C₀ = 1 and C₁ = 1 catalanArray[0] = 1; catalanArray[1] = 1; @@ -48,7 +47,9 @@ static long findNthCatalan(int n) { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println("Enter the number n to find nth Catalan number (n <= 50)"); + System.out.println( + "Enter the number n to find nth Catalan number (n <= 50)" + ); int n = sc.nextInt(); System.out.println(n + "th Catalan number is " + findNthCatalan(n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index 51f615dff1fa..d7bd476f5071 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -7,17 +7,21 @@ public class CoinChange { // Driver Program public static void main(String[] args) { - int amount = 12; - int[] coins = {2, 4, 5}; + int[] coins = { 2, 4, 5 }; System.out.println( - "Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); + "Number of combinations of getting change for " + + amount + + " is: " + + change(coins, amount) + ); System.out.println( - "Minimum number of coins required for amount :" - + amount - + " is: " - + minimumCoins(coins, amount)); + "Minimum number of coins required for amount :" + + amount + + " is: " + + minimumCoins(coins, amount) + ); } /** @@ -29,7 +33,6 @@ public static void main(String[] args) { * number of combinations of change */ public static int change(int[] coins, int amount) { - int[] combinations = new int[amount + 1]; combinations[0] = 1; @@ -64,7 +67,10 @@ public static int minimumCoins(int[] coins, int amount) { for (int coin : coins) { if (coin <= i) { int sub_res = minimumCoins[i - coin]; - if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) { + if ( + sub_res != Integer.MAX_VALUE && + sub_res + 1 < minimumCoins[i] + ) { minimumCoins[i] = sub_res + 1; } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java index a5d069391dfb..968586c552ab 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java @@ -14,6 +14,7 @@ package com.thealgorithms.dynamicprogramming; public class CountFriendsPairing { + public static boolean countFriendsPairing(int n, int a[]) { int dp[] = new int[n + 1]; // array of n+1 size is created diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java index fd272f8e5779..5744e4f84217 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java @@ -11,13 +11,12 @@ And it can be done using Dynamic Programming(DP). Following is implementation of Dynamic Programming approach. */ // Code ----> -// Java program to find number of ways to get sum 'x' with 'n' -// dice where every dice has 'm' faces +// Java program to find number of ways to get sum 'x' with 'n' +// dice where every dice has 'm' faces class DP { /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ public static long findWays(int m, int n, int x) { - /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). @@ -50,7 +49,6 @@ public static void main(String[] args) { System.out.println(findWays(4, 3, 5)); } } - /* OUTPUT: 0 @@ -60,4 +58,3 @@ public static void main(String[] args) { 6 */ // Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum. - diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java index 6f4df8f634d4..ffbefd479552 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java @@ -20,7 +20,8 @@ static int knapSack(int W, int wt[], int val[], int n) { if (i == 0 || w == 0) { K[i][w] = 0; } else if (wt[i - 1] <= w) { - K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); + K[i][w] = + max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); } else { K[i][w] = K[i - 1][w]; } @@ -32,8 +33,8 @@ static int knapSack(int W, int wt[], int val[], int n) { // Driver code public static void main(String args[]) { - int val[] = new int[]{60, 100, 120}; - int wt[] = new int[]{10, 20, 30}; + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java index b99d016c0a27..0f27ba0bcc26 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java @@ -77,7 +77,13 @@ public static void main(String[] args) { // ans stores the final Edit Distance between the two strings int ans = minDistance(s1, s2); System.out.println( - "The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); + "The minimum Edit Distance between \"" + + s1 + + "\" and \"" + + s2 + + "\" is " + + ans + ); input.close(); } @@ -85,7 +91,6 @@ public static void main(String[] args) { public static int editDistance(String s1, String s2) { int[][] storage = new int[s1.length() + 1][s2.length() + 1]; return editDistance(s1, s2, storage); - } public static int editDistance(String s1, String s2, int[][] storage) { @@ -93,22 +98,19 @@ public static int editDistance(String s1, String s2, int[][] storage) { int n = s2.length(); if (storage[m][n] > 0) { return storage[m][n]; - } if (m == 0) { storage[m][n] = n; return storage[m][n]; - } if (n == 0) { storage[m][n] = m; return storage[m][n]; - } if (s1.charAt(0) == s2.charAt(0)) { - storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage); + storage[m][n] = + editDistance(s1.substring(1), s2.substring(1), storage); return storage[m][n]; - } else { int op1 = editDistance(s1, s2.substring(1), storage); int op2 = editDistance(s1.substring(1), s2, storage); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java index 4bcca33e7c33..2bb782d2aafb 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java @@ -7,7 +7,6 @@ public class EggDropping { // min trials with n eggs and m floors private static int minTrials(int n, int m) { - int[][] eggFloor = new int[n + 1][m + 1]; int result, x; @@ -26,7 +25,9 @@ private static int minTrials(int n, int m) { for (int j = 2; j <= m; j++) { eggFloor[i][j] = Integer.MAX_VALUE; for (x = 1; x <= j; x++) { - result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + result = + 1 + + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); // choose min of all values for particular x if (result < eggFloor[i][j]) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index ac97ba004197..aeabb20e3b18 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -12,7 +12,6 @@ public class Fibonacci { private static Map map = new HashMap<>(); public static void main(String[] args) { - // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] Scanner sc = new Scanner(System.in); int n = sc.nextInt(); @@ -52,7 +51,6 @@ public static int fibMemo(int n) { * Outputs the nth fibonacci number */ public static int fibBotUp(int n) { - Map fib = new HashMap<>(); for (int i = 0; i <= n; i++) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java index 63ec477c4590..1b9f1deea884 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java @@ -26,7 +26,9 @@ public static void main(String[] args) { capacity[3][4] = 15; capacity[4][5] = 17; - System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); + System.out.println( + "Max capacity in networkFlow : " + networkFlow(0, 5) + ); } private static int networkFlow(int source, int sink) { @@ -44,7 +46,10 @@ private static int networkFlow(int source, int sink) { int here = q.peek(); q.poll(); for (int there = 0; there < V; ++there) { - if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { + if ( + capacity[here][there] - flow[here][there] > 0 && + parent.get(there) == -1 + ) { q.add(there); parent.set(there, here); } @@ -58,7 +63,11 @@ private static int networkFlow(int source, int sink) { String printer = "path : "; StringBuilder sb = new StringBuilder(); for (int p = sink; p != source; p = parent.get(p)) { - amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); + amount = + Math.min( + capacity[parent.get(p)][p] - flow[parent.get(p)][p], + amount + ); sb.append(p + "-"); } sb.append(source); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index ab15ba17d968..8123a02562f3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -3,24 +3,22 @@ */ /** Program description - To find the maximum subarray sum */ - package com.thealgorithms.dynamicprogramming; +package com.thealgorithms.dynamicprogramming; public class KadaneAlgorithm { - public static boolean max_Sum(int a[] , int predicted_answer) - { - int sum=a[0],running_sum=0; - for(int k:a) - { - running_sum=running_sum+k; + + public static boolean max_Sum(int a[], int predicted_answer) { + int sum = a[0], running_sum = 0; + for (int k : a) { + running_sum = running_sum + k; // running sum of all the indexs are stored - sum=Math.max(sum,running_sum); + sum = Math.max(sum, running_sum); // the max is stored inorder to the get the maximum sum - if(running_sum<0) - running_sum=0; + if (running_sum < 0) running_sum = 0; // if running sum is negative then it is initialized to zero } // for-each loop is used to iterate over the array and find the maximum subarray sum - return sum==predicted_answer; + return sum == predicted_answer; // It returns true if sum and predicted answer matches // The predicted answer is the answer itself. So it always return true } @@ -31,4 +29,4 @@ public static boolean max_Sum(int a[] , int predicted_answer) * 1st approach Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java index c4d990e4fb58..df1bbd234fb7 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java @@ -5,7 +5,8 @@ */ public class Knapsack { - private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { + private static int knapSack(int W, int wt[], int val[], int n) + throws IllegalArgumentException { if (wt == null || val == null) { throw new IllegalArgumentException(); } @@ -18,7 +19,11 @@ private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArg if (i == 0 || w == 0) { rv[i][w] = 0; } else if (wt[i - 1] <= w) { - rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); + rv[i][w] = + Math.max( + val[i - 1] + rv[i - 1][w - wt[i - 1]], + rv[i - 1][w] + ); } else { rv[i][w] = rv[i - 1][w]; } @@ -30,8 +35,8 @@ private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArg // Driver program to test above function public static void main(String args[]) { - int val[] = new int[]{50, 100, 130}; - int wt[] = new int[]{10, 20, 40}; + int val[] = new int[] { 50, 100, 130 }; + int wt[] = new int[] { 10, 20, 40 }; int W = 50; System.out.println(knapSack(W, wt, val, val.length)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java index d2e2e9c045fc..8d2b324ab7dd 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java @@ -40,8 +40,8 @@ public static int knapsack(int[] wt, int[] value, int W, int n) { // Driver code public static void main(String args[]) { - int[] wt = {1, 3, 4, 5}; - int[] value = {1, 4, 5, 7}; + int[] wt = { 1, 3, 4, 5 }; + int[] value = { 1, 4, 5, 7 }; int W = 10; t = new int[wt.length + 1][W + 1]; Arrays.stream(t).forEach(a -> Arrays.fill(a, -1)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java index be36d9535064..e3e221ea7aa9 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java @@ -35,9 +35,13 @@ private static int calculate_distance(String a, String b) { } else { cost = 1; } - distance_mat[i][j] - = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) - + cost; + distance_mat[i][j] = + minimum( + distance_mat[i - 1][j], + distance_mat[i - 1][j - 1], + distance_mat[i][j - 1] + ) + + cost; } } return distance_mat[len_a - 1][len_b - 1]; @@ -47,7 +51,9 @@ public static void main(String[] args) { String a = ""; // enter your string here String b = ""; // enter your string here - System.out.print("Levenshtein distance between " + a + " and " + b + " is: "); + System.out.print( + "Levenshtein distance between " + a + " and " + b + " is: " + ); System.out.println(calculate_distance(a, b)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java index 47e55eceb8cb..e3786ac6bbad 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java @@ -38,10 +38,8 @@ static int AlternatingLength(int arr[], int n) { /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { - /* Consider all elements as previous of arr[i]*/ for (int j = 0; j < i; j++) { - /* If arr[i] is greater, then check with las[j][1] */ if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) { las[i][0] = las[j][1] + 1; @@ -63,8 +61,12 @@ static int AlternatingLength(int arr[], int n) { } public static void main(String[] args) { - int arr[] = {10, 22, 9, 33, 49, 50, 31, 60}; + int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; - System.out.println("Length of Longest " + "alternating subsequence is " + AlternatingLength(arr, n)); + System.out.println( + "Length of Longest " + + "alternating subsequence is " + + AlternatingLength(arr, n) + ); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java index d28c0fe152e8..b749423642fe 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java @@ -3,7 +3,6 @@ class LongestCommonSubsequence { public static String getLCS(String str1, String str2) { - // At least one string is null if (str1 == null || str2 == null) { return null; @@ -31,15 +30,21 @@ public static String getLCS(String str1, String str2) { if (arr1[i - 1].equals(arr2[j - 1])) { lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1; } else { - lcsMatrix[i][j] - = lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1]; + lcsMatrix[i][j] = + lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] + ? lcsMatrix[i - 1][j] + : lcsMatrix[i][j - 1]; } } } return lcsString(str1, str2, lcsMatrix); } - public static String lcsString(String str1, String str2, int[][] lcsMatrix) { + public static String lcsString( + String str1, + String str2, + int[][] lcsMatrix + ) { StringBuilder lcs = new StringBuilder(); int i = str1.length(), j = str2.length(); while (i > 0 && j > 0) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java index ecf6ad6c41cc..3911d60bb718 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java @@ -8,7 +8,6 @@ public class LongestIncreasingSubsequence { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); int n = sc.nextInt(); @@ -48,7 +47,6 @@ private static int LIS(int[] array) { tail[0] = array[0]; for (int i = 1; i < N; i++) { - // new smallest value if (array[i] < tail[0]) { tail[0] = array[i]; @@ -86,6 +84,7 @@ public static int findLISLen(int a[]) { } return lis; } + // O(logn) private static int binarySearchBetween(int[] t, int end, int key) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java index 5a0f8b2e7e86..d3d7c36b2ef1 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java @@ -30,15 +30,18 @@ private static String recursiveLPS(String original, String reverse) { if (original.length() == 0 || reverse.length() == 0) { bestResult = ""; } else { - // if the last chars match, then remove it from both strings and recur - if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) { - String bestSubResult - = recursiveLPS( - original.substring(0, original.length() - 1), - reverse.substring(0, reverse.length() - 1)); + if ( + original.charAt(original.length() - 1) == + reverse.charAt(reverse.length() - 1) + ) { + String bestSubResult = recursiveLPS( + original.substring(0, original.length() - 1), + reverse.substring(0, reverse.length() - 1) + ); - bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; + bestResult = + reverse.charAt(reverse.length() - 1) + bestSubResult; } else { // otherwise (1) ignore the last character of reverse, and recur on original and updated // reverse again @@ -46,8 +49,14 @@ private static String recursiveLPS(String original, String reverse) { // again // then select the best result from these two subproblems. - String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1)); - String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse); + String bestSubResult1 = recursiveLPS( + original, + reverse.substring(0, reverse.length() - 1) + ); + String bestSubResult2 = recursiveLPS( + original.substring(0, original.length() - 1), + reverse + ); if (bestSubResult1.length() > bestSubResult2.length()) { bestResult = bestSubResult1; } else { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java index 4452700fddec..1d7bbe438cdf 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java @@ -24,7 +24,6 @@ private static String LPS(String input) { int start = 0, end = 0; for (int g = 0; g < input.length(); g++) { for (int i = 0, j = g; j < input.length(); i++, j++) { - if (g == 0) { arr[i][j] = true; } else if (g == 1) { @@ -34,8 +33,9 @@ private static String LPS(String input) { arr[i][j] = false; } } else { - - if (input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]) { + if ( + input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1] + ) { arr[i][j] = true; } else { arr[i][j] = false; @@ -50,5 +50,4 @@ private static String LPS(String input) { } return input.substring(start, end + 1); } - } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java index 5a4202b8be81..b2c0bedb1273 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java @@ -31,7 +31,10 @@ public static int getLongestValidParentheses(String s) { int index = i - res[i - 1] - 1; if (index >= 0 && chars[index] == '(') { // ()(()) - res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); + res[i] = + res[i - 1] + + 2 + + (index - 1 >= 0 ? res[index - 1] : 0); } } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java index 152d602c599e..5c4be18e38dc 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java @@ -16,7 +16,9 @@ public class MatrixChainMultiplication { public static void main(String[] args) { int count = 1; while (true) { - String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); + String[] mSize = input( + "input size of matrix A(" + count + ") ( ex. 10 20 ) : " + ); int col = Integer.parseInt(mSize[0]); if (col == 0) { break; @@ -28,7 +30,12 @@ public static void main(String[] args) { count++; } for (Matrix m : mArray) { - System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); + System.out.format( + "A(%d) = %2d x %2d%n", + m.count(), + m.col(), + m.row() + ); } size = mArray.size(); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java index 6ccdbf98b7d6..bf751e8c359e 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java @@ -2,7 +2,7 @@ // Matrix-chain Multiplication // Problem Statement -// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n, +// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n, // matrix Ai has dimension pi−1 ×pi // , fully parenthesize the product A1A2 ···An in a way that // minimizes the number of scalar multiplications. @@ -28,7 +28,10 @@ static int Lookup_Chain(int m[][], int p[], int i, int j) { return m[i][j]; } else { for (int k = i; k < j; k++) { - int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) + (p[i - 1] * p[k] * p[j]); + int q = + Lookup_Chain(m, p, i, k) + + Lookup_Chain(m, p, k + 1, j) + + (p[i - 1] * p[k] * p[j]); if (q < m[i][j]) { m[i][j] = q; } @@ -40,8 +43,9 @@ static int Lookup_Chain(int m[][], int p[], int i, int j) { // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively // output should be Minimum number of multiplications is 38 public static void main(String[] args) { - - int arr[] = {1, 2, 3, 4, 5}; - System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)); + int arr[] = { 1, 2, 3, 4, 5 }; + System.out.println( + "Minimum number of multiplications is " + Memoized_Matrix_Chain(arr) + ); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MemoizationTechniqueKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/MemoizationTechniqueKnapsack.java index 12ad52cbf809..bd64c3642e82 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MemoizationTechniqueKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MemoizationTechniqueKnapsack.java @@ -1,4 +1,5 @@ package com.thealgorithms.dynamicprogramming; + // Here is the top-down approach of // dynamic programming @@ -12,7 +13,6 @@ static int max(int a, int b) { // Returns the value of maximum profit static int knapSackRec(int W, int wt[], int val[], int n, int[][] dp) { - // Base condition if (n == 0 || W == 0) { return 0; @@ -22,21 +22,25 @@ static int knapSackRec(int W, int wt[], int val[], int n, int[][] dp) { return dp[n][W]; } - if (wt[n - 1] > W) // Store the value of function call - // stack in table before return - { + if ( + wt[n - 1] > W + ) { // stack in table before return // Store the value of function call return dp[n][W] = knapSackRec(W, wt, val, n - 1, dp); - } else // Return value of table after storing - { - return dp[n][W] - = max( - (val[n - 1] + knapSackRec(W - wt[n - 1], wt, val, n - 1, dp)), - knapSackRec(W, wt, val, n - 1, dp)); + } else { // Return value of table after storing + return ( + dp[n][W] = + max( + ( + val[n - 1] + + knapSackRec(W - wt[n - 1], wt, val, n - 1, dp) + ), + knapSackRec(W, wt, val, n - 1, dp) + ) + ); } } static int knapSack(int W, int wt[], int val[], int N) { - // Declare the table dynamically int dp[][] = new int[N + 1][W + 1]; @@ -53,8 +57,8 @@ static int knapSack(int W, int wt[], int val[], int N) { // Driver Code public static void main(String[] args) { - int val[] = {60, 100, 120}; - int wt[] = {10, 20, 30}; + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; int W = 50; int N = val.length; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java index 04adb0cebdd0..22e77c047754 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java @@ -28,33 +28,22 @@ The Space Complexity of your algorithm should be smaller than or equal to O(mn). public class MinimumPathSum { public void testRegular() { - int[][] grid = { - {1, 3, 1}, - {1, 5, 1}, - {4, 2, 1} - }; + int[][] grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } }; System.out.println(minimumPathSum(grid)); } public void testLessColumns() { - int[][] grid = { - {1, 2}, - {5, 6}, - {1, 1} - }; + int[][] grid = { { 1, 2 }, { 5, 6 }, { 1, 1 } }; System.out.println(minimumPathSum(grid)); } public void testLessRows() { - int[][] grid = { - {2, 3, 3}, - {7, 2, 1} - }; + int[][] grid = { { 2, 3, 3 }, { 7, 2, 1 } }; System.out.println(minimumPathSum(grid)); } public void testOneRowOneColumn() { - int[][] grid = {{2}}; + int[][] grid = { { 2 } }; System.out.println(minimumPathSum(grid)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java index c6f8f18b8a1a..78676c0085b4 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java @@ -1,4 +1,5 @@ package com.thealgorithms.dynamicprogramming; + // Partition a set into two subsets such that the difference of subset sums is minimum /* @@ -81,8 +82,8 @@ public static int getMin(int[] arr, int sum) { * Driver Code */ public static void main(String[] args) { - assert subSet(new int[]{1, 6, 11, 5}) == 1; - assert subSet(new int[]{36, 7, 46, 40}) == 23; - assert subSet(new int[]{1, 2, 3, 9}) == 3; + assert subSet(new int[] { 1, 6, 11, 5 }) == 1; + assert subSet(new int[] { 36, 7, 46, 40 }) == 23; + assert subSet(new int[] { 1, 2, 3, 9 }) == 3; } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java index 645f4cfa4595..e52d72fd4942 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java @@ -2,25 +2,23 @@ * Github : https://github.com/siddhant2002 */ - /** Program description - To find the New Man Shanks Prime. */ /** Wikipedia Link - https://en.wikipedia.org/wiki/Newman%E2%80%93Shanks%E2%80%93Williams_prime */ package com.thealgorithms.dynamicprogramming; public class NewManShanksPrime { - public static boolean nthManShanksPrime(int n , int expected_answer) - { - int a[] = new int[n+1]; + + public static boolean nthManShanksPrime(int n, int expected_answer) { + int a[] = new int[n + 1]; // array of n+1 size is initialized a[0] = a[1] = 1; // The 0th and 1st index position values are fixed. They are initialized as 1 - for(int i=2;i<=n;i++) - { - a[i]=2*a[i-1]+a[i-2]; + for (int i = 2; i <= n; i++) { + a[i] = 2 * a[i - 1] + a[i - 2]; } // The loop is continued till n - return a[n]==expected_answer; + return a[n] == expected_answer; // returns true if calculated answer matches with expected answer } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java index 46fbbb6569c3..e1218fefccb7 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java @@ -48,12 +48,14 @@ public static int minimalpartitions(String word) { if (L == 2) { isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)); } else { - if ((word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1]) { + if ( + (word.charAt(i) == word.charAt(j)) && + isPalindrome[i + 1][j - 1] + ) { isPalindrome[i][j] = true; } else { isPalindrome[i][j] = false; } - } } } @@ -65,7 +67,10 @@ public static int minimalpartitions(String word) { } else { minCuts[i] = Integer.MAX_VALUE; for (j = 0; j < i; j++) { - if (isPalindrome[j + 1][i] == true && 1 + minCuts[j] < minCuts[i]) { + if ( + isPalindrome[j + 1][i] == true && + 1 + minCuts[j] < minCuts[i] + ) { minCuts[i] = 1 + minCuts[j]; } } @@ -85,7 +90,11 @@ public static void main(String[] args) { // ans stores the final minimal cut count needed for partitioning int ans = minimalpartitions(word); System.out.println( - "The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans); + "The minimum cuts needed to partition \"" + + word + + "\" into palindromes is " + + ans + ); input.close(); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java index d9ab4c419511..238d8abcdae3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java @@ -52,7 +52,12 @@ static boolean regexRecursion(String src, String pat) { // Method 2: Using Recursion and breaking string using virtual index // Time Complexity=0(2^(N+M)) Space Complexity=Recursion Extra Space - static boolean regexRecursion(String src, String pat, int svidx, int pvidx) { + static boolean regexRecursion( + String src, + String pat, + int svidx, + int pvidx + ) { if (src.length() == svidx && pat.length() == pvidx) { return true; } @@ -85,7 +90,13 @@ static boolean regexRecursion(String src, String pat, int svidx, int pvidx) { // Method 3: Top-Down DP(Memoization) // Time Complexity=0(N*M) Space Complexity=0(N*M)+Recursion Extra Space - static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[][] strg) { + static boolean regexRecursion( + String src, + String pat, + int svidx, + int pvidx, + int[][] strg + ) { if (src.length() == svidx && pat.length() == pvidx) { return true; } @@ -123,7 +134,6 @@ static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[ // Method 4: Bottom-Up DP(Tabulation) // Time Complexity=0(N*M) Space Complexity=0(N*M) static boolean regexBU(String src, String pat) { - boolean strg[][] = new boolean[src.length() + 1][pat.length() + 1]; strg[src.length()][pat.length()] = true; for (int row = src.length(); row >= 0; row--) { @@ -156,16 +166,16 @@ static boolean regexBU(String src, String pat) { } public static void main(String[] args) { - String src = "aa"; String pat = "*"; System.out.println("Method 1: " + regexRecursion(src, pat)); System.out.println("Method 2: " + regexRecursion(src, pat, 0, 0)); - System.out.println("Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()])); + System.out.println( + "Method 3: " + + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]) + ); System.out.println("Method 4: " + regexBU(src, pat)); - } - } // Memoization vs Tabulation : https://www.geeksforgeeks.org/tabulation-vs-memoization/ // Question Link : https://practice.geeksforgeeks.org/problems/wildcard-pattern-matching/1 diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java index 58c122c485c6..90369b6ff0c1 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java @@ -25,7 +25,7 @@ private static int cutRod(int[] price, int n) { // main function to test public static void main(String args[]) { - int[] arr = new int[]{2, 5, 13, 19, 20}; + int[] arr = new int[] { 2, 5, 13, 19, 20 }; int result = cutRod(arr, arr.length); System.out.println("Maximum Obtainable Value is " + result); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java index 4b067d9fde72..722e0a8989f0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java @@ -34,8 +34,7 @@ static int lcs(String X, String Y, int m, int n) { } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { L[i][j] = L[i - 1][j - 1] + 1; } else { - L[i][j] = Math.max(L[i - 1][j], - L[i][j - 1]); + L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } } @@ -50,8 +49,10 @@ public static void main(String args[]) { String X = "AGGTAB"; String Y = "GXTXAYB"; - System.out.println("Length of the shortest " - + "supersequence is " - + shortestSuperSequence(X, Y)); + System.out.println( + "Length of the shortest " + + "supersequence is " + + shortestSuperSequence(X, Y) + ); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java index 1da65ce68401..89544266c9b3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java @@ -6,7 +6,7 @@ public class SubsetSum { * Driver Code */ public static void main(String[] args) { - int[] arr = new int[]{50, 4, 10, 15, 34}; + int[] arr = new int[] { 50, 4, 10, 15, 34 }; assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ assert subsetSum(arr, 99); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java b/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java index c40c65dbb886..896907757c89 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java @@ -3,8 +3,7 @@ public class Sum_Of_Subset { public static void main(String[] args) { - - int[] arr = {7, 3, 2, 5, 8}; + int[] arr = { 7, 3, 2, 5, 8 }; int Key = 14; if (subsetSum(arr, arr.length - 1, Key)) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java index 508227f098c3..7e45f681164b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java @@ -2,7 +2,6 @@ * Github : https://github.com/siddhant2002 */ - /** * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. @@ -17,51 +16,46 @@ import java.util.*; public class UniquePaths { - public static boolean uniquePaths(int m , int n , int ans) { - int []dp = new int[n]; - Arrays.fill(dp,1); - for (int i=1; i Math.abs(number) > Math.abs(absMaxWrapper.value)) - .forEach(number -> absMaxWrapper.value = number); + Arrays + .stream(numbers) + .skip(1) + .filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value)) + .forEach(number -> absMaxWrapper.value = number); return absMaxWrapper.value; } diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java index 9dc8b0111098..d5b278481aee 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java @@ -19,10 +19,11 @@ public static int getMinValue(int... numbers) { int value = numbers[0]; }; - Arrays.stream(numbers) - .skip(1) - .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)) - .forEach(number -> absMinWrapper.value = number); + Arrays + .stream(numbers) + .skip(1) + .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)) + .forEach(number -> absMinWrapper.value = number); return absMinWrapper.value; } diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index 7565d49c8acf..3525c368461a 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -22,10 +22,11 @@ public static int getAliquotValue(int number) { int value = 0; }; - IntStream.iterate(1, i -> ++i) - .limit(number / 2) - .filter(i -> number % i == 0) - .forEach(i -> sumWrapper.value += i); + IntStream + .iterate(1, i -> ++i) + .limit(number / 2) + .filter(i -> number % i == 0) + .forEach(i -> sumWrapper.value += i); return sumWrapper.value; } diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index 2cc13f3e1e44..4b49e21c726e 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -20,7 +20,6 @@ public class AmicableNumber { public static void main(String[] args) { - AmicableNumber.findAllInRange(1, 3000); /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210) 3: = ( 2620,2924) So it worked */ @@ -33,10 +32,9 @@ public static void main(String[] args) { * @return */ static void findAllInRange(int startValue, int stopValue) { - /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation - * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber - * */ + * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber + * */ StringBuilder res = new StringBuilder(); int countofRes = 0; @@ -44,19 +42,22 @@ static void findAllInRange(int startValue, int stopValue) { for (int j = i + 1; j <= stopValue; j++) { if (isAmicableNumber(i, j)) { countofRes++; - res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t"); + res.append( + "" + countofRes + ": = ( " + i + "," + j + ")" + "\t" + ); } } } res.insert( - 0, - "Int Range of " - + startValue - + " till " - + stopValue - + " there are " - + countofRes - + " Amicable_numbers.These are \n "); + 0, + "Int Range of " + + startValue + + " till " + + stopValue + + " there are " + + countofRes + + " Amicable_numbers.These are \n " + ); System.out.println(res.toString()); } @@ -68,9 +69,12 @@ static void findAllInRange(int startValue, int stopValue) { * otherwise false */ static boolean isAmicableNumber(int numberOne, int numberTwo) { - - return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo - && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo))); + return ( + ( + recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && + numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo) + ) + ); } /** @@ -81,7 +85,6 @@ static boolean isAmicableNumber(int numberOne, int numberTwo) { * @return sum of all the dividers */ static int recursiveCalcOfDividerSum(int number, int div) { - if (div == 1) { return 0; } else if (number % --div == 0) { diff --git a/src/main/java/com/thealgorithms/maths/Area.java b/src/main/java/com/thealgorithms/maths/Area.java index 31375f400402..c87bd6348d18 100644 --- a/src/main/java/com/thealgorithms/maths/Area.java +++ b/src/main/java/com/thealgorithms/maths/Area.java @@ -6,7 +6,6 @@ public class Area { public static void main(String[] args) { - /* test cube */ assert Double.compare(surfaceAreaCube(1), 6.0) == 0; @@ -33,16 +32,17 @@ public static void main(String[] args) { assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0; /* test cylinder */ - assert Double.compare(surfaceAreaCylinder(1, 2), 18.84955592153876) == 0; + assert Double.compare(surfaceAreaCylinder(1, 2), 18.84955592153876) == + 0; /* test hemisphere */ - assert Double.compare(surfaceAreaHemisphere(5), 235.61944901923448) == 0; + assert Double.compare(surfaceAreaHemisphere(5), 235.61944901923448) == + 0; assert Double.compare(surfaceAreaHemisphere(1), 9.42477796076938) == 0; /* test cone */ assert Double.compare(surfaceAreaCone(6, 8), 301.59289474462014) == 0; assert Double.compare(surfaceAreaCone(10, 24), 1130.9733552923256) == 0; - } /** @@ -127,7 +127,11 @@ private static double surfaceAreaParallelogram(double base, double height) { * @param height height of trapezium * @return area of given trapezium */ - private static double surfaceAreaTrapezium(double base1, double base2, double height) { + private static double surfaceAreaTrapezium( + double base1, + double base2, + double height + ) { return (base1 + base2) * height / 2; } @@ -159,6 +163,10 @@ private static double surfaceAreaHemisphere(double radius) { * @return surface area of given cone. */ private static double surfaceAreaCone(double radius, double height) { - return Math.PI * radius * (radius + Math.pow((height * height + radius * radius), 0.5)); + return ( + Math.PI * + radius * + (radius + Math.pow((height * height + radius * radius), 0.5)) + ); } } diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index fa1198ceaea3..dda8288a722f 100644 --- a/src/main/java/com/thealgorithms/maths/Armstrong.java +++ b/src/main/java/com/thealgorithms/maths/Armstrong.java @@ -26,4 +26,4 @@ public boolean isArmstrong(int number) { } return sum == number; } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java index 2444a3628b41..61bdd32f8beb 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -30,8 +30,7 @@ public static boolean isAutomorphic(int n) { } while (n != 0); s = Math.pow(10, c); r = p % (int) s; - if (m == r) //Checking if the original number entered is present at the end of the square - { + if (m == r) { //Checking if the original number entered is present at the end of the square return true; } else { return false; @@ -44,7 +43,9 @@ public static boolean isAutomorphic(int n) { * Number: 7 Output - It is not an Automorphic Number. */ public static void main(String args[]) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in) + ); System.out.println("Enter a Number: "); int n = Integer.parseInt(br.readLine()); if (isAutomorphic(n)) { diff --git a/src/main/java/com/thealgorithms/maths/Average.java b/src/main/java/com/thealgorithms/maths/Average.java index 3413f09aa29d..21ca818a957c 100644 --- a/src/main/java/com/thealgorithms/maths/Average.java +++ b/src/main/java/com/thealgorithms/maths/Average.java @@ -8,10 +8,19 @@ public class Average { private static final double SMALL_VALUE = 0.00001f; public static void main(String[] args) { - assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE; - assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE; - assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE; - int[] array = {2, 4, 10}; + assert Math.abs( + average(new double[] { 3, 6, 9, 12, 15, 18, 21 }) - 12 + ) < + SMALL_VALUE; + assert Math.abs( + average(new double[] { 5, 10, 15, 20, 25, 30, 35 }) - 20 + ) < + SMALL_VALUE; + assert Math.abs( + average(new double[] { 1, 2, 3, 4, 5, 6, 7, 8 }) - 4.5 + ) < + SMALL_VALUE; + int[] array = { 2, 4, 10 }; assert average(array) == 5; } diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java index 96b2c9ba86d4..18f0d12b67f8 100644 --- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java +++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java @@ -5,9 +5,9 @@ * Binomial Cofficients: A binomial cofficient C(n,k) gives number ways * in which k objects can be chosen from n objects. * Wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class BinomialCoefficient { @@ -20,8 +20,10 @@ public class BinomialCoefficient { * @return number of ways in which no_of_objects objects can be chosen from total_objects objects */ - public static int binomialCoefficient(int totalObjects, int numberOfObjects) { - + public static int binomialCoefficient( + int totalObjects, + int numberOfObjects + ) { // Base Case if (numberOfObjects > totalObjects) { return 0; @@ -33,7 +35,9 @@ public static int binomialCoefficient(int totalObjects, int numberOfObjects) { } // Recursive Call - return binomialCoefficient(totalObjects - 1, numberOfObjects - 1) - + binomialCoefficient(totalObjects - 1, numberOfObjects); + return ( + binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + + binomialCoefficient(totalObjects - 1, numberOfObjects) + ); } } diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java index 9b35ead01303..693fbbe9b38a 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -39,10 +39,10 @@ private static void padding(ArrayList x, int newSize) { * @return The convolved signal. */ public static ArrayList fftCircularConvolution( - ArrayList a, ArrayList b) { - int convolvedSize - = Math.max( - a.size(), b.size()); // The two signals must have the same size equal to the bigger one + ArrayList a, + ArrayList b + ) { + int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one padding(a, convolvedSize); // Zero padding the smaller signal padding(b, convolvedSize); diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index d7c94b7a1764..c5f48815de46 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -43,7 +43,9 @@ private static void padding(ArrayList x, int newSize) { * @return The convolved signal. */ public static ArrayList convolutionFFT( - ArrayList a, ArrayList b) { + ArrayList a, + ArrayList b + ) { int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal padding(a, convolvedSize); // Zero padding both signals padding(b, convolvedSize); @@ -57,9 +59,7 @@ public static ArrayList convolutionFFT( convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b) } FFT.fft(convolved, true); // IFFT - convolved - .subList(convolvedSize, convolved.size()) - .clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came from + convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came from // paddingPowerOfTwo() method inside the fft() method. return convolved; diff --git a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java index fc695876b1ea..52ddc75b7b5f 100644 --- a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java +++ b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java @@ -2,9 +2,9 @@ import java.util.*; -/* -* @author Ojasva Jain -* Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant +/* + * @author Ojasva Jain + * Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant */ public class DeterminantOfMatrix { diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java index 16f67e6d28e8..6a3541f3454d 100644 --- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java +++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java @@ -39,8 +39,7 @@ class DigitalRoot { public static int digitalRoot(int n) { - if (single(n) <= 9) // If n is already single digit than simply call single method and return the value - { + if (single(n) <= 9) { // If n is already single digit than simply call single method and return the value return single(n); } else { return digitalRoot(single(n)); @@ -49,17 +48,15 @@ public static int digitalRoot(int n) { // This function is used for finding the sum of digits of number public static int single(int n) { - if (n <= 9) // if n becomes less than 10 than return n - { + if (n <= 9) { // if n becomes less than 10 than return n return n; } else { - return (n % 10) + single(n / 10); // n % 10 for extracting digits one by one + return (n % 10) + single(n / 10); // n % 10 for extracting digits one by one } - } // n / 10 is the number obtainded after removing the digit one by one + } // n / 10 is the number obtainded after removing the digit one by one // Sum of digits is stored in the Stack memory and then finally returned } - /** * Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity : * O(Number of Digits) Constraints : 1 <= n <= 10^7 diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index 245aad9d80e2..96f8e6969f7c 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -1,46 +1,57 @@ package com.thealgorithms.maths; public class DistanceFormula { - public static double euclideanDistance(double x1, double y1, double x2, double y2) { - double dX = Math.pow(x2 - x1, 2); - double dY = Math.pow(y2 - x1, 2); - double d = Math.sqrt(dX + dY); - return d; - } - - public static double manhattanDistance(double x1, double y1, double x2, double y2) { - double d = Math.abs(x1 - x2) + Math.abs(y1 - y2); - return d; - } - - public static int hammingDistance(int[] b1, int[] b2) { - int d = 0; - - if (b1.length != b2.length) { - return -1; // error, both array must be have the same length - } - - for (int i = 0; i < b1.length; i++) { - d += Math.abs(b1[i] - b2[i]); - } - - return d; - } - - public static double minkowskiDistance(double[] p1, double[] p2, int p) { - double d = 0; - double distance = 0.0; - - if (p1.length != p2.length) { - return -1; // error, both array must be have the same length - } - - for (int i = 0; i < p1.length; i++) { - distance += Math.abs(Math.pow(p1[i] - p2[i], p)); - } - - distance = Math.pow(distance, (double) 1 / p); - d = distance; - return d; - } + + public static double euclideanDistance( + double x1, + double y1, + double x2, + double y2 + ) { + double dX = Math.pow(x2 - x1, 2); + double dY = Math.pow(y2 - x1, 2); + double d = Math.sqrt(dX + dY); + return d; + } + + public static double manhattanDistance( + double x1, + double y1, + double x2, + double y2 + ) { + double d = Math.abs(x1 - x2) + Math.abs(y1 - y2); + return d; + } + + public static int hammingDistance(int[] b1, int[] b2) { + int d = 0; + + if (b1.length != b2.length) { + return -1; // error, both array must be have the same length + } + + for (int i = 0; i < b1.length; i++) { + d += Math.abs(b1[i] - b2[i]); + } + + return d; + } + + public static double minkowskiDistance(double[] p1, double[] p2, int p) { + double d = 0; + double distance = 0.0; + + if (p1.length != p2.length) { + return -1; // error, both array must be have the same length + } + + for (int i = 0; i < p1.length; i++) { + distance += Math.abs(Math.pow(p1[i] - p2[i], p)); + } + + distance = Math.pow(distance, (double) 1 / p); + d = distance; + return d; + } } diff --git a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java index bb3b7608810a..945b5341c5b3 100644 --- a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java +++ b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java @@ -18,11 +18,10 @@ public static boolean isDudeney(int n) { if (cube_root * cube_root * cube_root != n) { return false; } - int sum_of_digits = 0;// Stores the sums of the digit of the entered number - int temp = n;//A temporary variable to store the entered number + int sum_of_digits = 0; // Stores the sums of the digit of the entered number + int temp = n; //A temporary variable to store the entered number // Loop to calculate sum of the digits. while (temp > 0) { - // Extracting Last digit of the number int rem = temp % 10; @@ -33,7 +32,7 @@ public static boolean isDudeney(int n) { temp /= 10; } - //If the cube root of the number is not equal to the sum of its digits we return false. + //If the cube root of the number is not equal to the sum of its digits we return false. if (cube_root != sum_of_digits) { return false; } @@ -47,7 +46,9 @@ public static boolean isDudeney(int n) { * 125 Output - It is not a Dudeney Number. */ public static void main(String args[]) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in) + ); System.out.println("Enter a Number: "); int n = Integer.parseInt(br.readLine()); if (isDudeney(n)) { diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index c4b154bb2808..4904c5038f04 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -26,24 +26,40 @@ public static void main(String[] args) { BiFunction exampleEquation1 = (x, y) -> x; ArrayList points1 = eulerFull(0, 4, 0.1, 0, exampleEquation1); assert points1.get(points1.size() - 1)[1] == 7.800000000000003; - points1.forEach( - point -> System.out.println(String.format("x: %1$f; y: %2$f", point[0], point[1]))); + points1.forEach(point -> + System.out.println( + String.format("x: %1$f; y: %2$f", point[0], point[1]) + ) + ); // example from https://en.wikipedia.org/wiki/Euler_method System.out.println("\n\nexample 2:"); BiFunction exampleEquation2 = (x, y) -> y; ArrayList points2 = eulerFull(0, 4, 0.1, 1, exampleEquation2); assert points2.get(points2.size() - 1)[1] == 45.25925556817596; - points2.forEach( - point -> System.out.println(String.format("x: %1$f; y: %2$f", point[0], point[1]))); + points2.forEach(point -> + System.out.println( + String.format("x: %1$f; y: %2$f", point[0], point[1]) + ) + ); // example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ System.out.println("\n\nexample 3:"); - BiFunction exampleEquation3 = (x, y) -> x + y + x * y; - ArrayList points3 = eulerFull(0, 0.1, 0.025, 1, exampleEquation3); + BiFunction exampleEquation3 = (x, y) -> + x + y + x * y; + ArrayList points3 = eulerFull( + 0, + 0.1, + 0.025, + 1, + exampleEquation3 + ); assert points3.get(points3.size() - 1)[1] == 1.1116729841674804; - points3.forEach( - point -> System.out.println(String.format("x: %1$f; y: %2$f", point[0], point[1]))); + points3.forEach(point -> + System.out.println( + String.format("x: %1$f; y: %2$f", point[0], point[1]) + ) + ); } /** @@ -57,14 +73,20 @@ public static void main(String[] args) { * @return The next y-value. */ public static double eulerStep( - double xCurrent, - double stepSize, - double yCurrent, - BiFunction differentialEquation) { + double xCurrent, + double stepSize, + double yCurrent, + BiFunction differentialEquation + ) { if (stepSize <= 0) { - throw new IllegalArgumentException("stepSize should be greater than zero"); + throw new IllegalArgumentException( + "stepSize should be greater than zero" + ); } - double yNext = yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent); + double yNext = + yCurrent + + stepSize * + differentialEquation.apply(xCurrent, yCurrent); return yNext; } @@ -81,29 +103,35 @@ public static double eulerStep( * equation. */ public static ArrayList eulerFull( - double xStart, - double xEnd, - double stepSize, - double yStart, - BiFunction differentialEquation) { + double xStart, + double xEnd, + double stepSize, + double yStart, + BiFunction differentialEquation + ) { if (xStart >= xEnd) { - throw new IllegalArgumentException("xEnd should be greater than xStart"); + throw new IllegalArgumentException( + "xEnd should be greater than xStart" + ); } if (stepSize <= 0) { - throw new IllegalArgumentException("stepSize should be greater than zero"); + throw new IllegalArgumentException( + "stepSize should be greater than zero" + ); } ArrayList points = new ArrayList(); - double[] firstPoint = {xStart, yStart}; + double[] firstPoint = { xStart, yStart }; points.add(firstPoint); double yCurrent = yStart; double xCurrent = xStart; while (xCurrent < xEnd) { // Euler method for next step - yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); + yCurrent = + eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); xCurrent += stepSize; - double[] point = {xCurrent, yCurrent}; + double[] point = { xCurrent, yCurrent }; points.add(point); } diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java index 41184e098fbb..998d0668f5fe 100644 --- a/src/main/java/com/thealgorithms/maths/FFT.java +++ b/src/main/java/com/thealgorithms/maths/FFT.java @@ -143,7 +143,7 @@ public double abs() { public Complex divide(Complex z) { Complex temp = new Complex(); double d = z.abs() * z.abs(); - d = (double)Math.round(d * 1000000000d) / 1000000000d; + d = (double) Math.round(d * 1000000000d) / 1000000000d; temp.real = (this.real * z.real + this.img * z.img) / (d); temp.img = (this.img * z.real - this.real * z.img) / (d); return temp; @@ -180,12 +180,15 @@ public Complex divide(double n) { * @param inverse True if you want to find the inverse FFT. * @return */ - public static ArrayList fft(ArrayList x, boolean inverse) { + public static ArrayList fft( + ArrayList x, + boolean inverse + ) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int N = x.size(); int log2N = findLog2(N); - x = fftBitReversal(N,log2N,x); + x = fftBitReversal(N, log2N, x); int direction = inverse ? -1 : 1; /* Main loop of the algorithm */ @@ -203,12 +206,12 @@ public static ArrayList fft(ArrayList x, boolean inverse) { } } } - x = inverseFFT(N,inverse,x); + x = inverseFFT(N, inverse, x); return x; } /* Find the log2(N) */ - public static int findLog2(int N){ + public static int findLog2(int N) { int log2N = 0; while ((1 << log2N) < N) { log2N++; @@ -217,7 +220,11 @@ public static int findLog2(int N){ } /* Swap the values of the signal with bit-reversal method */ - public static ArrayList fftBitReversal(int N, int log2N, ArrayList x){ + public static ArrayList fftBitReversal( + int N, + int log2N, + ArrayList x + ) { int reverse; for (int i = 0; i < N; i++) { reverse = reverseBits(i, log2N); @@ -229,7 +236,11 @@ public static ArrayList fftBitReversal(int N, int log2N, ArrayList inverseFFT(int N, boolean inverse, ArrayList x ){ + public static ArrayList inverseFFT( + int N, + boolean inverse, + ArrayList x + ) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); diff --git a/src/main/java/com/thealgorithms/maths/FFTBluestein.java b/src/main/java/com/thealgorithms/maths/FFTBluestein.java index b15143094997..ffd42bd57198 100644 --- a/src/main/java/com/thealgorithms/maths/FFTBluestein.java +++ b/src/main/java/com/thealgorithms/maths/FFTBluestein.java @@ -38,16 +38,26 @@ public static void fftBluestein(ArrayList x, boolean inverse) { for (int i = 0; i < N; i++) { double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction; bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle))); - bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle))); + bn.set( + bnSize - i - 1, + new FFT.Complex(Math.cos(angle), Math.sin(angle)) + ); } /* Initialization of the a(n) sequence */ for (int i = 0; i < N; i++) { double angle = -i * i * Math.PI / N * direction; - an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))); + an.add( + x + .get(i) + .multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle))) + ); } - ArrayList convolution = ConvolutionFFT.convolutionFFT(an, bn); + ArrayList convolution = ConvolutionFFT.convolutionFFT( + an, + bn + ); /* The final multiplication of the convolution with the b*(k) factor */ for (int i = 0; i < N; i++) { diff --git a/src/main/java/com/thealgorithms/maths/Factorial.java b/src/main/java/com/thealgorithms/maths/Factorial.java index 6ba6d4159721..4c31e69d78b3 100644 --- a/src/main/java/com/thealgorithms/maths/Factorial.java +++ b/src/main/java/com/thealgorithms/maths/Factorial.java @@ -21,8 +21,7 @@ public static long factorial(int n) { throw new IllegalArgumentException("number is negative"); } long factorial = 1; - for (int i = 1; i <= n; factorial *= i, ++i) - ; + for (int i = 1; i <= n; factorial *= i, ++i); return factorial; } } diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java index 205447c908d1..c8ba532b2598 100644 --- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java +++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java @@ -2,15 +2,14 @@ * Github : https://github.com/siddhant2002 */ - /** Program description - To find out the inverse square root of the given number*/ /** Wikipedia Link - https://en.wikipedia.org/wiki/Fast_inverse_square_root */ - package com.thealgorithms.maths; public class FastInverseSqrt { + public static boolean inverseSqrt(float number) { float x = number; float xhalf = 0.5f * x; @@ -18,15 +17,14 @@ public static boolean inverseSqrt(float number) { i = 0x5f3759df - (i >> 1); x = Float.intBitsToFloat(i); x = x * (1.5f - xhalf * x * x); - return x == (float)((float)1/(float)Math.sqrt(number)); + return x == (float) ((float) 1 / (float) Math.sqrt(number)); } - + /** * Returns the inverse square root of the given number upto 6 - 8 decimal places. * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false */ - public static boolean inverseSqrt(double number) { double x = number; double xhalf = 0.5d * x; @@ -37,23 +35,21 @@ public static boolean inverseSqrt(double number) { x = x * (1.5d - xhalf * x * x); } x *= number; - return x == 1/Math.sqrt(number); + return x == 1 / Math.sqrt(number); } /** * Returns the inverse square root of the given number upto 14 - 16 decimal places. * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false */ } - - /** - * OUTPUT : - * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 1st approach Time Complexity : O(1) - * Auxiliary Space Complexity : O(1) - * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 2nd approach Time Complexity : O(1) - * Auxiliary Space Complexity : O(1) - */ + * OUTPUT : + * Input - number = 4522 + * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. + * 1st approach Time Complexity : O(1) + * Auxiliary Space Complexity : O(1) + * Input - number = 4522 + * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. + * 2nd approach Time Complexity : O(1) + * Auxiliary Space Complexity : O(1) + */ diff --git a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java index f3b031b6d9f5..b6a39adf0517 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java @@ -25,28 +25,31 @@ public static Optional calculate(final BigDecimal index) { return Optional.of(BigDecimal.ONE); } - final List results = Stream.iterate( + final List results = Stream + .iterate( index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE) - ) - .reduce( - List.of(), - (list, current) - -> list.isEmpty() || list.size() < 2 + ) + .reduce( + List.of(), + (list, current) -> + list.isEmpty() || list.size() < 2 ? List.of(BigDecimal.ZERO, BigDecimal.ONE) : List.of(list.get(1), list.get(0).add(list.get(1))), - (list1, list2) -> list1 - ); + (list1, list2) -> list1 + ); return results.isEmpty() - ? Optional.empty() - : Optional.of(results.get(results.size() - 1)); + ? Optional.empty() + : Optional.of(results.get(results.size() - 1)); } public static void assertThat(final Object actual, final Object expected) { if (!Objects.equals(actual, expected)) { - throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); + throw new AssertionError( + String.format("expected=%s but was actual=%s", expected, actual) + ); } } @@ -88,27 +91,39 @@ public static void main(final String[] args) { { final Optional result = calculate(new BigDecimal(30)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal(832040))); + result.ifPresent(value -> assertThat(value, new BigDecimal(832040)) + ); } { final Optional result = calculate(new BigDecimal(40)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal(102334155))); + result.ifPresent(value -> + assertThat(value, new BigDecimal(102334155)) + ); } { final Optional result = calculate(new BigDecimal(50)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal(12586269025L))); + result.ifPresent(value -> + assertThat(value, new BigDecimal(12586269025L)) + ); } { final Optional result = calculate(new BigDecimal(100)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal("354224848179261915075"))); + result.ifPresent(value -> + assertThat(value, new BigDecimal("354224848179261915075")) + ); } { final Optional result = calculate(new BigDecimal(200)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525"))); + result.ifPresent(value -> + assertThat( + value, + new BigDecimal("280571172992510140037611932413038677189525") + ) + ); } } } diff --git a/src/main/java/com/thealgorithms/maths/FibonacciNumber.java b/src/main/java/com/thealgorithms/maths/FibonacciNumber.java index 41027edfb76c..17a8de61d1c9 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciNumber.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciNumber.java @@ -35,6 +35,9 @@ public static boolean isPerfectSquare(int number) { * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification */ public static boolean isFibonacciNumber(int number) { - return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); + return ( + isPerfectSquare(5 * number * number + 4) || + isPerfectSquare(5 * number * number - 4) + ); } } diff --git a/src/main/java/com/thealgorithms/maths/FindKthNumber.java b/src/main/java/com/thealgorithms/maths/FindKthNumber.java index 0d7f05fe571a..d869ca47c759 100644 --- a/src/main/java/com/thealgorithms/maths/FindKthNumber.java +++ b/src/main/java/com/thealgorithms/maths/FindKthNumber.java @@ -7,6 +7,7 @@ * use quick sort algorithm to get kth largest or kth smallest element in given array */ public class FindKthNumber { + private static final Random random = new Random(); public static void main(String[] args) { diff --git a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java index c38da196f46e..837cd321e971 100644 --- a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java @@ -17,8 +17,10 @@ public static void main(String[] args) { array[i] = rand.nextInt() % 100; } - assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); - assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); + assert max(array, array.length) == + Arrays.stream(array).max().getAsInt(); + assert max(array, 0, array.length - 1) == + Arrays.stream(array).max().getAsInt(); } /** @@ -50,6 +52,8 @@ public static int max(int[] array, int low, int high) { * @return max value of {@code array} */ public static int max(int[] array, int len) { - return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); + return len == 1 + ? array[0] + : Math.max(max(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java index 66400d23db3f..aeee582de01a 100644 --- a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java @@ -20,8 +20,10 @@ public static void main(String[] args) { array[i] = rand.nextInt() % 100; } - assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); - assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); + assert min(array, 0, array.length - 1) == + Arrays.stream(array).min().getAsInt(); + assert min(array, array.length) == + Arrays.stream(array).min().getAsInt(); } /** @@ -53,6 +55,8 @@ public static int min(int[] array, int low, int high) { * @return min value of {@code array} */ public static int min(int[] array, int len) { - return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); + return len == 1 + ? array[0] + : Math.min(min(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index 14c104b509c3..c05f96332e55 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -40,8 +40,7 @@ public static int gcd(int num1, int num2) { */ public static int gcd(int[] number) { int result = number[0]; - for (int i = 1; i < number.length; i++) // call gcd function (input two value) - { + for (int i = 1; i < number.length; i++) { // call gcd function (input two value) result = gcd(result, number[i]); } @@ -49,10 +48,14 @@ public static int gcd(int[] number) { } public static void main(String[] args) { - int[] myIntArray = {4, 16, 32}; + int[] myIntArray = { 4, 16, 32 }; // call gcd function (input array) System.out.println(gcd(myIntArray)); // => 4 - System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 + System.out.printf( + "gcd(40,24)=%d gcd(24,40)=%d%n", + gcd(40, 24), + gcd(24, 40) + ); // => 8 } } diff --git a/src/main/java/com/thealgorithms/maths/GCDRecursion.java b/src/main/java/com/thealgorithms/maths/GCDRecursion.java index df9a002be0f9..05e44f941ac7 100644 --- a/src/main/java/com/thealgorithms/maths/GCDRecursion.java +++ b/src/main/java/com/thealgorithms/maths/GCDRecursion.java @@ -22,7 +22,6 @@ public static void main(String[] args) { * @return gcd */ public static int gcd(int a, int b) { - if (a < 0 || b < 0) { throw new ArithmeticException(); } diff --git a/src/main/java/com/thealgorithms/maths/Gaussian.java b/src/main/java/com/thealgorithms/maths/Gaussian.java index 823e6a992b2d..9bb7c03586c6 100644 --- a/src/main/java/com/thealgorithms/maths/Gaussian.java +++ b/src/main/java/com/thealgorithms/maths/Gaussian.java @@ -4,7 +4,10 @@ public class Gaussian { - public static ArrayList gaussian(int mat_size, ArrayList matrix) { + public static ArrayList gaussian( + int mat_size, + ArrayList matrix + ) { ArrayList answerArray = new ArrayList(); int i, j = 0; @@ -24,7 +27,11 @@ public static ArrayList gaussian(int mat_size, ArrayList matrix) } // Perform Gaussian elimination - public static double[][] gaussianElimination(int mat_size, int i, double[][] mat) { + public static double[][] gaussianElimination( + int mat_size, + int i, + double[][] mat + ) { int step = 0; for (step = 0; step < mat_size - 1; step++) { for (i = step; i < mat_size - 1; i++) { @@ -39,7 +46,11 @@ public static double[][] gaussianElimination(int mat_size, int i, double[][] mat } // calculate the x_1, x_2,... values of the gaussian and save it in an arraylist. - public static ArrayList valueOfGaussian(int mat_size, double[][] x, double[][] mat) { + public static ArrayList valueOfGaussian( + int mat_size, + double[][] x, + double[][] mat + ) { ArrayList answerArray = new ArrayList(); int i, j; @@ -64,4 +75,4 @@ public static ArrayList valueOfGaussian(int mat_size, double[][] x, doub } return answerArray; } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/maths/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java index 153e369fb22b..9b24209bf528 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -19,7 +19,6 @@ public static void main(String[] args) { * @param a The number which should be checked */ public static void checkHarshadNumber(long a) { - long b = a; int sum = 0; diff --git a/src/main/java/com/thealgorithms/maths/HeronsFormula.java b/src/main/java/com/thealgorithms/maths/HeronsFormula.java index b3da87017829..72052a1b8d45 100644 --- a/src/main/java/com/thealgorithms/maths/HeronsFormula.java +++ b/src/main/java/com/thealgorithms/maths/HeronsFormula.java @@ -5,15 +5,14 @@ */ public class HeronsFormula { - - public static double Herons(int s1, int s2, int s3) - { - double a = s1; - double b = s2; - double c = s3; - double s = (a + b + c)/2.0; - double area = 0; - area = Math.sqrt((s)*(s-a)*(s-b)*(s-c)); - return area; - } + + public static double Herons(int s1, int s2, int s3) { + double a = s1; + double b = s2; + double c = s3; + double s = (a + b + c) / 2.0; + double area = 0; + area = Math.sqrt((s) * (s - a) * (s - b) * (s - c)); + return area; + } } diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java index f2f14b90b492..1e223f0fa860 100644 --- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java +++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java @@ -1,36 +1,36 @@ -package com.thealgorithms.maths; - - /** There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. - */ - - /** The rules of the game are as follows: - - 1.Start at the 1st friend. - 2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. - 3.The last friend you counted leaves the circle and loses the game. - 4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. - 5.Else, the last friend in the circle wins the game. - - @author Kunal - */ - -public class JosephusProblem { - - /** - * Find the Winner of the Circular Game. - * - * @param number of friends, n, and an integer k - * @return return the winner of the game - */ - - public static int findTheWinner(int n, int k) { - return winner(n, k) + 1; - } - - public static int winner(int n, int k){ - if (n == 1){ - return 0; - } - return (winner(n -1, k) + k) % n; - } -} +package com.thealgorithms.maths; + +/** There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. + */ + +/** The rules of the game are as follows: + + 1.Start at the 1st friend. + 2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. + 3.The last friend you counted leaves the circle and loses the game. + 4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. + 5.Else, the last friend in the circle wins the game. + + @author Kunal + */ + +public class JosephusProblem { + + /** + * Find the Winner of the Circular Game. + * + * @param number of friends, n, and an integer k + * @return return the winner of the game + */ + + public static int findTheWinner(int n, int k) { + return winner(n, k) + 1; + } + + public static int winner(int n, int k) { + if (n == 1) { + return 0; + } + return (winner(n - 1, k) + k) % n; + } +} diff --git a/src/main/java/com/thealgorithms/maths/JugglerSequence.java b/src/main/java/com/thealgorithms/maths/JugglerSequence.java index bb2c4bdc871c..da18dd647479 100644 --- a/src/main/java/com/thealgorithms/maths/JugglerSequence.java +++ b/src/main/java/com/thealgorithms/maths/JugglerSequence.java @@ -4,14 +4,15 @@ import java.util.List; /* - * Java program for printing juggler sequence + * Java program for printing juggler sequence * Wikipedia: https://en.wikipedia.org/wiki/Juggler_sequence - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class JugglerSequence { + /** * This method prints juggler sequence starting with the number in the parameter * @@ -34,7 +35,10 @@ public static void jugglerSequence(int inputNumber) { if (n % 2 == 0) { temp = (int) Math.floor(Math.sqrt(n)); } else { - temp = (int) Math.floor(Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)); + temp = + (int) Math.floor( + Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n) + ); } n = temp; seq.add(n + ""); diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index 7cdd182ab119..2d15dc4fe9a7 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -1,53 +1,68 @@ package com.thealgorithms.maths; + import java.math.BigInteger; import java.util.*; public class KaprekarNumbers { - /* This program demonstrates if a given number is Kaprekar Number or not. + /* This program demonstrates if a given number is Kaprekar Number or not. Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into two parts where the right part has n digits and sum of these parts is equal to the original number. */ - // Provides a list of kaprekarNumber in a range - public static ArrayList kaprekarNumberInRange(long start, long end) throws Exception { - long n = end-start; - if (n <0) throw new Exception("Invalid range"); - ArrayList list = new ArrayList<>(); - - for (long i = start; i <= end; i++) { - if (isKaprekarNumber(i)) list.add(i); - } + // Provides a list of kaprekarNumber in a range + public static ArrayList kaprekarNumberInRange(long start, long end) + throws Exception { + long n = end - start; + if (n < 0) throw new Exception("Invalid range"); + ArrayList list = new ArrayList<>(); - return list; - } + for (long i = start; i <= end; i++) { + if (isKaprekarNumber(i)) list.add(i); + } - // Checks whether a given number is Kaprekar Number or not - public static boolean isKaprekarNumber(long num) { - String number = Long.toString(num); - BigInteger originalNumber = new BigInteger(number); - BigInteger numberSquared = originalNumber.multiply(originalNumber); - if(number.length() == numberSquared.toString().length()){ - return number.equals(numberSquared.toString()); - } - else{ - BigInteger leftDigits1 = new BigInteger("0"); - BigInteger leftDigits2; - if(numberSquared.toString().contains("0")){ - leftDigits1 = new BigInteger( - numberSquared.toString(). - substring(0, numberSquared.toString().indexOf("0") - ) - ); - } - leftDigits2 = new BigInteger( - numberSquared.toString() - .substring(0, (numberSquared.toString().length() - number.length())) - ); - BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(numberSquared.toString().length() - number.length())); - String x = leftDigits1.add(rightDigits).toString(); - String y = leftDigits2.add(rightDigits).toString(); - return (number.equals(x)) || (number.equals(y)); - } - } + return list; + } + // Checks whether a given number is Kaprekar Number or not + public static boolean isKaprekarNumber(long num) { + String number = Long.toString(num); + BigInteger originalNumber = new BigInteger(number); + BigInteger numberSquared = originalNumber.multiply(originalNumber); + if (number.length() == numberSquared.toString().length()) { + return number.equals(numberSquared.toString()); + } else { + BigInteger leftDigits1 = new BigInteger("0"); + BigInteger leftDigits2; + if (numberSquared.toString().contains("0")) { + leftDigits1 = + new BigInteger( + numberSquared + .toString() + .substring(0, numberSquared.toString().indexOf("0")) + ); + } + leftDigits2 = + new BigInteger( + numberSquared + .toString() + .substring( + 0, + ( + numberSquared.toString().length() - + number.length() + ) + ) + ); + BigInteger rightDigits = new BigInteger( + numberSquared + .toString() + .substring( + numberSquared.toString().length() - number.length() + ) + ); + String x = leftDigits1.add(rightDigits).toString(); + String y = leftDigits2.add(rightDigits).toString(); + return (number.equals(x)) || (number.equals(y)); + } + } } diff --git a/src/main/java/com/thealgorithms/maths/KeithNumber.java b/src/main/java/com/thealgorithms/maths/KeithNumber.java index ddad3db38d5c..a96638b0febb 100644 --- a/src/main/java/com/thealgorithms/maths/KeithNumber.java +++ b/src/main/java/com/thealgorithms/maths/KeithNumber.java @@ -4,42 +4,42 @@ class KeithNumber { - //user-defined function that checks if the given number is Keith or not + //user-defined function that checks if the given number is Keith or not static boolean isKeith(int x) { - //List stores all the digits of the X + //List stores all the digits of the X ArrayList terms = new ArrayList(); - //n denotes the number of digits + //n denotes the number of digits int temp = x, n = 0; - //executes until the condition becomes false + //executes until the condition becomes false while (temp > 0) { - //determines the last digit of the number and add it to the List + //determines the last digit of the number and add it to the List terms.add(temp % 10); - //removes the last digit + //removes the last digit temp = temp / 10; - //increments the number of digits (n) by 1 + //increments the number of digits (n) by 1 n++; } - //reverse the List + //reverse the List Collections.reverse(terms); int next_term = 0, i = n; - //finds next term for the series - //loop executes until the condition returns true + //finds next term for the series + //loop executes until the condition returns true while (next_term < x) { next_term = 0; - //next term is the sum of previous n terms (it depends on number of digits the number has) + //next term is the sum of previous n terms (it depends on number of digits the number has) for (int j = 1; j <= n; j++) { next_term = next_term + terms.get(i - j); } terms.add(next_term); i++; } - //when the control comes out of the while loop, there will be two conditions: - //either next_term will be equal to x or greater than x - //if equal, the given number is Keith, else not + //when the control comes out of the while loop, there will be two conditions: + //either next_term will be equal to x or greater than x + //if equal, the given number is Keith, else not return (next_term == x); } - //driver code + //driver code public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); diff --git a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java index 10052acda684..64569be4b6c3 100644 --- a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java +++ b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java @@ -8,6 +8,7 @@ import java.io.*; public class KrishnamurthyNumber { + //returns True if the number is a Krishnamurthy number and False if it is not. public static boolean isKMurthy(int n) { @@ -44,8 +45,12 @@ public static boolean isKMurthy(int n) { } public static void main(String args[]) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("Enter a number to check if it is a Krishnamurthy number: "); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in) + ); + System.out.println( + "Enter a number to check if it is a Krishnamurthy number: " + ); int n = Integer.parseInt(br.readLine()); if (isKMurthy(n)) { System.out.println(n + " is a Krishnamurthy number."); diff --git a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java index c8c2d1ca56d2..6d3657469a62 100644 --- a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java +++ b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java @@ -1,45 +1,47 @@ package com.thealgorithms.maths; + import java.util.*; + /** - * Is a common mathematics concept to find the smallest value number - * that can be divide using either number without having the remainder. + * Is a common mathematics concept to find the smallest value number + * that can be divide using either number without having the remainder. * https://maticschool.blogspot.com/2013/11/find-least-common-multiple-lcm.html * @author LauKinHoong */ public class LeastCommonMultiple { + /** * Driver Code */ public static void main(String[] args) { - - Scanner input = new Scanner(System.in); + Scanner input = new Scanner(System.in); System.out.println("Please enter first number >> "); int num1 = input.nextInt(); System.out.println("Please enter second number >> "); int num2 = input.nextInt(); - System.out.println("The least common multiple of two numbers is >> " + lcm(num1,num2)); + System.out.println( + "The least common multiple of two numbers is >> " + lcm(num1, num2) + ); + } - } - /* * get least common multiple from two number */ - public static int lcm (int num1, int num2){ + public static int lcm(int num1, int num2) { int high, num3; int cmv = 0; /* * value selection for the numerator */ - if (num1 > num2){ + if (num1 > num2) { high = num3 = num1; - } - else{ + } else { high = num3 = num2; } - while(num1 != 0){ - if(high % num1 == 0 && high % num2 == 0){ + while (num1 != 0) { + if (high % num1 == 0 && high % num2 == 0) { cmv = high; break; } diff --git a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java index 8e05d248cc33..8af36e803c13 100644 --- a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java +++ b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java @@ -16,6 +16,5 @@ public static void main(String args[]) { for (int i = 0; i < 20; i++) { System.out.print(leonardoNumber(i) + " "); } - } } diff --git a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java index 19771f62169f..d6788ea1f72e 100644 --- a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java +++ b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java @@ -27,23 +27,39 @@ public static Solution findAnySolution(final Equation equation) { return toReturn; } - private static GcdSolutionWrapper gcd(final int a, final int b, final GcdSolutionWrapper previous) { + private static GcdSolutionWrapper gcd( + final int a, + final int b, + final GcdSolutionWrapper previous + ) { if (b == 0) { return new GcdSolutionWrapper(a, new Solution(1, 0)); } // stub wrapper becomes the `previous` of the next recursive call final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0)); - final var next = /* recursive call */ gcd(b, a % b, stubWrapper); + final var next = /* recursive call */gcd(b, a % b, stubWrapper); previous.getSolution().setX(next.getSolution().getY()); - previous.getSolution().setY(next.getSolution().getX() - (a / b) * (next.getSolution().getY())); + previous + .getSolution() + .setY( + next.getSolution().getX() - + (a / b) * + (next.getSolution().getY()) + ); previous.setGcd(next.getGcd()); return new GcdSolutionWrapper(next.getGcd(), previous.getSolution()); } public static final class Solution { - public static final Solution NO_SOLUTION = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE); - public static final Solution INFINITE_SOLUTIONS = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE); + public static final Solution NO_SOLUTION = new Solution( + Integer.MAX_VALUE, + Integer.MAX_VALUE + ); + public static final Solution INFINITE_SOLUTIONS = new Solution( + Integer.MIN_VALUE, + Integer.MIN_VALUE + ); private int x; private int y; @@ -77,8 +93,7 @@ public boolean equals(Object obj) { return false; } var that = (Solution) obj; - return this.x == that.x - && this.y == that.y; + return this.x == that.x && this.y == that.y; } @Override @@ -88,16 +103,11 @@ public int hashCode() { @Override public String toString() { - return "Solution[" - + "x=" + x + ", " - + "y=" + y + ']'; + return "Solution[" + "x=" + x + ", " + "y=" + y + ']'; } - } - public record Equation(int a, int b, int c) { - - } + public record Equation(int a, int b, int c) {} public static final class GcdSolutionWrapper { @@ -118,8 +128,10 @@ public boolean equals(Object obj) { return false; } var that = (GcdSolutionWrapper) obj; - return this.gcd == that.gcd - && Objects.equals(this.solution, that.solution); + return ( + this.gcd == that.gcd && + Objects.equals(this.solution, that.solution) + ); } public int getGcd() { @@ -145,10 +157,15 @@ public int hashCode() { @Override public String toString() { - return "GcdSolutionWrapper[" - + "gcd=" + gcd + ", " - + "solution=" + solution + ']'; + return ( + "GcdSolutionWrapper[" + + "gcd=" + + gcd + + ", " + + "solution=" + + solution + + ']' + ); } - } } diff --git a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java index 3d49cec08523..c8e753e4e937 100644 --- a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java +++ b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java @@ -2,33 +2,35 @@ /* * Java program for liouville lambda function - * For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity. + * For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity. * It has values in {−1, 1} depending on the factorization of n into prime factors: * λ(n) = +1 if n is a positive integer with an even number of prime factors. * λ(n) = −1 if n is a positive integer with an odd number of prime factors. * Wikipedia: https://en.wikipedia.org/wiki/Liouville_function - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class LiouvilleLambdaFunction { - /** - * This method returns λ(n) of given number n - * - * @param number Integer value which λ(n) is to be calculated - * @return 1 when number has even number of prime factors - * -1 when number has odd number of prime factors - * @throws IllegalArgumentException when number is negative - */ - static int liouvilleLambda(int number) { - if(number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException("Number must be greater than zero."); - } + /** + * This method returns λ(n) of given number n + * + * @param number Integer value which λ(n) is to be calculated + * @return 1 when number has even number of prime factors + * -1 when number has odd number of prime factors + * @throws IllegalArgumentException when number is negative + */ + static int liouvilleLambda(int number) { + if (number <= 0) { + //throw exception when number is less than or is zero + throw new IllegalArgumentException( + "Number must be greater than zero." + ); + } - //return 1 if size of prime factor list is even, -1 otherwise - return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1; - } + //return 1 if size of prime factor list is even, -1 otherwise + return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1; + } } diff --git a/src/main/java/com/thealgorithms/maths/LucasSeries.java b/src/main/java/com/thealgorithms/maths/LucasSeries.java index 1ac9e55717c4..e1d9c3361ba4 100644 --- a/src/main/java/com/thealgorithms/maths/LucasSeries.java +++ b/src/main/java/com/thealgorithms/maths/LucasSeries.java @@ -23,7 +23,9 @@ public static void main(String[] args) { * @return nth number of lucas series */ public static int lucasSeries(int n) { - return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); + return n == 1 + ? 2 + : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); } /** diff --git a/src/main/java/com/thealgorithms/maths/MagicSquare.java b/src/main/java/com/thealgorithms/maths/MagicSquare.java index f1b187d7a6fb..1f9683059575 100644 --- a/src/main/java/com/thealgorithms/maths/MagicSquare.java +++ b/src/main/java/com/thealgorithms/maths/MagicSquare.java @@ -7,7 +7,6 @@ public class MagicSquare { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); System.out.print("Input a number: "); int num = sc.nextInt(); @@ -23,7 +22,10 @@ public static void main(String[] args) { magic_square[row_num][col_num] = 1; for (int i = 2; i <= num * num; i++) { - if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) { + if ( + magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == + 0 + ) { row_num = (row_num - 1 + num) % num; col_num = (col_num + 1) % num; } else { @@ -45,6 +47,5 @@ public static void main(String[] args) { } System.out.println(); } - } } diff --git a/src/main/java/com/thealgorithms/maths/MatrixUtil.java b/src/main/java/com/thealgorithms/maths/MatrixUtil.java index dba86b7ae3de..4f5e048a6244 100644 --- a/src/main/java/com/thealgorithms/maths/MatrixUtil.java +++ b/src/main/java/com/thealgorithms/maths/MatrixUtil.java @@ -17,20 +17,34 @@ public static boolean isValid(final BigDecimal[][] matrix) { return matrix != null && matrix.length > 0 && matrix[0].length > 0; } - public static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { - return isValid(matrix1) && isValid(matrix2) - && matrix1.length == matrix2.length - && matrix1[0].length == matrix2[0].length; + public static boolean hasEqualSizes( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2 + ) { + return ( + isValid(matrix1) && + isValid(matrix2) && + matrix1.length == matrix2.length && + matrix1[0].length == matrix2[0].length + ); } - public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { - return isValid(matrix1) && isValid(matrix2) - && matrix1[0].length == matrix2.length; + public static boolean canMultiply( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2 + ) { + return ( + isValid(matrix1) && + isValid(matrix2) && + matrix1[0].length == matrix2.length + ); } - public static Optional operate(final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2, - final BiFunction operation) { + public static Optional operate( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2, + final BiFunction operation + ) { if (!hasEqualSizes(matrix1, matrix2)) { return Optional.empty(); } @@ -40,26 +54,43 @@ public static Optional operate(final BigDecimal[][] matrix1, final BigDecimal[][] result = new BigDecimal[rowSize][columnSize]; - IntStream.range(0, rowSize).forEach(rowIndex - -> IntStream.range(0, columnSize).forEach(columnIndex -> { - final BigDecimal value1 = matrix1[rowIndex][columnIndex]; - final BigDecimal value2 = matrix2[rowIndex][columnIndex]; - - result[rowIndex][columnIndex] = operation.apply(value1, value2); - })); + IntStream + .range(0, rowSize) + .forEach(rowIndex -> + IntStream + .range(0, columnSize) + .forEach(columnIndex -> { + final BigDecimal value1 = + matrix1[rowIndex][columnIndex]; + final BigDecimal value2 = + matrix2[rowIndex][columnIndex]; + + result[rowIndex][columnIndex] = + operation.apply(value1, value2); + }) + ); return Optional.of(result); } - public static Optional add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional add( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2 + ) { return operate(matrix1, matrix2, BigDecimal::add); } - public static Optional subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional subtract( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2 + ) { return operate(matrix1, matrix2, BigDecimal::subtract); } - public static Optional multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional multiply( + final BigDecimal[][] matrix1, + final BigDecimal[][] matrix2 + ) { if (!canMultiply(matrix1, matrix2)) { return Optional.empty(); } @@ -71,47 +102,65 @@ public static Optional multiply(final BigDecimal[][] matrix1, fi final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize]; - IntStream.range(0, matrix1RowSize).forEach(rowIndex - -> IntStream.range(0, matrix2ColumnSize).forEach(columnIndex - -> result[rowIndex][columnIndex] = IntStream.range(0, size).mapToObj(index -> { - final BigDecimal value1 = matrix1[rowIndex][index]; - final BigDecimal value2 = matrix2[index][columnIndex]; - - return value1.multiply(value2); - }) - .reduce(BigDecimal.ZERO, BigDecimal::add) - ) - ); + IntStream + .range(0, matrix1RowSize) + .forEach(rowIndex -> + IntStream + .range(0, matrix2ColumnSize) + .forEach(columnIndex -> + result[rowIndex][columnIndex] = + IntStream + .range(0, size) + .mapToObj(index -> { + final BigDecimal value1 = + matrix1[rowIndex][index]; + final BigDecimal value2 = + matrix2[index][columnIndex]; + + return value1.multiply(value2); + }) + .reduce(BigDecimal.ZERO, BigDecimal::add) + ) + ); return Optional.of(result); } - public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) { + public static void assertThat( + final BigDecimal[][] actual, + final BigDecimal[][] expected + ) { if (!Objects.deepEquals(actual, expected)) { - throw new AssertionError(String.format( + throw new AssertionError( + String.format( "expected=%s but was actual=%s", Arrays.deepToString(expected), Arrays.deepToString(actual) - )); + ) + ); } } public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - {new BigDecimal(3), new BigDecimal(2)}, - {new BigDecimal(0), new BigDecimal(1)},}; + { new BigDecimal(3), new BigDecimal(2) }, + { new BigDecimal(0), new BigDecimal(1) }, + }; final BigDecimal[][] matrix2 = { - {new BigDecimal(1), new BigDecimal(3)}, - {new BigDecimal(2), new BigDecimal(0)},}; + { new BigDecimal(1), new BigDecimal(3) }, + { new BigDecimal(2), new BigDecimal(0) }, + }; final BigDecimal[][] actual = add(matrix1, matrix2) - .orElseThrow(() -> new AssertionError("Could not compute matrix!")); + .orElseThrow(() -> + new AssertionError("Could not compute matrix!") + ); final BigDecimal[][] expected = { - {new BigDecimal(4), new BigDecimal(5)}, - {new BigDecimal(2), new BigDecimal(1)} + { new BigDecimal(4), new BigDecimal(5) }, + { new BigDecimal(2), new BigDecimal(1) }, }; assertThat(actual, expected); @@ -119,19 +168,23 @@ public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - {new BigDecimal(1), new BigDecimal(4)}, - {new BigDecimal(5), new BigDecimal(6)},}; + { new BigDecimal(1), new BigDecimal(4) }, + { new BigDecimal(5), new BigDecimal(6) }, + }; final BigDecimal[][] matrix2 = { - {new BigDecimal(2), new BigDecimal(0)}, - {new BigDecimal(-2), new BigDecimal(-3)},}; + { new BigDecimal(2), new BigDecimal(0) }, + { new BigDecimal(-2), new BigDecimal(-3) }, + }; final BigDecimal[][] actual = subtract(matrix1, matrix2) - .orElseThrow(() -> new AssertionError("Could not compute matrix!")); + .orElseThrow(() -> + new AssertionError("Could not compute matrix!") + ); final BigDecimal[][] expected = { - {new BigDecimal(-1), new BigDecimal(4)}, - {new BigDecimal(7), new BigDecimal(9)} + { new BigDecimal(-1), new BigDecimal(4) }, + { new BigDecimal(7), new BigDecimal(9) }, }; assertThat(actual, expected); @@ -139,24 +192,26 @@ public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - {new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)}, - {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, - {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)} + { new BigDecimal(1), new BigDecimal(2), new BigDecimal(3) }, + { new BigDecimal(4), new BigDecimal(5), new BigDecimal(6) }, + { new BigDecimal(7), new BigDecimal(8), new BigDecimal(9) }, }; final BigDecimal[][] matrix2 = { - {new BigDecimal(1), new BigDecimal(2)}, - {new BigDecimal(3), new BigDecimal(4)}, - {new BigDecimal(5), new BigDecimal(6)} + { new BigDecimal(1), new BigDecimal(2) }, + { new BigDecimal(3), new BigDecimal(4) }, + { new BigDecimal(5), new BigDecimal(6) }, }; final BigDecimal[][] actual = multiply(matrix1, matrix2) - .orElseThrow(() -> new AssertionError("Could not compute matrix!")); + .orElseThrow(() -> + new AssertionError("Could not compute matrix!") + ); final BigDecimal[][] expected = { - {new BigDecimal(22), new BigDecimal(28)}, - {new BigDecimal(49), new BigDecimal(64)}, - {new BigDecimal(76), new BigDecimal(100)} + { new BigDecimal(22), new BigDecimal(28) }, + { new BigDecimal(49), new BigDecimal(64) }, + { new BigDecimal(76), new BigDecimal(100) }, }; assertThat(actual, expected); diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java index 014fd07a870c..3bc8bae26c69 100644 --- a/src/main/java/com/thealgorithms/maths/Median.java +++ b/src/main/java/com/thealgorithms/maths/Median.java @@ -8,11 +8,11 @@ public class Median { public static void main(String[] args) { - assert median(new int[]{0}) == 0; - assert median(new int[]{1, 2}) == 1.5; - assert median(new int[]{4, 1, 3, 2}) == 2.5; - assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6; - assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5; + assert median(new int[] { 0 }) == 0; + assert median(new int[] { 1, 2 }) == 1.5; + assert median(new int[] { 4, 1, 3, 2 }) == 2.5; + assert median(new int[] { 1, 3, 3, 6, 7, 8, 9 }) == 6; + assert median(new int[] { 1, 2, 3, 4, 5, 6, 8, 9 }) == 4.5; } /** @@ -25,7 +25,7 @@ public static double median(int[] values) { Arrays.sort(values); int length = values.length; return length % 2 == 0 - ? (values[length / 2] + values[length / 2 - 1]) / 2.0 - : values[length / 2]; + ? (values[length / 2] + values[length / 2 - 1]) / 2.0 + : values[length / 2]; } } diff --git a/src/main/java/com/thealgorithms/maths/MobiusFunction.java b/src/main/java/com/thealgorithms/maths/MobiusFunction.java index a73da8daab45..5ed83c7c5833 100644 --- a/src/main/java/com/thealgorithms/maths/MobiusFunction.java +++ b/src/main/java/com/thealgorithms/maths/MobiusFunction.java @@ -2,56 +2,56 @@ /* * Java program for mobius function - * For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity. + * For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity. * It has values in {−1, 0, 1} depending on the factorization of n into prime factors: * μ(n) = +1 if n is a square-free positive integer with an even number of prime factors. * μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. * μ(n) = 0 if n has a squared prime factor. * Wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class MobiusFunction { - /** - * This method returns μ(n) of given number n - * - * @param number Integer value which μ(n) is to be calculated - * @return 1 when number is less than or equals 1 - * or number has even number of prime factors - * 0 when number has repeated prime factor - * -1 when number has odd number of prime factors - */ - static int mobius(int number) { - - if(number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException("Number must be greater than zero."); - } - - if(number == 1) { - //return 1 if number passed is less or is 1 - return 1; - } - - int primeFactorCount=0; - - for(int i = 1; i <= number; i++) { - //find prime factors of number - if(number % i == 0 && PrimeCheck.isPrime(i)) { - //check if number is divisible by square of prime factor - if(number % (i*i) == 0) { - //if number is divisible by square of prime factor - return 0; - } - /*increment primeFactorCount by 1 + /** + * This method returns μ(n) of given number n + * + * @param number Integer value which μ(n) is to be calculated + * @return 1 when number is less than or equals 1 + * or number has even number of prime factors + * 0 when number has repeated prime factor + * -1 when number has odd number of prime factors + */ + static int mobius(int number) { + if (number <= 0) { + //throw exception when number is less than or is zero + throw new IllegalArgumentException( + "Number must be greater than zero." + ); + } + + if (number == 1) { + //return 1 if number passed is less or is 1 + return 1; + } + + int primeFactorCount = 0; + + for (int i = 1; i <= number; i++) { + //find prime factors of number + if (number % i == 0 && PrimeCheck.isPrime(i)) { + //check if number is divisible by square of prime factor + if (number % (i * i) == 0) { + //if number is divisible by square of prime factor + return 0; + } + /*increment primeFactorCount by 1 if number is not divisible by square of found prime factor*/ - primeFactorCount++; - } - } - - return (primeFactorCount % 2 == 0) ? 1 : -1; - } + primeFactorCount++; + } + } + return (primeFactorCount % 2 == 0) ? 1 : -1; + } } diff --git a/src/main/java/com/thealgorithms/maths/Mode.java b/src/main/java/com/thealgorithms/maths/Mode.java index ee06b83e53b9..f90f70626ef5 100644 --- a/src/main/java/com/thealgorithms/maths/Mode.java +++ b/src/main/java/com/thealgorithms/maths/Mode.java @@ -14,23 +14,30 @@ public class Mode { public static void main(String[] args) { - /* Test array of integers */ - assert (mode(new int[]{})) == null; - assert Arrays.equals(mode(new int[]{5}), new int[]{5}); - assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5}); - assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7}); - assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9}); + assert (mode(new int[] {})) == null; + assert Arrays.equals(mode(new int[] { 5 }), new int[] { 5 }); + assert Arrays.equals( + mode(new int[] { 1, 2, 3, 4, 5 }), + new int[] { 1, 2, 3, 4, 5 } + ); + assert Arrays.equals( + mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 8 }), + new int[] { 7 } + ); + assert Arrays.equals( + mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 9 }), + new int[] { 7, 9 } + ); } /* - * Find the mode of an array of integers - * - * @param numbers array of integers - * @return mode of the array + * Find the mode of an array of integers + * + * @param numbers array of integers + * @return mode of the array */ public static int[] mode(int[] numbers) { - if (numbers.length == 0) { return null; } @@ -39,11 +46,8 @@ public static int[] mode(int[] numbers) { for (int num : numbers) { if (count.containsKey(num)) { - count.put(num, count.get(num) + 1); - } else { - count.put(num, 1); } } diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java index e0e59ded7d2c..6182e9668923 100644 --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java @@ -5,12 +5,11 @@ /* * Find the 2 elements which are non repeating in an array * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not on - * actual numbers. + * actual numbers. */ public class NonRepeatingElement { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); int i, res = 0; System.out.println("Enter the number of elements in the array"); @@ -22,7 +21,11 @@ public static void main(String[] args) { } int arr[] = new int[n]; - System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat"); + System.out.println( + "Enter " + + n + + " elements in the array. NOTE: Only 2 elements should not repeat" + ); for (i = 0; i < n; i++) { arr[i] = sc.nextInt(); } @@ -43,18 +46,17 @@ public static void main(String[] args) { int num1 = 0, num2 = 0; for (i = 0; i < n; i++) { - if ((res & arr[i]) > 0)//Case 1 explained below - { + if ((res & arr[i]) > 0) { //Case 1 explained below num1 ^= arr[i]; } else { - num2 ^= arr[i];//Case 2 explained below + num2 ^= arr[i]; //Case 2 explained below } } - System.out.println("The two non repeating elements are " + num1 + " and " + num2); - + System.out.println( + "The two non repeating elements are " + num1 + " and " + num2 + ); } - /* Explanation of the code: let us assume we have an array [1,2,1,2,3,4] diff --git a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java index 77e5653f6a87..7c5c540b7ae6 100644 --- a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java @@ -6,7 +6,17 @@ public class NumberOfDigits { public static void main(String[] args) { - int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789}; + int[] numbers = { + 0, + 12, + 123, + 1234, + -12345, + 123456, + 1234567, + 12345678, + 123456789, + }; for (int i = 0; i < numbers.length; ++i) { assert numberOfDigits(numbers[i]) == i + 1; assert numberOfDigitsFast(numbers[i]) == i + 1; @@ -37,7 +47,9 @@ private static int numberOfDigits(int number) { * @return number of digits of given number */ private static int numberOfDigitsFast(int number) { - return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); + return number == 0 + ? 1 + : (int) Math.floor(Math.log10(Math.abs(number)) + 1); } /** diff --git a/src/main/java/com/thealgorithms/maths/PalindromeNumber.java b/src/main/java/com/thealgorithms/maths/PalindromeNumber.java index 9796593e4069..56c34d3dc49c 100644 --- a/src/main/java/com/thealgorithms/maths/PalindromeNumber.java +++ b/src/main/java/com/thealgorithms/maths/PalindromeNumber.java @@ -3,7 +3,6 @@ public class PalindromeNumber { public static void main(String[] args) { - assert isPalindrome(12321); assert !isPalindrome(1234); assert isPalindrome(1); diff --git a/src/main/java/com/thealgorithms/maths/ParseInteger.java b/src/main/java/com/thealgorithms/maths/ParseInteger.java index d0cf89b949b7..e2e9e52ac14c 100644 --- a/src/main/java/com/thealgorithms/maths/ParseInteger.java +++ b/src/main/java/com/thealgorithms/maths/ParseInteger.java @@ -24,7 +24,11 @@ public static int parseInt(String s) { boolean isNegative = s.charAt(0) == '-'; boolean isPositive = s.charAt(0) == '+'; int number = 0; - for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { + for ( + int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); + i < length; + ++i + ) { if (!Character.isDigit(s.charAt(i))) { throw new NumberFormatException("s=" + s); } diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index b2ae1c5feb81..fb7468f242aa 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -1,5 +1,7 @@ package com.thealgorithms.maths; + public class PascalTriangle { + /** *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that arises * in probability theory, combinatorics, and algebra. In much of the Western world, it is named after @@ -31,8 +33,7 @@ public class PascalTriangle { * */ - public static int[][] pascal(int n) - { + public static int[][] pascal(int n) { /** * @param arr An auxiliary array to store generated pascal triangle values * @return @@ -42,22 +43,18 @@ public static int[][] pascal(int n) * @param line Iterate through every line and print integer(s) in it * @param i Represents the column number of the element we are currently on */ - for (int line = 0; line < n; line++) - { + for (int line = 0; line < n; line++) { /** * @Every line has number of integers equal to line number */ - for (int i = 0; i <= line; i++) - { + for (int i = 0; i <= line; i++) { // First and last values in every row are 1 - if (line == i || i == 0) - arr[line][i] = 1; - // The rest elements are sum of values just above and left of above - else - arr[line][i] = arr[line-1][i-1] + arr[line-1][i]; + if (line == i || i == 0) arr[line][i] = 1; + // The rest elements are sum of values just above and left of above + else arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; } } - + return arr; } } diff --git a/src/main/java/com/thealgorithms/maths/Perimeter.java b/src/main/java/com/thealgorithms/maths/Perimeter.java index 046b9b29fbb5..921538b17c89 100644 --- a/src/main/java/com/thealgorithms/maths/Perimeter.java +++ b/src/main/java/com/thealgorithms/maths/Perimeter.java @@ -1,11 +1,13 @@ package com.thealgorithms.maths; public class Perimeter { + public static void main(String[] args) { - System.out.println(perimeter_polygon(5,4)); - System.out.println(perimeter_rectangle(3,4)); - System.out.printf("%,3f",circumference(5)); + System.out.println(perimeter_polygon(5, 4)); + System.out.println(perimeter_rectangle(3, 4)); + System.out.printf("%,3f", circumference(5)); } + // Perimeter of different 2D geometrical shapes /** *Calculate the Perimeter of polygon. @@ -13,26 +15,28 @@ public static void main(String[] args) { * @parameter number of sides. * @return Perimeter of given polygon */ - public static float perimeter_polygon( int n, float side){ - float perimeter = n*side; + public static float perimeter_polygon(int n, float side) { + float perimeter = n * side; return perimeter; } + /** *Calculate the Perimeter of rectangle. * @parameter length and breadth. * @return Perimeter of given rectangle */ - public static float perimeter_rectangle( float length, float breadth){ - float perimeter = 2*(length + breadth); + public static float perimeter_rectangle(float length, float breadth) { + float perimeter = 2 * (length + breadth); return perimeter; } + /** *Calculate the circumference of circle. * @parameter radius of circle. * @return circumference of given circle. */ - public static double circumference( float r){ - double circumference = 2*Math.PI*r; + public static double circumference(float r) { + double circumference = 2 * Math.PI * r; return circumference; } } diff --git a/src/main/java/com/thealgorithms/maths/PiNilakantha.java b/src/main/java/com/thealgorithms/maths/PiNilakantha.java index 39dd51aed548..c60b3b5b634a 100644 --- a/src/main/java/com/thealgorithms/maths/PiNilakantha.java +++ b/src/main/java/com/thealgorithms/maths/PiNilakantha.java @@ -22,18 +22,25 @@ public static void main(String[] args) { */ public static double calculatePi(int iterations) { if (iterations < 0 || iterations > 500) { - throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); + throw new IllegalArgumentException( + "Please input Integer Number between 0 and 500" + ); } double pi = 3; int divCounter = 2; for (int i = 0; i < iterations; i++) { - if (i % 2 == 0) { - pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = + pi + + 4.0 / + (divCounter * (divCounter + 1) * (divCounter + 2)); } else { - pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = + pi - + 4.0 / + (divCounter * (divCounter + 1) * (divCounter + 2)); } divCounter += 2; diff --git a/src/main/java/com/thealgorithms/maths/PollardRho.java b/src/main/java/com/thealgorithms/maths/PollardRho.java index 36e7116c940e..59852c5adea5 100644 --- a/src/main/java/com/thealgorithms/maths/PollardRho.java +++ b/src/main/java/com/thealgorithms/maths/PollardRho.java @@ -35,40 +35,40 @@ * * */ public class PollardRho { - - /** - * This method returns a polynomial in x computed modulo n - * - * @param base Integer base of the polynomial - * @param modulus Integer is value which is to be used to perform modulo operation over the polynomial - * @return Integer (((base * base) - 1) % modulus) - */ - static int g(int base,int modulus) { - return ((base * base) - 1) % modulus; - } - - /** - * This method returns a non-trivial factor of given integer number - * - * @param number Integer is a integer value whose non-trivial factor is to be found - * @return Integer non-trivial factor of number - * @throws RuntimeException object if GCD of given number cannot be found - */ - static int pollardRho(int number) { - int x = 2, y = 2, d = 1; - while(d == 1) { - //tortoise move - x = g(x, number); - - //hare move - y = g(g(y, number), number); - - //check GCD of |x-y| and number - d = GCD.gcd(Math.abs(x - y), number); - } - if(d == number) { - throw new RuntimeException("GCD cannot be found."); - } - return d; - } + + /** + * This method returns a polynomial in x computed modulo n + * + * @param base Integer base of the polynomial + * @param modulus Integer is value which is to be used to perform modulo operation over the polynomial + * @return Integer (((base * base) - 1) % modulus) + */ + static int g(int base, int modulus) { + return ((base * base) - 1) % modulus; + } + + /** + * This method returns a non-trivial factor of given integer number + * + * @param number Integer is a integer value whose non-trivial factor is to be found + * @return Integer non-trivial factor of number + * @throws RuntimeException object if GCD of given number cannot be found + */ + static int pollardRho(int number) { + int x = 2, y = 2, d = 1; + while (d == 1) { + //tortoise move + x = g(x, number); + + //hare move + y = g(g(y, number), number); + + //check GCD of |x-y| and number + d = GCD.gcd(Math.abs(x - y), number); + } + if (d == number) { + throw new RuntimeException("GCD cannot be found."); + } + return d; + } } diff --git a/src/main/java/com/thealgorithms/maths/PrimeCheck.java b/src/main/java/com/thealgorithms/maths/PrimeCheck.java index fd06cb7f2bc6..5eb757acf598 100644 --- a/src/main/java/com/thealgorithms/maths/PrimeCheck.java +++ b/src/main/java/com/thealgorithms/maths/PrimeCheck.java @@ -12,13 +12,17 @@ public static void main(String[] args) { if (isPrime(n)) { System.out.println("algo1 verify that " + n + " is a prime number"); } else { - System.out.println("algo1 verify that " + n + " is not a prime number"); + System.out.println( + "algo1 verify that " + n + " is not a prime number" + ); } if (fermatPrimeChecking(n, 20)) { System.out.println("algo2 verify that " + n + " is a prime number"); } else { - System.out.println("algo2 verify that " + n + " is not a prime number"); + System.out.println( + "algo2 verify that " + n + " is not a prime number" + ); } scanner.close(); } @@ -52,19 +56,18 @@ public static boolean isPrime(int n) { * @param n the number * @return {@code true} if {@code n} is prime */ - public static boolean fermatPrimeChecking(int n, int iteration){ - long a; - int up = n - 2, down = 2; - for(int i=0;i pfactors(int n) { - - List primeFactors = new ArrayList<>(); - - if (n == 0) { - return primeFactors; - } - - while (n % 2 == 0) { - primeFactors.add(2); - n /= 2; - } - - for (int i = 3; i <= Math.sqrt(n); i += 2) { - while (n % i == 0) { - primeFactors.add(i); - n /= i; - } - } - - if (n > 2) { - primeFactors.add(n); - } - return primeFactors; - } + public static List pfactors(int n) { + List primeFactors = new ArrayList<>(); + + if (n == 0) { + return primeFactors; + } + + while (n % 2 == 0) { + primeFactors.add(2); + n /= 2; + } + + for (int i = 3; i <= Math.sqrt(n); i += 2) { + while (n % i == 0) { + primeFactors.add(i); + n /= i; + } + } + + if (n > 2) { + primeFactors.add(n); + } + return primeFactors; + } } diff --git a/src/main/java/com/thealgorithms/maths/PronicNumber.java b/src/main/java/com/thealgorithms/maths/PronicNumber.java index bfb295a615ca..15fae23a5b23 100644 --- a/src/main/java/com/thealgorithms/maths/PronicNumber.java +++ b/src/main/java/com/thealgorithms/maths/PronicNumber.java @@ -5,34 +5,30 @@ * Pronic Number: A number n is a pronic number if * it is equal to product of two consecutive numbers m and m+1. * Wikipedia: https://en.wikipedia.org/wiki/Pronic_number - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class PronicNumber { - /** + /** * This method checks if the given number is pronic number or non-pronic number * - * @param input_number Integer value which is to be checked if is a pronic number or not + * @param input_number Integer value which is to be checked if is a pronic number or not * @return true if input number is a pronic number, false otherwise */ - static boolean isPronic(int input_number) { - - //Iterating from 0 to input_number - for(int i = 0; i <= input_number; i++) { - - //Checking if product of i and (i+1) is equals input_number - if(i * (i+1) == input_number && i != input_number) { - - //return true if product of i and (i+1) is equals input_number - return true; - } - - } - - //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number - return false; - } + static boolean isPronic(int input_number) { + //Iterating from 0 to input_number + for (int i = 0; i <= input_number; i++) { + //Checking if product of i and (i+1) is equals input_number + if (i * (i + 1) == input_number && i != input_number) { + //return true if product of i and (i+1) is equals input_number + return true; + } + } + + //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number + return false; + } } diff --git a/src/main/java/com/thealgorithms/maths/ReverseNumber.java b/src/main/java/com/thealgorithms/maths/ReverseNumber.java index 5b489d9a2cf4..a78c4de82163 100644 --- a/src/main/java/com/thealgorithms/maths/ReverseNumber.java +++ b/src/main/java/com/thealgorithms/maths/ReverseNumber.java @@ -1,8 +1,8 @@ package com.thealgorithms.maths; -import java.util.Scanner; -import java.util.NoSuchElementException; import java.lang.IllegalStateException; +import java.util.NoSuchElementException; +import java.util.Scanner; public class ReverseNumber { diff --git a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java index dda07a5ae819..ead630a7955e 100644 --- a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java +++ b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java @@ -13,28 +13,70 @@ public class RomanNumeralUtil { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 5999; //1000-5999 - private static final String[] RN_M = {"", "M", "MM", "MMM", "MMMM", "MMMMM"}; + private static final String[] RN_M = { + "", + "M", + "MM", + "MMM", + "MMMM", + "MMMMM", + }; //100-900 - private static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + private static final String[] RN_C = { + "", + "C", + "CC", + "CCC", + "CD", + "D", + "DC", + "DCC", + "DCCC", + "CM", + }; //10-90 - private static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + private static final String[] RN_X = { + "", + "X", + "XX", + "XXX", + "XL", + "L", + "LX", + "LXX", + "LXXX", + "XC", + }; //1-9 - private static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + private static final String[] RN_I = { + "", + "I", + "II", + "III", + "IV", + "V", + "VI", + "VII", + "VIII", + "IX", + }; public static String generate(int number) { if (number < MIN_VALUE || number > MAX_VALUE) { throw new IllegalArgumentException( - String.format( - "The number must be in the range [%d, %d]", - MIN_VALUE, - MAX_VALUE - ) + String.format( + "The number must be in the range [%d, %d]", + MIN_VALUE, + MAX_VALUE + ) ); } - return RN_M[number / 1000] - + RN_C[number % 1000 / 100] - + RN_X[number % 100 / 10] - + RN_I[number % 10]; + return ( + RN_M[number / 1000] + + RN_C[number % 1000 / 100] + + RN_X[number % 100 / 10] + + RN_I[number % 10] + ); } } diff --git a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java index 473afc4a3702..d9efb5e976e6 100644 --- a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java +++ b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java @@ -25,7 +25,9 @@ public static void main(String[] args) { // Check so that N is even if (N % 2 != 0) { - System.out.println("N must be even number for Simpsons method. Aborted"); + System.out.println( + "N must be even number for Simpsons method. Aborted" + ); System.exit(1); } @@ -83,7 +85,6 @@ public double simpsonsMethod(int N, double h, double a) { // Function f(x) = e^(-x) * (4 - x^2) public double f(double x) { return Math.exp(-x) * (4 - Math.pow(x, 2)); -// return Math.sqrt(x); + // return Math.sqrt(x); } - } diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java index a79927fc4076..2f8fa9a83885 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java @@ -1,15 +1,14 @@ package com.thealgorithms.maths; - public class SquareRootWithBabylonianMethod { + /** * get the value, return the square root * * @param num contains elements * @return the square root of num */ - public static float square_Root(float num) - { + public static float square_Root(float num) { float a = num; float b = 1; double e = 0.000001; @@ -19,5 +18,4 @@ public static float square_Root(float num) } return a; } - } diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 05bb0e7a9e3d..1cfe8b63af62 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -3,30 +3,28 @@ import java.util.Scanner; /* -*To learn about the method, visit the link below : -* https://en.wikipedia.org/wiki/Newton%27s_method -* -* To obtain the square root, no built-in functions should be used -* -* The formula to calculate the root is : root = 0.5(x + n/x), -* here, n is the no. whose square root has to be calculated and -* x has to be guessed such that, the calculation should result into -* the square root of n. -* And the root will be obtained when the error < 0.5 or the precision value can also -* be changed according to the user preference. -*/ + *To learn about the method, visit the link below : + * https://en.wikipedia.org/wiki/Newton%27s_method + * + * To obtain the square root, no built-in functions should be used + * + * The formula to calculate the root is : root = 0.5(x + n/x), + * here, n is the no. whose square root has to be calculated and + * x has to be guessed such that, the calculation should result into + * the square root of n. + * And the root will be obtained when the error < 0.5 or the precision value can also + * be changed according to the user preference. + */ public class SquareRootWithNewtonRaphsonMethod { - public static double squareRoot (int n) { + public static double squareRoot(int n) { + double x = n; //initially taking a guess that x = n. + double root = 0.5 * (x + n / x); //applying Newton-Raphson Method. - double x = n; //initially taking a guess that x = n. - double root = 0.5 * (x + n/x); //applying Newton-Raphson Method. - - while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here. - - x = root; //decreasing the value of x to root, i.e. decreasing the guess. - root = 0.5 * (x + n/x); + while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here. + x = root; //decreasing the value of x to root, i.e. decreasing the guess. + root = 0.5 * (x + n / x); } return root; diff --git a/src/main/java/com/thealgorithms/maths/StandardDeviation.java b/src/main/java/com/thealgorithms/maths/StandardDeviation.java index 70885eee1b50..84d21f3082f0 100644 --- a/src/main/java/com/thealgorithms/maths/StandardDeviation.java +++ b/src/main/java/com/thealgorithms/maths/StandardDeviation.java @@ -1,22 +1,18 @@ package com.thealgorithms.maths; public class StandardDeviation { - - public static double stdDev(double[] data) - { - double var = 0; - double avg = 0; - for (int i = 0; i < data.length; i++) - { - avg += data[i]; - } - avg /= data.length; - for (int j = 0; j < data.length; j++) - { - var += Math.pow((data[j] - avg), 2); - } - var /= data.length; - return Math.sqrt(var); - } - + + public static double stdDev(double[] data) { + double var = 0; + double avg = 0; + for (int i = 0; i < data.length; i++) { + avg += data[i]; + } + avg /= data.length; + for (int j = 0; j < data.length; j++) { + var += Math.pow((data[j] - avg), 2); + } + var /= data.length; + return Math.sqrt(var); + } } diff --git a/src/main/java/com/thealgorithms/maths/StandardScore.java b/src/main/java/com/thealgorithms/maths/StandardScore.java index fc794e1ec508..42a41f3cb036 100644 --- a/src/main/java/com/thealgorithms/maths/StandardScore.java +++ b/src/main/java/com/thealgorithms/maths/StandardScore.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; public class StandardScore { - public static double zScore(double num, double mean, double stdDev) - { - double z = (num - mean)/stdDev; - return z; - } + + public static double zScore(double num, double mean, double stdDev) { + double z = (num - mean) / stdDev; + return z; + } } diff --git a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java index d6db0ab9712c..688756d09373 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java +++ b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java @@ -13,7 +13,6 @@ public class SumOfArithmeticSeries { public static void main(String[] args) { - /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */ assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0; @@ -37,7 +36,13 @@ public static void main(String[] args) { * @param numOfTerms the total terms of an arithmetic series * @return sum of given arithmetic series */ - private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { - return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff); + private static double sumOfSeries( + double firstTerm, + double commonDiff, + int numOfTerms + ) { + return ( + numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff) + ); } } diff --git a/src/main/java/com/thealgorithms/maths/SumOfDigits.java b/src/main/java/com/thealgorithms/maths/SumOfDigits.java index 5ac8525c1d3a..22d059d92ea6 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/SumOfDigits.java @@ -3,13 +3,17 @@ public class SumOfDigits { public static void main(String[] args) { - assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6; + assert sumOfDigits(-123) == 6 && + sumOfDigitsRecursion(-123) == 6 && + sumOfDigitsFast(-123) == 6; - assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0; + assert sumOfDigits(0) == 0 && + sumOfDigitsRecursion(0) == 0 && + sumOfDigitsFast(0) == 0; - assert sumOfDigits(12345) == 15 - && sumOfDigitsRecursion(12345) == 15 - && sumOfDigitsFast(12345) == 15; + assert sumOfDigits(12345) == 15 && + sumOfDigitsRecursion(12345) == 15 && + sumOfDigitsFast(12345) == 15; } /** @@ -38,7 +42,9 @@ public static int sumOfDigits(int number) { public static int sumOfDigitsRecursion(int number) { number = number < 0 ? -number : number; /* calculate abs value */ - return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10); + return number < 10 + ? number + : number % 10 + sumOfDigitsRecursion(number / 10); } /** diff --git a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java index 2b7ce2a9c68d..587886ee71bd 100644 --- a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java +++ b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java @@ -18,7 +18,11 @@ public static int TrinomialValue(int n, int k) { return 0; } - return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); + return ( + TrinomialValue(n - 1, k - 1) + + TrinomialValue(n - 1, k) + + TrinomialValue(n - 1, k + 1) + ); } public static void printTrinomial(int n) { diff --git a/src/main/java/com/thealgorithms/maths/VampireNumber.java b/src/main/java/com/thealgorithms/maths/VampireNumber.java index bdb8a61f40bc..fab745aae20a 100644 --- a/src/main/java/com/thealgorithms/maths/VampireNumber.java +++ b/src/main/java/com/thealgorithms/maths/VampireNumber.java @@ -19,7 +19,6 @@ public class VampireNumber { public static void main(String[] args) { - test(10, 1000); } @@ -32,15 +31,30 @@ static void test(int startValue, int stopValue) { // System.out.println(i+ " "+ j); if (isVampireNumber(i, j, true)) { countofRes++; - res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n"); + res.append( + "" + + countofRes + + ": = ( " + + i + + "," + + j + + " = " + + i * + j + + ")" + + "\n" + ); } } } System.out.println(res); } - static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) { - + static boolean isVampireNumber( + int a, + int b, + boolean noPseudoVamireNumbers + ) { // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for // example // 126 = 6 x 21 @@ -58,7 +72,6 @@ static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) { // methode to Split the numbers to Digits static String splitIntoDigits(int num, int num2) { - StringBuilder res = new StringBuilder(); ArrayList digits = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java index 1b194a55d54a..f9e903b9ff72 100644 --- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java +++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java @@ -121,7 +121,5 @@ static void test() { //Determine dot product int dotProd = A.dotProduct(B); System.out.println("Dot Product of A and B: " + dotProd); - } - } diff --git a/src/main/java/com/thealgorithms/maths/Volume.java b/src/main/java/com/thealgorithms/maths/Volume.java index c1c20a6c3398..4348a1153d0d 100644 --- a/src/main/java/com/thealgorithms/maths/Volume.java +++ b/src/main/java/com/thealgorithms/maths/Volume.java @@ -1,11 +1,9 @@ package com.thealgorithms.maths; - /* Find volume of various shapes.*/ public class Volume { public static void main(String[] args) { - /* test cube */ assert Double.compare(volumeCube(7), 343.0) == 0; @@ -23,13 +21,12 @@ public static void main(String[] args) { /* test cone */ assert Double.compare(volumeCone(5, 7), 916.297857297023) == 0; - + /*test prism*/ assert Double.compare(volumePrism(10, 2), 20.0) == 0; - + /*test pyramid*/ assert Double.compare(volumePyramid(10, 3), 10.0) == 0; - } /** @@ -50,7 +47,11 @@ private static double volumeCube(double sidelength) { * @param length of cuboid * @return volume of given cuboid */ - private static double volumeCuboid(double width, double height, double length) { + private static double volumeCuboid( + double width, + double height, + double length + ) { return width * height * length; } @@ -95,7 +96,7 @@ private static double volumeHemisphere(double radius) { private static double volumeCone(double radius, double height) { return Math.PI * radius * radius * height / 3; } - + /** * Calculate the volume of a prism. * @@ -106,7 +107,7 @@ private static double volumeCone(double radius, double height) { private static double volumePrism(double basearea, double height) { return basearea * height; } - + /** * Calculate the volume of a pyramid. * diff --git a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java index abbd74f6a427..7a370d0fc5b7 100644 --- a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java @@ -10,10 +10,10 @@ public class Fibonacci { // Exponentiation matrix for Fibonacci sequence - private static final int[][] fibMatrix = {{1, 1}, {1, 0}}; - private static final int[][] identityMatrix = {{1, 0}, {0, 1}}; + private static final int[][] fibMatrix = { { 1, 1 }, { 1, 0 } }; + private static final int[][] identityMatrix = { { 1, 0 }, { 0, 1 } }; //First 2 fibonacci numbers - private static final int[][] baseFibNumbers = {{1}, {0}}; + private static final int[][] baseFibNumbers = { { 1 }, { 0 } }; /** * Performs multiplication of 2 matrices @@ -22,7 +22,10 @@ public class Fibonacci { * @param matrix2 * @return The product of matrix1 and matrix2 */ - private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) { + private static int[][] matrixMultiplication( + int[][] matrix1, + int[][] matrix2 + ) { //Check if matrices passed can be multiplied int rowsInMatrix1 = matrix1.length; int columnsInMatrix1 = matrix1[0].length; @@ -35,8 +38,14 @@ private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) { for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) { for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) { int matrixEntry = 0; - for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; intermediateIndex++) { - matrixEntry += matrix1[rowIndex][intermediateIndex] * matrix2[intermediateIndex][colIndex]; + for ( + int intermediateIndex = 0; + intermediateIndex < columnsInMatrix1; + intermediateIndex++ + ) { + matrixEntry += + matrix1[rowIndex][intermediateIndex] * + matrix2[intermediateIndex][colIndex]; } product[rowIndex][colIndex] = matrixEntry; } @@ -56,11 +65,17 @@ public static int[][] fib(int n) { return Fibonacci.identityMatrix; } else { int[][] cachedResult = fib(n / 2); - int[][] matrixExpResult = matrixMultiplication(cachedResult, cachedResult); + int[][] matrixExpResult = matrixMultiplication( + cachedResult, + cachedResult + ); if (n % 2 == 0) { return matrixExpResult; } else { - return matrixMultiplication(Fibonacci.fibMatrix, matrixExpResult); + return matrixMultiplication( + Fibonacci.fibMatrix, + matrixExpResult + ); } } } diff --git a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java index 4870ae35556b..495492ed225f 100644 --- a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java +++ b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java @@ -23,7 +23,9 @@ public Schedule(int t, int d) { public static void main(String[] args) throws IOException { StringTokenizer token; - BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt")); + BufferedReader in = new BufferedReader( + new FileReader("MinimizingLateness/lateness_data.txt") + ); String ch = in.readLine(); if (ch == null || ch.isEmpty()) { in.close(); @@ -38,8 +40,11 @@ public static void main(String[] args) throws IOException { token = new StringTokenizer(ch, " "); // Include the time required for the operation to be performed in the array and the time it // should be completed. - array[i] - = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken())); + array[i] = + new Schedule( + Integer.parseInt(token.nextToken()), + Integer.parseInt(token.nextToken()) + ); i++; System.out.println(array[i - 1].t + " " + array[i - 1].d); } diff --git a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java index 23fd2f3ead62..96192e0bcecb 100644 --- a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java +++ b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java @@ -54,7 +54,9 @@ public double getRelativeLuminance(Color color) { */ public double getColor(int color8Bit) { final double sRgb = getColorSRgb(color8Bit); - return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4); + return (sRgb <= 0.03928) + ? sRgb / 12.92 + : Math.pow((sRgb + 0.055) / 1.055, 2.4); } /** @@ -81,25 +83,38 @@ private static void test() { final Color black = Color.BLACK; final double blackLuminance = algImpl.getRelativeLuminance(black); - assert blackLuminance == 0 : "Test 1 Failed - Incorrect relative luminance."; + assert blackLuminance == + 0 : "Test 1 Failed - Incorrect relative luminance."; final Color white = Color.WHITE; final double whiteLuminance = algImpl.getRelativeLuminance(white); - assert whiteLuminance == 1 : "Test 2 Failed - Incorrect relative luminance."; + assert whiteLuminance == + 1 : "Test 2 Failed - Incorrect relative luminance."; final double highestColorRatio = algImpl.getContrastRatio(black, white); - assert highestColorRatio == 21 : "Test 3 Failed - Incorrect contrast ratio."; + assert highestColorRatio == + 21 : "Test 3 Failed - Incorrect contrast ratio."; final Color foreground = new Color(23, 103, 154); - final double foregroundLuminance = algImpl.getRelativeLuminance(foreground); - assert foregroundLuminance == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; + final double foregroundLuminance = algImpl.getRelativeLuminance( + foreground + ); + assert foregroundLuminance == + 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; final Color background = new Color(226, 229, 248); - final double backgroundLuminance = algImpl.getRelativeLuminance(background); - assert backgroundLuminance == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance."; - - final double contrastRatio = algImpl.getContrastRatio(foreground, background); - assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; + final double backgroundLuminance = algImpl.getRelativeLuminance( + background + ); + assert backgroundLuminance == + 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance."; + + final double contrastRatio = algImpl.getContrastRatio( + foreground, + background + ); + assert contrastRatio == + 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; } public static void main(String args[]) { diff --git a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java index 856117246cea..0f94533bed7e 100644 --- a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java +++ b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java @@ -3,12 +3,12 @@ import java.util.Scanner; /* -* Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix -* -* Here we use gauss elimination method to find the inverse of a given matrix. -* To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination -* -* We can also find the inverse of a matrix + * Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix + * + * Here we use gauss elimination method to find the inverse of a given matrix. + * To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination + * + * We can also find the inverse of a matrix */ public class InverseOfMatrix { @@ -52,8 +52,7 @@ public static double[][] invert(double a[][]) { for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { for (int k = 0; k < n; ++k) { - b[index[j]][k] - -= a[index[j]][i] * b[index[i]][k]; + b[index[j]][k] -= a[index[j]][i] * b[index[i]][k]; } } } @@ -72,8 +71,8 @@ public static double[][] invert(double a[][]) { return x; } -// Method to carry out the partial-pivoting Gaussian -// elimination. Here index[] stores pivoting order. + // Method to carry out the partial-pivoting Gaussian + // elimination. Here index[] stores pivoting order. public static void gaussian(double a[][], int index[]) { int n = index.length; double c[] = new double[n]; diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java index 0d0024c3db18..5126a0c0d82b 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java @@ -44,7 +44,7 @@ public static void main(String[] args) { */ MedianOfRunningArray p = new MedianOfRunningArray(); - int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; + int arr[] = { 10, 7, 4, 9, 2, 3, 11, 17, 14 }; for (int i = 0; i < 9; i++) { p.insert(arr[i]); System.out.print(p.median() + " "); diff --git a/src/main/java/com/thealgorithms/misc/PalindromePrime.java b/src/main/java/com/thealgorithms/misc/PalindromePrime.java index 58de938394af..ac6d2750afbf 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromePrime.java +++ b/src/main/java/com/thealgorithms/misc/PalindromePrime.java @@ -6,7 +6,9 @@ public class PalindromePrime { public static void main(String[] args) { // Main funtion Scanner in = new Scanner(System.in); - System.out.println("Enter the quantity of First Palindromic Primes you want"); + System.out.println( + "Enter the quantity of First Palindromic Primes you want" + ); int n = in.nextInt(); // Input of how many first palindromic prime we want functioning(n); // calling function - functioning in.close(); diff --git a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java index edd270c123ea..b2fe18973895 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java @@ -1,7 +1,7 @@ package com.thealgorithms.misc; -import java.util.Stack; import com.thealgorithms.datastructures.lists.SinglyLinkedList; +import java.util.Stack; /** * A simple way of knowing if a singly linked list is palindrome is to push all diff --git a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java index eb88f814805c..c8526407a4e3 100644 --- a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java +++ b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java @@ -6,15 +6,24 @@ public class RangeInSortedArray { public static void main(String[] args) { // Testcases - assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 3), new int[]{2, 4}); - assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 4), new int[]{5, 5}); - assert Arrays.equals(sortedRange(new int[]{0, 1, 2}, 3), new int[]{-1, -1}); + assert Arrays.equals( + sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 3), + new int[] { 2, 4 } + ); + assert Arrays.equals( + sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 4), + new int[] { 5, 5 } + ); + assert Arrays.equals( + sortedRange(new int[] { 0, 1, 2 }, 3), + new int[] { -1, -1 } + ); } // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums' // Gives [-1, -1] in case element doesn't exist in array public static int[] sortedRange(int[] nums, int key) { - int[] range = new int[]{-1, -1}; + int[] range = new int[] { -1, -1 }; alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true); alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false); return range; @@ -23,7 +32,13 @@ public static int[] sortedRange(int[] nums, int key) { // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of // 'key' public static void alteredBinSearch( - int[] nums, int key, int left, int right, int[] range, boolean goLeft) { + int[] nums, + int key, + int left, + int right, + int[] range, + boolean goLeft + ) { if (left > right) { return; } @@ -52,7 +67,13 @@ public static void alteredBinSearch( // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of // 'key' public static void alteredBinSearchIter( - int[] nums, int key, int left, int right, int[] range, boolean goLeft) { + int[] nums, + int key, + int left, + int right, + int[] range, + boolean goLeft + ) { while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > key) { diff --git a/src/main/java/com/thealgorithms/misc/Sort012D.java b/src/main/java/com/thealgorithms/misc/Sort012D.java index 206b52d58a2b..93bcb9f68501 100644 --- a/src/main/java/com/thealgorithms/misc/Sort012D.java +++ b/src/main/java/com/thealgorithms/misc/Sort012D.java @@ -30,24 +30,26 @@ public static void sort012(int[] a) { int temp; while (mid <= h) { switch (a[mid]) { - case 0: { - temp = a[l]; - a[l] = a[mid]; - a[mid] = temp; - l++; - mid++; - break; - } + case 0: + { + temp = a[l]; + a[l] = a[mid]; + a[mid] = temp; + l++; + mid++; + break; + } case 1: mid++; break; - case 2: { - temp = a[mid]; - a[mid] = a[h]; - a[h] = temp; - h--; - break; - } + case 2: + { + temp = a[mid]; + a[mid] = a[h]; + a[h] = temp; + h--; + break; + } } } System.out.println("the Sorted array is "); diff --git a/src/main/java/com/thealgorithms/misc/Sparcity.java b/src/main/java/com/thealgorithms/misc/Sparcity.java index 700b8c936ef0..9326416090ec 100644 --- a/src/main/java/com/thealgorithms/misc/Sparcity.java +++ b/src/main/java/com/thealgorithms/misc/Sparcity.java @@ -3,23 +3,23 @@ import java.util.*; /* -*A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). -*The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. -* -* @author Ojasva Jain + *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). + *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. + * + * @author Ojasva Jain */ class Sparcity { /* - * @return Sparcity of matrix - * - * where sparcity = number of zeroes/total elements in matrix - * + * @return Sparcity of matrix + * + * where sparcity = number of zeroes/total elements in matrix + * */ static double sparcity(double[][] mat) { int zero = 0; - //Traversing the matrix to count number of zeroes + //Traversing the matrix to count number of zeroes for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) { if (mat[i][j] == 0) { diff --git a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java index 67facd73e399..bbf3be8714ea 100644 --- a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java @@ -16,10 +16,13 @@ public static void main(String args[]) { arr[i] = scan.nextInt(); } ThreeSumProblem th = new ThreeSumProblem(); - System.out.println("Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n"); - System.out.println("Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n"); + System.out.println( + "Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n" + ); + System.out.println( + "Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n" + ); System.out.println("Hashmap Approach\n" + (th.Hashmap(arr, ts))); - } public List> BruteForce(int[] nums, int target) { @@ -36,11 +39,11 @@ public List> BruteForce(int[] nums, int target) { Collections.sort(temp); arr.add(temp); } - } } } - arr = new ArrayList>(new LinkedHashSet>(arr)); + arr = + new ArrayList>(new LinkedHashSet>(arr)); return arr; } @@ -67,7 +70,6 @@ public List> TwoPointer(int[] nums, int target) { } else { end -= 1; } - } i++; } @@ -98,5 +100,4 @@ public List> Hashmap(int[] nums, int target) { } return new ArrayList(ts); } - } diff --git a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java index 07ec58caaa25..cf987413645e 100644 --- a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java @@ -17,14 +17,23 @@ public static void main(String args[]) { arr[i] = scan.nextInt(); } TwoSumProblem t = new TwoSumProblem(); - System.out.println("Brute Force Approach\n" + Arrays.toString(t.BruteForce(arr, ts)) + "\n"); - System.out.println("Two Pointer Approach\n" + Arrays.toString(t.TwoPointer(arr, ts)) + "\n"); - System.out.println("Hashmap Approach\n" + Arrays.toString(t.HashMap(arr, ts))); - + System.out.println( + "Brute Force Approach\n" + + Arrays.toString(t.BruteForce(arr, ts)) + + "\n" + ); + System.out.println( + "Two Pointer Approach\n" + + Arrays.toString(t.TwoPointer(arr, ts)) + + "\n" + ); + System.out.println( + "Hashmap Approach\n" + Arrays.toString(t.HashMap(arr, ts)) + ); } public int[] BruteForce(int[] nums, int target) { - //Brute Force Approach + //Brute Force Approach int ans[] = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { @@ -34,7 +43,6 @@ public int[] BruteForce(int[] nums, int target) { break; } - } } @@ -48,21 +56,24 @@ public int[] TwoPointer(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { hm.put(i, nums[i]); } - HashMap temp - = hm.entrySet() - .stream() - .sorted((i1, i2) - -> i1.getValue().compareTo( - i2.getValue())) - .collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (e1, e2) -> e1, LinkedHashMap::new)); + HashMap temp = hm + .entrySet() + .stream() + .sorted((i1, i2) -> i1.getValue().compareTo(i2.getValue())) + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (e1, e2) -> e1, + LinkedHashMap::new + ) + ); int start = 0; int end = nums.length - 1; while (start < end) { - int currSum = (Integer) temp.values().toArray()[start] + (Integer) temp.values().toArray()[end]; + int currSum = (Integer) temp.values().toArray()[start] + + (Integer) temp.values().toArray()[end]; if (currSum == target) { ans[0] = (Integer) temp.keySet().toArray()[start]; @@ -73,10 +84,8 @@ public int[] TwoPointer(int[] nums, int target) { } else if (currSum < target) { start += 1; } - } return ans; - } public int[] HashMap(int[] nums, int target) { @@ -97,5 +106,4 @@ public int[] HashMap(int[] nums, int target) { return ans; } - } diff --git a/src/main/java/com/thealgorithms/misc/WordBoggle.java b/src/main/java/com/thealgorithms/misc/WordBoggle.java index 625b0321eb52..1257c5363c81 100644 --- a/src/main/java/com/thealgorithms/misc/WordBoggle.java +++ b/src/main/java/com/thealgorithms/misc/WordBoggle.java @@ -26,21 +26,31 @@ public static List boggleBoard(char[][] board, String[] words) { public static void main(String[] args) { // Testcase - List ans - = new ArrayList<>( - Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board")); - assert (boggleBoard( - new char[][]{ - {'t', 'h', 'i', 's', 'i', 's', 'a'}, - {'s', 'i', 'm', 'p', 'l', 'e', 'x'}, - {'b', 'x', 'x', 'x', 'x', 'e', 'b'}, - {'x', 'o', 'g', 'g', 'l', 'x', 'o'}, - {'x', 'x', 'x', 'D', 'T', 'r', 'a'}, - {'R', 'E', 'P', 'E', 'A', 'd', 'x'}, - {'x', 'x', 'x', 'x', 'x', 'x', 'x'}, - {'N', 'O', 'T', 'R', 'E', '_', 'P'}, - {'x', 'x', 'D', 'E', 'T', 'A', 'E'},}, - new String[]{ + List ans = new ArrayList<>( + Arrays.asList( + "a", + "boggle", + "this", + "NOTRE_PEATED", + "is", + "simple", + "board" + ) + ); + assert ( + boggleBoard( + new char[][] { + { 't', 'h', 'i', 's', 'i', 's', 'a' }, + { 's', 'i', 'm', 'p', 'l', 'e', 'x' }, + { 'b', 'x', 'x', 'x', 'x', 'e', 'b' }, + { 'x', 'o', 'g', 'g', 'l', 'x', 'o' }, + { 'x', 'x', 'x', 'D', 'T', 'r', 'a' }, + { 'R', 'E', 'P', 'E', 'A', 'd', 'x' }, + { 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, + { 'N', 'O', 'T', 'R', 'E', '_', 'P' }, + { 'x', 'x', 'D', 'E', 'T', 'A', 'E' }, + }, + new String[] { "this", "is", "not", @@ -50,17 +60,21 @@ public static void main(String[] args) { "boggle", "board", "REPEATED", - "NOTRE_PEATED",}) - .equals(ans)); + "NOTRE_PEATED", + } + ) + .equals(ans) + ); } public static void explore( - int i, - int j, - char[][] board, - TrieNode trieNode, - boolean[][] visited, - Set finalWords) { + int i, + int j, + char[][] board, + TrieNode trieNode, + boolean[][] visited, + Set finalWords + ) { if (visited[i][j]) { return; } @@ -77,7 +91,14 @@ public static void explore( List neighbors = getNeighbors(i, j, board); for (Integer[] neighbor : neighbors) { - explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords); + explore( + neighbor[0], + neighbor[1], + board, + trieNode, + visited, + finalWords + ); } visited[i][j] = false; @@ -86,35 +107,35 @@ public static void explore( public static List getNeighbors(int i, int j, char[][] board) { List neighbors = new ArrayList<>(); if (i > 0 && j > 0) { - neighbors.add(new Integer[]{i - 1, j - 1}); + neighbors.add(new Integer[] { i - 1, j - 1 }); } if (i > 0 && j < board[0].length - 1) { - neighbors.add(new Integer[]{i - 1, j + 1}); + neighbors.add(new Integer[] { i - 1, j + 1 }); } if (i < board.length - 1 && j < board[0].length - 1) { - neighbors.add(new Integer[]{i + 1, j + 1}); + neighbors.add(new Integer[] { i + 1, j + 1 }); } if (i < board.length - 1 && j > 0) { - neighbors.add(new Integer[]{i + 1, j - 1}); + neighbors.add(new Integer[] { i + 1, j - 1 }); } if (i > 0) { - neighbors.add(new Integer[]{i - 1, j}); + neighbors.add(new Integer[] { i - 1, j }); } if (i < board.length - 1) { - neighbors.add(new Integer[]{i + 1, j}); + neighbors.add(new Integer[] { i + 1, j }); } if (j > 0) { - neighbors.add(new Integer[]{i, j - 1}); + neighbors.add(new Integer[] { i, j - 1 }); } if (j < board[0].length - 1) { - neighbors.add(new Integer[]{i, j + 1}); + neighbors.add(new Integer[] { i, j + 1 }); } return neighbors; diff --git a/src/main/java/com/thealgorithms/misc/matrixTranspose.java b/src/main/java/com/thealgorithms/misc/matrixTranspose.java index 63d024082777..b5ad02184a00 100644 --- a/src/main/java/com/thealgorithms/misc/matrixTranspose.java +++ b/src/main/java/com/thealgorithms/misc/matrixTranspose.java @@ -22,25 +22,25 @@ public class matrixTranspose { public static void main(String[] args) { /* - * This is the main method - * - * @param args Unused. - * - * @return Nothing. + * This is the main method + * + * @param args Unused. + * + * @return Nothing. */ Scanner sc = new Scanner(System.in); int i, j, row, column; System.out.println("Enter the number of rows in the 2D matrix:"); /* - * Take input from user for how many rows to be print + * Take input from user for how many rows to be print */ row = sc.nextInt(); System.out.println("Enter the number of columns in the 2D matrix:"); /* - * Take input from user for how many coloumn to be print + * Take input from user for how many coloumn to be print */ column = sc.nextInt(); int[][] arr = new int[row][column]; @@ -52,7 +52,7 @@ public static void main(String[] args) { } /* - * Print matrix before the Transpose in proper way + * Print matrix before the Transpose in proper way */ System.out.println("The matrix is:"); for (i = 0; i < row; i++) { @@ -63,9 +63,9 @@ public static void main(String[] args) { } /* - * Print matrix after the tranpose in proper way Transpose means Interchanging - * of rows wth column so we interchange the rows in next loop Thus at last - * matrix of transpose is obtained through user input... + * Print matrix after the tranpose in proper way Transpose means Interchanging + * of rows wth column so we interchange the rows in next loop Thus at last + * matrix of transpose is obtained through user input... */ System.out.println("The Transpose of the given matrix is:"); for (i = 0; i < column; i++) { diff --git a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java index e1dfa35f736f..4ee54bbdacf8 100644 --- a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java +++ b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java @@ -4,30 +4,29 @@ * A left rotation operation on an array * shifts each of the array's elements * given integer n unit to the left. - * - * @author sangin-lee + * + * @author sangin-lee */ public class ArrayLeftRotation { - /* - * Returns the result of left rotation of given array arr and integer n - * - * @param arr : int[] given array - * - * @param n : int given integer - * - * @return : int[] result of left rotation - */ - public static int[] rotateLeft(int[] arr, int n) { - int size = arr.length; - int[] dst = new int[size]; - n = n % size; - for(int i = 0; i < size; i++) { - dst[i] = arr[n]; - n = (n + 1) % size; - } - return dst; - } - + /* + * Returns the result of left rotation of given array arr and integer n + * + * @param arr : int[] given array + * + * @param n : int given integer + * + * @return : int[] result of left rotation + */ + public static int[] rotateLeft(int[] arr, int n) { + int size = arr.length; + int[] dst = new int[size]; + n = n % size; + for (int i = 0; i < size; i++) { + dst[i] = arr[n]; + n = (n + 1) % size; + } + return dst; + } } diff --git a/src/main/java/com/thealgorithms/others/BFPRT.java b/src/main/java/com/thealgorithms/others/BFPRT.java index 6ae5db8e7ff4..f296fbda139f 100644 --- a/src/main/java/com/thealgorithms/others/BFPRT.java +++ b/src/main/java/com/thealgorithms/others/BFPRT.java @@ -66,7 +66,8 @@ public static int medianOfMedians(int[] arr, int begin, int end) { int offset = num % 5 == 0 ? 0 : 1; int[] mArr = new int[num / 5 + offset]; for (int i = 0; i < mArr.length; i++) { - mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); + mArr[i] = + getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); } return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); } @@ -119,7 +120,27 @@ public static void insertionSort(int[] arr, int begin, int end) { } public static void main(String[] args) { - int[] arr = {11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9}; + int[] arr = { + 11, + 9, + 1, + 3, + 9, + 2, + 2, + 5, + 6, + 5, + 3, + 5, + 9, + 7, + 2, + 5, + 5, + 1, + 9, + }; int[] minK = getMinKNumsByBFPRT(arr, 5); System.out.println(Arrays.toString(minK)); } diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index 5ecc27dbff9b..f6d683a22eef 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -25,7 +25,13 @@ public class BankersAlgorithm { /** * This method finds the need of each process */ - static void calculateNeed(int needArray[][], int maxArray[][], int allocationArray[][], int totalProcess, int totalResources) { + static void calculateNeed( + int needArray[][], + int maxArray[][], + int allocationArray[][], + int totalProcess, + int totalResources + ) { for (int i = 0; i < totalProcess; i++) { for (int j = 0; j < totalResources; j++) { needArray[i][j] = maxArray[i][j] - allocationArray[i][j]; @@ -48,10 +54,23 @@ static void calculateNeed(int needArray[][], int maxArray[][], int allocationArr * * @return boolean if the system is in safe state or not */ - static boolean checkSafeSystem(int processes[], int availableArray[], int maxArray[][], int allocationArray[][], int totalProcess, int totalResources) { + static boolean checkSafeSystem( + int processes[], + int availableArray[], + int maxArray[][], + int allocationArray[][], + int totalProcess, + int totalResources + ) { int[][] needArray = new int[totalProcess][totalResources]; - calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); + calculateNeed( + needArray, + maxArray, + allocationArray, + totalProcess, + totalResources + ); boolean[] finishProcesses = new boolean[totalProcess]; @@ -94,12 +113,16 @@ static boolean checkSafeSystem(int processes[], int availableArray[], int maxArr // If we could not find a next process in safe sequence. if (foundSafeSystem == false) { - System.out.print("The system is not in the safe state because lack of resources"); + System.out.print( + "The system is not in the safe state because lack of resources" + ); return false; } } - System.out.print("The system is in safe sequence and the sequence is as follows: "); + System.out.print( + "The system is in safe sequence and the sequence is as follows: " + ); for (int i = 0; i < totalProcess; i++) { System.out.print("P" + safeSequenceArray[i] + " "); } @@ -140,7 +163,9 @@ public static void main(String[] args) { for (int i = 0; i < numberOfProcesses; i++) { System.out.println("For process " + i + ": "); for (int j = 0; j < numberOfResources; j++) { - System.out.println("Enter the maximum instances of resource " + j); + System.out.println( + "Enter the maximum instances of resource " + j + ); maxArray[i][j] = sc.nextInt(); } } @@ -156,12 +181,18 @@ public static void main(String[] args) { } } - checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources); + checkSafeSystem( + processes, + availableArray, + maxArray, + allocationArray, + numberOfProcesses, + numberOfResources + ); sc.close(); } } - /* Example: n = 5 diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 62566f7359fb..bb3a186b46e4 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -43,6 +43,5 @@ public static void main(String args[]) { a[i] = input.nextInt(); } System.out.println("the majority element is " + findmajor(a)); - } } diff --git a/src/main/java/com/thealgorithms/others/CountChar.java b/src/main/java/com/thealgorithms/others/CountChar.java index 40c0db86b178..11876e409835 100644 --- a/src/main/java/com/thealgorithms/others/CountChar.java +++ b/src/main/java/com/thealgorithms/others/CountChar.java @@ -9,7 +9,9 @@ public static void main(String[] args) { System.out.print("Enter your text: "); String str = input.nextLine(); input.close(); - System.out.println("There are " + CountCharacters(str) + " characters."); + System.out.println( + "There are " + CountCharacters(str) + " characters." + ); } /** diff --git a/src/main/java/com/thealgorithms/others/CountWords.java b/src/main/java/com/thealgorithms/others/CountWords.java index 66b8f148bcf1..2bbfe08ef356 100644 --- a/src/main/java/com/thealgorithms/others/CountWords.java +++ b/src/main/java/com/thealgorithms/others/CountWords.java @@ -16,7 +16,9 @@ public static void main(String[] args) { String str = input.nextLine(); System.out.println("Your text has " + wordCount(str) + " word(s)"); - System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); + System.out.println( + "Your text has " + secondaryWordCount(str) + " word(s)" + ); input.close(); } diff --git a/src/main/java/com/thealgorithms/others/Damm.java b/src/main/java/com/thealgorithms/others/Damm.java index 7e4240d7f363..83550a7f083c 100644 --- a/src/main/java/com/thealgorithms/others/Damm.java +++ b/src/main/java/com/thealgorithms/others/Damm.java @@ -24,16 +24,16 @@ public class Damm { * calculation. */ private static final byte[][] DAMM_TABLE = { - {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, - {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, - {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, - {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, - {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, - {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, - {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, - {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, - {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, - {2, 5, 8, 1, 4, 3, 6, 7, 9, 0} + { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 }, + { 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 }, + { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 }, + { 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 }, + { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 }, + { 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 }, + { 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 }, + { 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 }, + { 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 }, + { 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 }, }; /** @@ -92,27 +92,31 @@ public static void main(String[] args) { } private static void checkAndPrint(String input) { - String validationResult = Damm.dammCheck(input) - ? "valid" - : "not valid"; + String validationResult = Damm.dammCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addDammChecksum(input); - System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); + System.out.println( + "Generate and add checksum to initial value '" + + input + + "'. Result: '" + + result + + "'" + ); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { - throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); + throw new IllegalArgumentException( + "Input '" + input + "' contains not only digits" + ); } } private static int[] toIntArray(String string) { - return string.chars() - .map(i -> Character.digit(i, 10)) - .toArray(); + return string.chars().map(i -> Character.digit(i, 10)).toArray(); } } diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java index 9a8b9d130254..8f5a5f570aa8 100644 --- a/src/main/java/com/thealgorithms/others/Dijkstra.java +++ b/src/main/java/com/thealgorithms/others/Dijkstra.java @@ -31,7 +31,8 @@ public class Dijkstra { new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), - new Graph.Edge("e", "f", 9),}; + new Graph.Edge("e", "f", 9), + }; private static final String START = "a"; private static final String END = "e"; @@ -47,6 +48,7 @@ public static void main(String[] args) { } class Graph { + // mapping of vertex names to Vertex objects, built from a set of Edges private final Map graph; @@ -117,13 +119,23 @@ public boolean equals(Object object) { if (dist != vertex.dist) { return false; } - if (name != null ? !name.equals(vertex.name) : vertex.name != null) { + if ( + name != null ? !name.equals(vertex.name) : vertex.name != null + ) { return false; } - if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) { + if ( + previous != null + ? !previous.equals(vertex.previous) + : vertex.previous != null + ) { return false; } - if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) { + if ( + neighbours != null + ? !neighbours.equals(vertex.neighbours) + : vertex.neighbours != null + ) { return false; } @@ -136,7 +148,8 @@ public int hashCode() { result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + dist; result = 31 * result + (previous != null ? previous.hashCode() : 0); - result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); + result = + 31 * result + (neighbours != null ? neighbours.hashCode() : 0); return result; } @@ -175,7 +188,10 @@ public Graph(Edge[] edges) { */ public void dijkstra(String startName) { if (!graph.containsKey(startName)) { - System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); + System.err.printf( + "Graph doesn't contain start vertex \"%s\"%n", + startName + ); return; } final Vertex source = graph.get(startName); @@ -222,7 +238,10 @@ private void dijkstra(final NavigableSet q) { */ public void printPath(String endName) { if (!graph.containsKey(endName)) { - System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); + System.err.printf( + "Graph doesn't contain end vertex \"%s\"%n", + endName + ); return; } diff --git a/src/main/java/com/thealgorithms/others/EulersFunction.java b/src/main/java/com/thealgorithms/others/EulersFunction.java index eed7da05a0bb..b8ab2acfa087 100644 --- a/src/main/java/com/thealgorithms/others/EulersFunction.java +++ b/src/main/java/com/thealgorithms/others/EulersFunction.java @@ -7,6 +7,7 @@ * See https://en.wikipedia.org/wiki/Euler%27s_totient_function */ public class EulersFunction { + // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time // complexity; diff --git a/src/main/java/com/thealgorithms/others/FloydTriangle.java b/src/main/java/com/thealgorithms/others/FloydTriangle.java index d25ab303e3ed..a21ba47917a8 100644 --- a/src/main/java/com/thealgorithms/others/FloydTriangle.java +++ b/src/main/java/com/thealgorithms/others/FloydTriangle.java @@ -6,7 +6,9 @@ class FloydTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); + System.out.println( + "Enter the number of rows which you want in your Floyd Triangle: " + ); int r = sc.nextInt(), n = 0; sc.close(); for (int i = 0; i < r; i++) { diff --git a/src/main/java/com/thealgorithms/others/GuassLegendre.java b/src/main/java/com/thealgorithms/others/GuassLegendre.java index 596ca4a45e80..9d1b169a0d04 100644 --- a/src/main/java/com/thealgorithms/others/GuassLegendre.java +++ b/src/main/java/com/thealgorithms/others/GuassLegendre.java @@ -16,7 +16,7 @@ public static void main(String[] args) { static double pi(int l) { /* - * l: No of loops to run + * l: No of loops to run */ double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; diff --git a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java index 9db111574cc5..006b165a9e97 100644 --- a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java +++ b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java @@ -6,7 +6,10 @@ import java.util.Set; public class HappyNumbersSeq { - private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); + + private static final Set CYCLE_NUMS = new HashSet<>( + Arrays.asList(4, 16, 20, 37, 58, 145) + ); public static void main(String[] args) { Scanner in = new Scanner(System.in); diff --git a/src/main/java/com/thealgorithms/others/Huffman.java b/src/main/java/com/thealgorithms/others/Huffman.java index 3b8d12480fea..cf36ae22285e 100644 --- a/src/main/java/com/thealgorithms/others/Huffman.java +++ b/src/main/java/com/thealgorithms/others/Huffman.java @@ -1,11 +1,11 @@ package com.thealgorithms.others; +import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; -import java.util.Comparator; -// node class is the basic structure -// of each node present in the Huffman - tree. +// node class is the basic structure +// of each node present in the Huffman - tree. class HuffmanNode { int data; @@ -15,67 +15,64 @@ class HuffmanNode { HuffmanNode right; } -// comparator class helps to compare the node -// on the basis of one of its attribute. -// Here we will be compared -// on the basis of data values of the nodes. +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. class MyComparator implements Comparator { public int compare(HuffmanNode x, HuffmanNode y) { - return x.data - y.data; } } public class Huffman { - // recursive function to print the - // huffman-code through the tree traversal. - // Here s is the huffman - code generated. + // recursive function to print the + // huffman-code through the tree traversal. + // Here s is the huffman - code generated. public static void printCode(HuffmanNode root, String s) { - - // base case; if the left and right are null - // then its a leaf node and we print - // the code s generated by traversing the tree. - if (root.left - == null - && root.right - == null - && Character.isLetter(root.c)) { - - // c is the character in the node + // base case; if the left and right are null + // then its a leaf node and we print + // the code s generated by traversing the tree. + if ( + root.left == null && + root.right == null && + Character.isLetter(root.c) + ) { + // c is the character in the node System.out.println(root.c + ":" + s); return; } - // if we go to left then add "0" to the code. - // if we go to the right add"1" to the code. - // recursive calls for left and - // right sub-tree of the generated tree. + // if we go to left then add "0" to the code. + // if we go to the right add"1" to the code. + // recursive calls for left and + // right sub-tree of the generated tree. printCode(root.left, s + "0"); printCode(root.right, s + "1"); } - // main function + // main function public static void main(String[] args) { - Scanner s = new Scanner(System.in); - // number of characters. + // number of characters. int n = 6; - char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; - int[] charfreq = {5, 9, 12, 13, 16, 45}; + char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int[] charfreq = { 5, 9, 12, 13, 16, 45 }; - // creating a priority queue q. - // makes a min-priority queue(min-heap). - PriorityQueue q - = new PriorityQueue(n, new MyComparator()); + // creating a priority queue q. + // makes a min-priority queue(min-heap). + PriorityQueue q = new PriorityQueue( + n, + new MyComparator() + ); for (int i = 0; i < n; i++) { - - // creating a Huffman node object - // and add it to the priority queue. + // creating a Huffman node object + // and add it to the priority queue. HuffmanNode hn = new HuffmanNode(); hn.c = charArray[i]; @@ -84,50 +81,49 @@ public static void main(String[] args) { hn.left = null; hn.right = null; - // add functions adds - // the huffman node to the queue. + // add functions adds + // the huffman node to the queue. q.add(hn); } - // create a root node + // create a root node HuffmanNode root = null; - // Here we will extract the two minimum value - // from the heap each time until - // its size reduces to 1, extract until - // all the nodes are extracted. + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. while (q.size() > 1) { - - // first min extract. + // first min extract. HuffmanNode x = q.peek(); q.poll(); - // second min extarct. + // second min extarct. HuffmanNode y = q.peek(); q.poll(); - // new node f which is equal + // new node f which is equal HuffmanNode f = new HuffmanNode(); - // to the sum of the frequency of the two nodes - // assigning values to the f node. + // to the sum of the frequency of the two nodes + // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; - // first extracted node as left child. + // first extracted node as left child. f.left = x; - // second extracted node as the right child. + // second extracted node as the right child. f.right = y; - // marking the f node as the root node. + // marking the f node as the root node. root = f; - // add this node to the priority-queue. + // add this node to the priority-queue. q.add(f); } - // print the codes by traversing the tree + // print the codes by traversing the tree printCode(root, ""); } } diff --git a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java index f3fe7a25c3e0..6364c5cd3df1 100644 --- a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java +++ b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java @@ -1,23 +1,23 @@ package com.thealgorithms.others; -// Java Program to implement Auto-Complete +// Java Program to implement Auto-Complete // Feature using Trie class Trieac { - // Alphabet size (# of symbols) + // Alphabet size (# of symbols) public static final int ALPHABET_SIZE = 26; - // Trie node + // Trie node static class TrieNode { TrieNode children[] = new TrieNode[ALPHABET_SIZE]; - // isWordEnd is true if the node represents - // end of a word + // isWordEnd is true if the node represents + // end of a word boolean isWordEnd; - }; + } - // Returns new trie node (initialized to NULLs) + // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isWordEnd = false; @@ -29,8 +29,8 @@ static TrieNode getNode() { return pNode; } - // If not present, inserts key into trie. If the - // key is prefix of trie node, just marks leaf node + // If not present, inserts key into trie. If the + // key is prefix of trie node, just marks leaf node static void insert(TrieNode root, final String key) { TrieNode pCrawl = root; @@ -42,11 +42,11 @@ static void insert(TrieNode root, final String key) { pCrawl = pCrawl.children[index]; } - // mark last node as leaf + // mark last node as leaf pCrawl.isWordEnd = true; } - // Returns true if key presents in trie, else false + // Returns true if key presents in trie, else false boolean search(TrieNode root, final String key) { int length = key.length(); TrieNode pCrawl = root; @@ -62,8 +62,8 @@ boolean search(TrieNode root, final String key) { return (pCrawl != null && pCrawl.isWordEnd); } - // Returns 0 if current node has a child - // If all children are NULL, return 1. + // Returns 0 if current node has a child + // If all children are NULL, return 1. static boolean isLastNode(TrieNode root) { for (int i = 0; i < ALPHABET_SIZE; i++) { if (root.children[i] != null) { @@ -73,25 +73,25 @@ static boolean isLastNode(TrieNode root) { return true; } - // Recursive function to print auto-suggestions - // for given node. + // Recursive function to print auto-suggestions + // for given node. static void suggestionsRec(TrieNode root, String currPrefix) { - // found a string in Trie with the given prefix + // found a string in Trie with the given prefix if (root.isWordEnd) { System.out.println(currPrefix); } - // All children struct node pointers are NULL + // All children struct node pointers are NULL if (isLastNode(root)) { return; } for (int i = 0; i < ALPHABET_SIZE; i++) { if (root.children[i] != null) { - // append current character to currPrefix string + // append current character to currPrefix string currPrefix += (char) (97 + i); - // recur over the rest + // recur over the rest suggestionsRec(root.children[i], currPrefix); } } @@ -99,20 +99,19 @@ static void suggestionsRec(TrieNode root, String currPrefix) { // Fucntion to print suggestions for // given query prefix. - static int printAutoSuggestions(TrieNode root, - final String query) { + static int printAutoSuggestions(TrieNode root, final String query) { TrieNode pCrawl = root; - // Check if prefix is present and find the - // the node (of last level) with last character - // of given string. + // Check if prefix is present and find the + // the node (of last level) with last character + // of given string. int level; int n = query.length(); for (level = 0; level < n; level++) { int index = (query.charAt(level) - 'a'); - // no string in the Trie has this prefix + // no string in the Trie has this prefix if (pCrawl.children[index] == null) { return 0; } @@ -120,23 +119,23 @@ static int printAutoSuggestions(TrieNode root, pCrawl = pCrawl.children[index]; } - // If prefix is present as a word. + // If prefix is present as a word. boolean isWord = (pCrawl.isWordEnd == true); - // If prefix is last node of tree (has no - // children) + // If prefix is last node of tree (has no + // children) boolean isLast = isLastNode(pCrawl); - // If prefix is present as a word, but - // there is no subtree below the last - // matching node. + // If prefix is present as a word, but + // there is no subtree below the last + // matching node. if (isWord && isLast) { System.out.println(query); return -1; } - // If there are nodes below the last - // matching character. + // If there are nodes below the last + // matching character. if (!isLast) { String prefix = query; suggestionsRec(pCrawl, prefix); @@ -161,11 +160,11 @@ public static void main(String[] args) { int comp = printAutoSuggestions(root, "hel"); if (comp == -1) { - System.out.println("No other strings found " - + "with this prefix\n"); + System.out.println( + "No other strings found " + "with this prefix\n" + ); } else if (comp == 0) { - System.out.println("No string found with" - + " this prefix\n"); + System.out.println("No string found with" + " this prefix\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java index 23c8671e729a..e38fab67468d 100644 --- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java +++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java @@ -18,7 +18,9 @@ public static void main(String[] args) { } // To insert a new element(we are creating a new array) - System.out.println("Enter the index at which the element should be inserted"); + System.out.println( + "Enter the index at which the element should be inserted" + ); int insert_pos = s.nextInt(); System.out.println("Enter the element to be inserted"); int ins = s.nextInt(); diff --git a/src/main/java/com/thealgorithms/others/KMP.java b/src/main/java/com/thealgorithms/others/KMP.java index b7a50dc74dd7..7fb5645a2726 100644 --- a/src/main/java/com/thealgorithms/others/KMP.java +++ b/src/main/java/com/thealgorithms/others/KMP.java @@ -5,6 +5,7 @@ * for an example */ public class KMP { + // a working example public static void main(String[] args) { diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index 5d160e4873a7..f82a812509e2 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -56,7 +56,8 @@ public static void main(String[] args) { assert image.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // The snowflake is drawn in black and this is the position of the first vector - assert image.getRGB((int) offsetX, (int) offsetY) == new Color(0, 0, 0).getRGB(); + assert image.getRGB((int) offsetX, (int) offsetY) == + new Color(0, 0, 0).getRGB(); // Save image try { @@ -76,7 +77,10 @@ public static void main(String[] args) { * @param steps The number of iterations. * @return The transformed vectors after the iteration-steps. */ - public static ArrayList Iterate(ArrayList initialVectors, int steps) { + public static ArrayList Iterate( + ArrayList initialVectors, + int steps + ) { ArrayList vectors = initialVectors; for (int i = 0; i < steps; i++) { vectors = IterationStep(vectors); @@ -94,14 +98,18 @@ public static ArrayList Iterate(ArrayList initialVectors, int */ public static BufferedImage GetKochSnowflake(int imageWidth, int steps) { if (imageWidth <= 0) { - throw new IllegalArgumentException("imageWidth should be greater than zero"); + throw new IllegalArgumentException( + "imageWidth should be greater than zero" + ); } double offsetX = imageWidth / 10.; double offsetY = imageWidth / 3.7; Vector2 vector1 = new Vector2(offsetX, offsetY); - Vector2 vector2 - = new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY); + Vector2 vector2 = new Vector2( + imageWidth / 2, + Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY + ); Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY); ArrayList initialVectors = new ArrayList(); initialVectors.add(vector1); @@ -122,15 +130,23 @@ public static BufferedImage GetKochSnowflake(int imageWidth, int steps) { * applied. * @return The transformed vectors after the iteration-step. */ - private static ArrayList IterationStep(ArrayList vectors) { + private static ArrayList IterationStep( + ArrayList vectors + ) { ArrayList newVectors = new ArrayList(); for (int i = 0; i < vectors.size() - 1; i++) { Vector2 startVector = vectors.get(i); Vector2 endVector = vectors.get(i + 1); newVectors.add(startVector); - Vector2 differenceVector = endVector.subtract(startVector).multiply(1. / 3); + Vector2 differenceVector = endVector + .subtract(startVector) + .multiply(1. / 3); newVectors.add(startVector.add(differenceVector)); - newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60))); + newVectors.add( + startVector + .add(differenceVector) + .add(differenceVector.rotate(60)) + ); newVectors.add(startVector.add(differenceVector.multiply(2))); } @@ -147,8 +163,15 @@ private static ArrayList IterationStep(ArrayList vectors) { * @return The image of the rendered edges. */ private static BufferedImage GetImage( - ArrayList vectors, int imageWidth, int imageHeight) { - BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); + ArrayList vectors, + int imageWidth, + int imageHeight + ) { + BufferedImage image = new BufferedImage( + imageWidth, + imageHeight, + BufferedImage.TYPE_INT_RGB + ); Graphics2D g2d = image.createGraphics(); // Set the background white diff --git a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java index 7e097f1b09db..c96da433c007 100644 --- a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java +++ b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java @@ -21,7 +21,11 @@ public class LinearCongruentialGenerator { * @param modulo The maximum number that can be generated (exclusive). A * common value is 2^32. */ - public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { + public LinearCongruentialGenerator( + double multiplier, + double increment, + double modulo + ) { this(System.currentTimeMillis(), multiplier, increment, modulo); } @@ -36,7 +40,11 @@ public LinearCongruentialGenerator(double multiplier, double increment, double m * common value is 2^32. */ public LinearCongruentialGenerator( - double seed, double multiplier, double increment, double modulo) { + double seed, + double multiplier, + double increment, + double modulo + ) { this.previousValue = seed; this.a = multiplier; this.c = increment; @@ -58,8 +66,11 @@ public static void main(String[] args) { // Show the LCG in action. // Decisive proof that the LCG works could be made by adding each number // generated to a Set while checking for duplicates. - LinearCongruentialGenerator lcg - = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0)); + LinearCongruentialGenerator lcg = new LinearCongruentialGenerator( + 1664525, + 1013904223, + Math.pow(2.0, 32.0) + ); for (int i = 0; i < 512; i++) { System.out.println(lcg.nextNumber()); } diff --git a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java index 4b11134452fa..95fffd41ca90 100644 --- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java +++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java @@ -29,8 +29,12 @@ public static void main(String[] args) { in.next(); } } - System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n)); - System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n))); + System.out.println( + n + " is a palindrome in base " + lowestBasePalindrome(n) + ); + System.out.println( + base2base(Integer.toString(n), 10, lowestBasePalindrome(n)) + ); in.close(); } diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 351dc13f7341..319955e7fdeb 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -67,8 +67,8 @@ public static boolean luhnCheck(int[] digits) { public static void main(String[] args) { System.out.println("Luhn algorithm usage examples:"); - int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7}; - int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; //typo in last symbol + int[] validInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7 }; + int[] invalidInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4 }; //typo in last symbol checkAndPrint(validInput); checkAndPrint(invalidInput); @@ -82,13 +82,12 @@ public static void main(String[] args) { } private static void checkAndPrint(int[] input) { - String validationResult = Luhn.luhnCheck(input) - ? "valid" - : "not valid"; - System.out.println("Input " + Arrays.toString(input) + " is " + validationResult); + String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid"; + System.out.println( + "Input " + Arrays.toString(input) + " is " + validationResult + ); } - /* ======================== Business usage example @@ -98,7 +97,6 @@ private static void checkAndPrint(int[] input) { * Object representation of credit card. */ private record CreditCard(int[] digits) { - private static final int DIGITS_COUNT = 16; /** @@ -111,14 +109,21 @@ private record CreditCard(int[] digits) { public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); String trimmedCardNumber = cardNumber.replaceAll(" ", ""); - if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { - throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); + if ( + trimmedCardNumber.length() != DIGITS_COUNT || + !trimmedCardNumber.matches("\\d+") + ) { + throw new IllegalArgumentException( + "{" + cardNumber + "} - is not a card number" + ); } int[] cardNumbers = toIntArray(trimmedCardNumber); boolean isValid = luhnCheck(cardNumbers); if (!isValid) { - throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo"); + throw new IllegalArgumentException( + "Credit card number {" + cardNumber + "} - have a typo" + ); } return new CreditCard(cardNumbers); @@ -141,23 +146,34 @@ public String number() { @Override public String toString() { - return String.format("%s {%s}", CreditCard.class.getSimpleName(), number()); + return String.format( + "%s {%s}", + CreditCard.class.getSimpleName(), + number() + ); } private static int[] toIntArray(String string) { - return string.chars() - .map(i -> Character.digit(i, 10)) - .toArray(); + return string.chars().map(i -> Character.digit(i, 10)).toArray(); } } private static void businessExample(String cardNumber) { try { - System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber); + System.out.println( + "Trying to create CreditCard object from valid card number: " + + cardNumber + ); CreditCard creditCard = CreditCard.fromString(cardNumber); - System.out.println("And business object is successfully created: " + creditCard + "\n"); + System.out.println( + "And business object is successfully created: " + + creditCard + + "\n" + ); } catch (IllegalArgumentException e) { - System.out.println("And fail with exception message: " + e.getMessage() + "\n"); + System.out.println( + "And fail with exception message: " + e.getMessage() + "\n" + ); } } } diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 7e2837f1d765..6ffcc8556d8a 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -27,13 +27,23 @@ public class Mandelbrot { public static void main(String[] args) { // Test black and white - BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false); + BufferedImage blackAndWhiteImage = getImage( + 800, + 600, + -0.6, + 0, + 3.2, + 50, + false + ); // Pixel outside the Mandelbrot set should be white. - assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); + assert blackAndWhiteImage.getRGB(0, 0) == + new Color(255, 255, 255).getRGB(); // Pixel inside the Mandelbrot set should be black. - assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); + assert blackAndWhiteImage.getRGB(400, 300) == + new Color(0, 0, 0).getRGB(); // Test color-coding BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true); @@ -71,44 +81,62 @@ public static void main(String[] args) { * @return The image of the rendered Mandelbrot set. */ public static BufferedImage getImage( - int imageWidth, - int imageHeight, - double figureCenterX, - double figureCenterY, - double figureWidth, - int maxStep, - boolean useDistanceColorCoding) { + int imageWidth, + int imageHeight, + double figureCenterX, + double figureCenterY, + double figureWidth, + int maxStep, + boolean useDistanceColorCoding + ) { if (imageWidth <= 0) { - throw new IllegalArgumentException("imageWidth should be greater than zero"); + throw new IllegalArgumentException( + "imageWidth should be greater than zero" + ); } if (imageHeight <= 0) { - throw new IllegalArgumentException("imageHeight should be greater than zero"); + throw new IllegalArgumentException( + "imageHeight should be greater than zero" + ); } if (maxStep <= 0) { - throw new IllegalArgumentException("maxStep should be greater than zero"); + throw new IllegalArgumentException( + "maxStep should be greater than zero" + ); } - BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); + BufferedImage image = new BufferedImage( + imageWidth, + imageHeight, + BufferedImage.TYPE_INT_RGB + ); double figureHeight = figureWidth / imageWidth * imageHeight; // loop through the image-coordinates for (int imageX = 0; imageX < imageWidth; imageX++) { for (int imageY = 0; imageY < imageHeight; imageY++) { // determine the figure-coordinates based on the image-coordinates - double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; - double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight; + double figureX = + figureCenterX + + ((double) imageX / imageWidth - 0.5) * + figureWidth; + double figureY = + figureCenterY + + ((double) imageY / imageHeight - 0.5) * + figureHeight; double distance = getDistance(figureX, figureY, maxStep); // color the corresponding pixel based on the selected coloring-function image.setRGB( - imageX, - imageY, - useDistanceColorCoding - ? colorCodedColorMap(distance).getRGB() - : blackAndWhiteColorMap(distance).getRGB()); + imageX, + imageY, + useDistanceColorCoding + ? colorCodedColorMap(distance).getRGB() + : blackAndWhiteColorMap(distance).getRGB() + ); } } @@ -177,7 +205,11 @@ private static Color colorCodedColorMap(double distance) { * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ - private static double getDistance(double figureX, double figureY, int maxStep) { + private static double getDistance( + double figureX, + double figureY, + int maxStep + ) { double a = figureX; double b = figureY; int currentStep = 0; diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index a5b5d44ea4d1..3ab711d27dc6 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -1,4 +1,5 @@ package com.thealgorithms.others; + /** * @author Alexandros Lemonaris */ @@ -20,16 +21,19 @@ public abstract class MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public abstract ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses); - + public abstract ArrayList fitProcess( + int[] sizeOfBlocks, + int[] sizeOfProcesses + ); } + /** * @author Dekas Dimitrios */ class BestFitCPU extends MemoryManagementAlgorithms { - private static final int NO_ALLOCATION - = -255; // if a process has been allocated in position -255, + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. /** @@ -62,13 +66,13 @@ private static int findBestFit(int[] blockSizes, int processSize) { // Initialize minDiff with an unreachable value by a difference between a blockSize and the // processSize. int minDiff = findMaxElement(blockSizes); - int index - = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the + int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the // result. - for (int i = 0; - i < blockSizes.length; - i++) { // Find the most fitting memory block for the given process. - if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { + for (int i = 0; i < blockSizes.length; i++) { // Find the most fitting memory block for the given process. + if ( + blockSizes[i] - processSize < minDiff && + blockSizes[i] - processSize >= 0 + ) { minDiff = blockSizes[i] - processSize; index = i; } @@ -88,23 +92,22 @@ private static int findBestFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + public ArrayList fitProcess( + int[] sizeOfBlocks, + int[] sizeOfProcesses + ) { // The array list responsible for saving the memory allocations done by the best-fit algorithm ArrayList memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx - = findBestFit( - sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx - != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } - } /** @@ -112,8 +115,8 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) */ class WorstFitCPU extends MemoryManagementAlgorithms { - private static final int NO_ALLOCATION - = -255; // if a process has been allocated in position -255, + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. /** @@ -128,9 +131,7 @@ class WorstFitCPU extends MemoryManagementAlgorithms { private static int findWorstFit(int[] blockSizes, int processSize) { int max = -1; int index = -1; - for (int i = 0; - i < blockSizes.length; - i++) { // Find the index of the biggest memory block available. + for (int i = 0; i < blockSizes.length; i++) { // Find the index of the biggest memory block available. if (blockSizes[i] > max) { max = blockSizes[i]; index = i; @@ -155,23 +156,22 @@ private static int findWorstFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + public ArrayList fitProcess( + int[] sizeOfBlocks, + int[] sizeOfProcesses + ) { // The array list responsible for saving the memory allocations done by the worst-fit algorithm ArrayList memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx - = findWorstFit( - sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx - != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } - } /** @@ -179,8 +179,8 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) */ class FirstFitCPU extends MemoryManagementAlgorithms { - private static final int NO_ALLOCATION - = -255; // if a process has been allocated in position -255, + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. /** @@ -214,23 +214,22 @@ private static int findFirstFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + public ArrayList fitProcess( + int[] sizeOfBlocks, + int[] sizeOfProcesses + ) { // The array list responsible for saving the memory allocations done by the first-fit algorithm ArrayList memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx - = findFirstFit( - sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx - != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } - } /** @@ -238,10 +237,10 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) */ class NextFit extends MemoryManagementAlgorithms { - private static final int NO_ALLOCATION - = -255; // if a process has been allocated in position -255, + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, // it means that it has not been actually allocated. private int counter = 0; // variable that keeps the position of the last registration into the memory + /** * Method to find the index of the memory block that is going to fit the * given process based on the next fit algorithm. In the case of next fit, @@ -253,9 +252,8 @@ class NextFit extends MemoryManagementAlgorithms { * exists. */ private int findNextFit(int[] blockSizes, int processSize) { - for (int i = 0; i < blockSizes.length; i++) { - if (counter + i >= blockSizes.length){ + if (counter + i >= blockSizes.length) { counter = -i; // starts from the start of the array } if (blockSizes[i + counter] >= processSize) { @@ -280,22 +278,20 @@ private int findNextFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + public ArrayList fitProcess( + int[] sizeOfBlocks, + int[] sizeOfProcesses + ) { // The array list responsible for saving the memory allocations done by the first-fit algorithm ArrayList memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx - = findNextFit( - sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx - != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } - } - diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index f40862baab1e..87ecd8594842 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -43,7 +43,11 @@ public static void main(String[] args) { System.out.println(Arrays.toString(miniMaxAlgorith.getScores())); System.out.println( - "The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + String.valueOf(bestScore)); + "The best score for " + + (isMaximizer ? "Maximizer" : "Minimizer") + + " is " + + String.valueOf(bestScore) + ); } /** @@ -55,7 +59,12 @@ public static void main(String[] args) { * @param verbose True to show each players choices. * @return The optimal score for the player that made the first move. */ - public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { + public int miniMax( + int depth, + boolean isMaximizer, + int index, + boolean verbose + ) { int bestScore, score1, score2; if (depth == height) { // Leaf node reached. @@ -79,8 +88,15 @@ public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { // (1 x 2) = 2; ((1 x 2) + 1) = 3 // (2 x 2) = 4; ((2 x 2) + 1) = 5 ... if (verbose) { - System.out.println(String.format("From %02d and %02d, %s chooses %02d", score1, score2, - (isMaximizer ? "Maximizer" : "Minimizer"), bestScore)); + System.out.println( + String.format( + "From %02d and %02d, %s chooses %02d", + score1, + score2, + (isMaximizer ? "Maximizer" : "Minimizer"), + bestScore + ) + ); } return bestScore; diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java index d9a2e648e893..b25ca3e3f61a 100644 --- a/src/main/java/com/thealgorithms/others/PageRank.java +++ b/src/main/java/com/thealgorithms/others/PageRank.java @@ -10,7 +10,9 @@ public static void main(String args[]) { System.out.print("Enter the Number of WebPages: "); nodes = in.nextInt(); PageRank p = new PageRank(); - System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); + System.out.println( + "Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: " + ); for (i = 1; i <= nodes; i++) { for (j = 1; j <= nodes; j++) { p.path[i][j] = in.nextInt(); @@ -26,7 +28,6 @@ public static void main(String args[]) { public double pagerank[] = new double[10]; public void calc(double totalNodes) { - double InitialPageRank; double OutgoingLinks = 0; double DampingFactor = 0.85; @@ -37,7 +38,12 @@ public void calc(double totalNodes) { int ITERATION_STEP = 1; InitialPageRank = 1 / totalNodes; System.out.printf( - " Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); + " Total Number of Nodes :" + + totalNodes + + "\t Initial PageRank of All Nodes :" + + InitialPageRank + + "\n" + ); // 0th ITERATION _ OR _ INITIALIZATION PHASE // for (k = 1; k <= totalNodes; k++) { @@ -46,20 +52,31 @@ public void calc(double totalNodes) { System.out.printf("\n Initial PageRank Values , 0th Step \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); + System.out.printf( + " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" + ); } - while (ITERATION_STEP <= 2) // Iterations - { + while (ITERATION_STEP <= 2) { // Iterations // Store the PageRank for All Nodes in Temporary Array for (k = 1; k <= totalNodes; k++) { TempPageRank[k] = this.pagerank[k]; this.pagerank[k] = 0; } - for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { - for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) { - if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) { + for ( + InternalNodeNumber = 1; + InternalNodeNumber <= totalNodes; + InternalNodeNumber++ + ) { + for ( + ExternalNodeNumber = 1; + ExternalNodeNumber <= totalNodes; + ExternalNodeNumber++ + ) { + if ( + this.path[ExternalNodeNumber][InternalNodeNumber] == 1 + ) { k = 1; OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber while (k <= totalNodes) { @@ -69,13 +86,21 @@ public void calc(double totalNodes) { k = k + 1; } // Calculate PageRank - this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); + this.pagerank[InternalNodeNumber] += + TempPageRank[ExternalNodeNumber] * + (1 / OutgoingLinks); } } System.out.printf("\n After " + ITERATION_STEP + "th Step \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); + System.out.printf( + " Page Rank of " + + k + + " is :\t" + + this.pagerank[k] + + "\n" + ); } ITERATION_STEP = ITERATION_STEP + 1; @@ -83,15 +108,17 @@ public void calc(double totalNodes) { // Add the Damping Factor to PageRank for (k = 1; k <= totalNodes; k++) { - this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k]; + this.pagerank[k] = + (1 - DampingFactor) + DampingFactor * this.pagerank[k]; } // Display PageRank System.out.printf("\n Final Page Rank : \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); + System.out.printf( + " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" + ); } - } } } diff --git a/src/main/java/com/thealgorithms/others/PasswordGen.java b/src/main/java/com/thealgorithms/others/PasswordGen.java index a88d94653bbd..e1de7242385b 100644 --- a/src/main/java/com/thealgorithms/others/PasswordGen.java +++ b/src/main/java/com/thealgorithms/others/PasswordGen.java @@ -38,7 +38,11 @@ static String generatePassword(int min_length, int max_length) { StringBuilder password = new StringBuilder(); // Note that size of the password is also random - for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { + for ( + int i = random.nextInt(max_length - min_length) + min_length; + i > 0; + --i + ) { password.append(letters.get(random.nextInt(letters.size()))); } diff --git a/src/main/java/com/thealgorithms/others/PerlinNoise.java b/src/main/java/com/thealgorithms/others/PerlinNoise.java index 88671f4aabcf..c3591cf0aaf8 100644 --- a/src/main/java/com/thealgorithms/others/PerlinNoise.java +++ b/src/main/java/com/thealgorithms/others/PerlinNoise.java @@ -18,7 +18,12 @@ public class PerlinNoise { * @return float array containing calculated "Perlin-Noise" values */ static float[][] generatePerlinNoise( - int width, int height, int octaveCount, float persistence, long seed) { + int width, + int height, + int octaveCount, + float persistence, + long seed + ) { final float[][] base = new float[width][height]; final float[][] perlinNoise = new float[width][height]; final float[][][] noiseLayers = new float[octaveCount][][]; @@ -33,7 +38,8 @@ static float[][] generatePerlinNoise( // calculate octaves with different roughness for (int octave = 0; octave < octaveCount; octave++) { - noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); + noiseLayers[octave] = + generatePerlinNoiseLayer(base, width, height, octave); } float amplitude = 1f; @@ -70,7 +76,12 @@ static float[][] generatePerlinNoise( * @param octave current layer * @return float array containing calculated "Perlin-Noise-Layer" values */ - static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { + static float[][] generatePerlinNoiseLayer( + float[][] base, + int width, + int height, + int octave + ) { float[][] perlinNoiseLayer = new float[width][height]; // calculate period (wavelength) for different shapes @@ -90,13 +101,22 @@ static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, float verticalBlend = (y - y0) * frequency; // blend top corners - float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend); + float top = interpolate( + base[x0][y0], + base[x1][y0], + horizintalBlend + ); // blend bottom corners - float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend); + float bottom = interpolate( + base[x0][y1], + base[x1][y1], + horizintalBlend + ); // blend top and bottom interpolation to get the final blend value for this cell - perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); + perlinNoiseLayer[x][y] = + interpolate(top, bottom, verticalBlend); } } @@ -143,7 +163,8 @@ public static void main(String[] args) { System.out.println("Charset (String): "); charset = in.next(); - perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); + perlinNoise = + generatePerlinNoise(width, height, octaveCount, persistence, seed); final char[] chars = charset.toCharArray(); final int length = chars.length; final float step = 1f / length; diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java index d699c4a6b94c..f73ce0f31238 100644 --- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java +++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java @@ -141,7 +141,9 @@ public static void main(String args[]) { System.out.println(myQueue.isEmpty()); // Will print false System.out.println(myQueue.remove()); // Will print 1 - System.out.println((myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL + System.out.println( + (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack() + ); // Will print NULL // instack: [] // outStack: [(top) 2, 3, 4] diff --git a/src/main/java/com/thealgorithms/others/RabinKarp.java b/src/main/java/com/thealgorithms/others/RabinKarp.java index 5fee40318709..3c123ace3e89 100644 --- a/src/main/java/com/thealgorithms/others/RabinKarp.java +++ b/src/main/java/com/thealgorithms/others/RabinKarp.java @@ -13,7 +13,6 @@ public class RabinKarp { public static final int d = 256; public static void main(String[] args) { - scanner = new Scanner(System.in); System.out.println("Enter String"); String text = scanner.nextLine(); @@ -25,7 +24,6 @@ public static void main(String[] args) { } private static void searchPat(String text, String pattern, int q) { - int m = pattern.length(); int n = text.length(); int t = 0; @@ -45,7 +43,6 @@ private static void searchPat(String text, String pattern, int q) { } for (i = 0; i <= n - m; i++) { - // if the calculated hash value of the pattern and text matches then // all the characters of the pattern is matched with the text of length equal to length of the // pattern @@ -54,10 +51,8 @@ private static void searchPat(String text, String pattern, int q) { // of the next character after the end // of the evaluated characters is added if (p == t) { - // if hash value matches then the individual characters are matched for (j = 0; j < m; j++) { - // if not matched then break out of the loop if (text.charAt(i + j) != pattern.charAt(j)) { break; diff --git a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java index fbf171cf06b9..b1e13816dea8 100644 --- a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java +++ b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java @@ -9,11 +9,15 @@ public class RemoveDuplicateFromString { public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in) + ); String inpStr = br.readLine(); System.out.println("Actual string is: " + inpStr); - System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); + System.out.println( + "String after removing duplicates: " + removeDuplicate(inpStr) + ); br.close(); } diff --git a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java index d1e3c2cfee54..19f875938a92 100644 --- a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java +++ b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java @@ -22,30 +22,23 @@ public static void main(String[] args) { * @return subsequence */ private static String[] returnSubsequence(String givenString) { - if (givenString.length() - == 0) // If string is empty we will create an array of size=1 and insert "" (Empty string) - // in it - { + if ( + givenString.length() == 0 + ) { // in it // If string is empty we will create an array of size=1 and insert "" (Empty string) String[] ans = new String[1]; ans[0] = ""; return ans; } - String[] SmallAns - = returnSubsequence( - givenString.substring( - 1)); // recursive call to get subsequences of substring starting from index + String[] SmallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index // position=1 - String[] ans - = new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns + String[] ans = new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns int i = 0; for (; i < SmallAns.length; i++) { ans[i] = SmallAns[i]; // Copying all the strings present in SmallAns to ans string array } for (int k = 0; k < SmallAns.length; k++) { - ans[k + SmallAns.length] - = givenString.charAt(0) - + SmallAns[k]; // Insert character at index=0 of the given substring in front of every string + ans[k + SmallAns.length] = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given substring in front of every string // in SmallAns } return ans; diff --git a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java index c16122088768..7c0fe0b2c6f6 100644 --- a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java +++ b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java @@ -33,8 +33,7 @@ public static void main(String[] args) { // Function Used to reverse Stack Using Recursion private static void reverseUsingRecursion(Stack stack) { - if (stack.isEmpty()) // If stack is empty then return - { + if (stack.isEmpty()) { // If stack is empty then return return; } /* All items are stored in call stack until we reach the end*/ diff --git a/src/main/java/com/thealgorithms/others/SJF.java b/src/main/java/com/thealgorithms/others/SJF.java index 0ced44166814..171474123029 100644 --- a/src/main/java/com/thealgorithms/others/SJF.java +++ b/src/main/java/com/thealgorithms/others/SJF.java @@ -53,7 +53,9 @@ class Schedule { System.out.print("Enter the no. of processes: "); noOfProcess = in.nextInt(); - System.out.println("Enter the arrival, burst and priority of processes"); + System.out.println( + "Enter the arrival, burst and priority of processes" + ); for (int i = 0; i < noOfProcess; i++) { Process p = new Process(); p.pid = i; @@ -75,14 +77,14 @@ class Schedule { } void startScheduling() { - processes.sort( - new Comparator() { - @Override - public int compare(Process a, Process b) { - return a.arrivalTime - b.arrivalTime; + new Comparator() { + @Override + public int compare(Process a, Process b) { + return a.arrivalTime - b.arrivalTime; + } } - }); + ); while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) { removeFinishedProcess(); @@ -92,19 +94,23 @@ public int compare(Process a, Process b) { } remainingProcess.sort( - new Comparator() { - private int alpha = 6; - private int beta = 1; - - @Override - public int compare(Process a, Process b) { - int aRem = a.remainingTime; - int bRem = b.remainingTime; - int aprior = a.priority; - int bprior = b.priority; - return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior); + new Comparator() { + private int alpha = 6; + private int beta = 1; + + @Override + public int compare(Process a, Process b) { + int aRem = a.remainingTime; + int bRem = b.remainingTime; + int aprior = a.priority; + int bprior = b.priority; + return ( + (alpha * aRem + beta * aprior) - + (alpha * bRem + beta * bprior) + ); + } } - }); + ); int k = timeElapsed(timer); ageing(k); @@ -124,7 +130,8 @@ void removeFinishedProcess() { for (int i = 0; i < completed.size(); i++) { int pid = remainingProcess.get(completed.get(i)).pid; - processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime; + processes.get(pid).waitTime = + remainingProcess.get(completed.get(i)).waitTime; remainingProcess.remove(remainingProcess.get(completed.get(i))); } } @@ -158,21 +165,25 @@ public void solve() { float tatTime = 0; for (int i = 0; i < noOfProcess; i++) { - processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime; + processes.get(i).turnAroundTime = + processes.get(i).waitTime + processes.get(i).burstTime; waitTimeTot += processes.get(i).waitTime; tatTime += processes.get(i).turnAroundTime; System.out.println( - "Process no.: " - + i - + " Wait time: " - + processes.get(i).waitTime - + " Turn Around Time: " - + processes.get(i).turnAroundTime); + "Process no.: " + + i + + " Wait time: " + + processes.get(i).waitTime + + " Turn Around Time: " + + processes.get(i).turnAroundTime + ); } - System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess); + System.out.println( + "Average Waiting Time: " + waitTimeTot / noOfProcess + ); System.out.println("Average TAT Time: " + tatTime / noOfProcess); System.out.println("Throughput: " + (float) noOfProcess / (timer - 1)); } diff --git a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java index 7ba6d76b4612..a62cbbda4df1 100644 --- a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java @@ -52,9 +52,10 @@ public static int[] findPrimesTill(int n) { } //Write all primes to result array - int primesCount = (int) Arrays.stream(numbers) - .filter(element -> element == Type.PRIME) - .count(); + int primesCount = (int) Arrays + .stream(numbers) + .filter(element -> element == Type.PRIME) + .count(); int[] primes = new int[primesCount]; int primeIndex = 0; @@ -68,7 +69,8 @@ public static int[] findPrimesTill(int n) { } private enum Type { - PRIME, NOT_PRIME + PRIME, + NOT_PRIME, } public static void main(String[] args) { diff --git a/src/main/java/com/thealgorithms/others/SkylineProblem.java b/src/main/java/com/thealgorithms/others/SkylineProblem.java index 149adf4349cf..015e6a2650c4 100644 --- a/src/main/java/com/thealgorithms/others/SkylineProblem.java +++ b/src/main/java/com/thealgorithms/others/SkylineProblem.java @@ -18,7 +18,11 @@ public void run() { for (int i = 0; i < num; i++) { String input = sc.next(); String[] data = input.split(","); - this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); + this.add( + Integer.parseInt(data[0]), + Integer.parseInt(data[1]), + Integer.parseInt(data[2]) + ); } this.print(this.findSkyline(0, num - 1)); @@ -58,7 +62,10 @@ public ArrayList findSkyline(int start, int end) { return this.mergeSkyline(sky1, sky2); } - public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { + public ArrayList mergeSkyline( + ArrayList sky1, + ArrayList sky2 + ) { int currentH1 = 0, currentH2 = 0; ArrayList skyline = new ArrayList<>(); int maxH = 0; diff --git a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java index 0a949fe874ac..b951d9d910dd 100644 --- a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java +++ b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java @@ -33,7 +33,6 @@ public static int postfixEvaluate(String exp) { } else { s.push(num1 / num2); } - // "+", "-", "*", "/" } } diff --git a/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java b/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java index b2be51c10234..fa3869bc5d2e 100644 --- a/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java +++ b/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java @@ -13,7 +13,6 @@ public class StringMatchFiniteAutomata { public static Scanner scanner = null; public static void main(String[] args) { - scanner = new Scanner(System.in); System.out.println("Enter String"); String text = scanner.nextLine(); @@ -26,7 +25,6 @@ public static void main(String[] args) { } public static void searchPat(String text, String pat) { - int m = pat.length(); int n = text.length(); @@ -46,7 +44,6 @@ public static void searchPat(String text, String pat) { // Computes finite automata for the partern public static void computeFA(String pat, int m, int[][] FA) { - for (int state = 0; state <= m; ++state) { for (int x = 0; x < CHARS; ++x) { FA[state][x] = getNextState(pat, m, state, x); @@ -55,7 +52,6 @@ public static void computeFA(String pat, int m, int[][] FA) { } public static int getNextState(String pat, int m, int state, int x) { - // if current state is less than length of pattern // and input character of pattern matches the character in the alphabet // then automata goes to next state @@ -64,11 +60,8 @@ public static int getNextState(String pat, int m, int state, int x) { } for (int ns = state; ns > 0; ns--) { - if (pat.charAt(ns - 1) == x) { - for (int i = 0; i < ns - 1; i++) { - if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) { break; } diff --git a/src/main/java/com/thealgorithms/others/Sudoku.java b/src/main/java/com/thealgorithms/others/Sudoku.java index 6c69663405d9..5ebe92c0c96d 100644 --- a/src/main/java/com/thealgorithms/others/Sudoku.java +++ b/src/main/java/com/thealgorithms/others/Sudoku.java @@ -2,12 +2,9 @@ class Sudoku { - public static boolean isSafe(int[][] board, - int row, int col, - int num) { + public static boolean isSafe(int[][] board, int row, int col, int num) { // Row has the unique (row-clash) for (int d = 0; d < board.length; d++) { - // Check if the number we are trying to // place is already present in // that row, return false; @@ -18,7 +15,6 @@ public static boolean isSafe(int[][] board, // Column has the unique numbers (column-clash) for (int r = 0; r < board.length; r++) { - // Check if the number // we are trying to // place is already present in @@ -34,10 +30,8 @@ public static boolean isSafe(int[][] board, int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; - for (int r = boxRowStart; - r < boxRowStart + sqrt; r++) { - for (int d = boxColStart; - d < boxColStart + sqrt; d++) { + for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { + for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } @@ -48,8 +42,7 @@ public static boolean isSafe(int[][] board, return true; } - public static boolean solveSudoku( - int[][] board, int n) { + public static boolean solveSudoku(int[][] board, int n) { int row = -1; int col = -1; boolean isEmpty = true; @@ -91,9 +84,7 @@ public static boolean solveSudoku( return false; } - public static void print( - int[][] board, int N) { - + public static void print(int[][] board, int N) { // We got the answer, just print it for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { @@ -110,17 +101,16 @@ public static void print( // Driver Code public static void main(String args[]) { - - int[][] board = new int[][]{ - {3, 0, 6, 5, 0, 8, 4, 0, 0}, - {5, 2, 0, 0, 0, 0, 0, 0, 0}, - {0, 8, 7, 0, 0, 0, 0, 3, 1}, - {0, 0, 3, 0, 1, 0, 0, 8, 0}, - {9, 0, 0, 8, 6, 3, 0, 0, 5}, - {0, 5, 0, 0, 9, 0, 6, 0, 0}, - {1, 3, 0, 0, 0, 0, 2, 5, 0}, - {0, 0, 0, 0, 0, 0, 0, 7, 4}, - {0, 0, 5, 2, 0, 6, 3, 0, 0} + int[][] board = new int[][] { + { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 }, }; int N = board.length; diff --git a/src/main/java/com/thealgorithms/others/ThreeSum.java b/src/main/java/com/thealgorithms/others/ThreeSum.java index a9a6c6728862..7c9f3a1f2909 100644 --- a/src/main/java/com/thealgorithms/others/ThreeSum.java +++ b/src/main/java/com/thealgorithms/others/ThreeSum.java @@ -33,7 +33,6 @@ public static void main(String args[]) { Arrays.sort(a); // Sort the array if array is not sorted for (int i = 0; i < n; i++) { - int l = i + 1, r = n - 1; while (l < r) { diff --git a/src/main/java/com/thealgorithms/others/TopKWords.java b/src/main/java/com/thealgorithms/others/TopKWords.java index fe19ca82f2ad..71fd4f9173c5 100644 --- a/src/main/java/com/thealgorithms/others/TopKWords.java +++ b/src/main/java/com/thealgorithms/others/TopKWords.java @@ -20,7 +20,6 @@ public Map getDictionary() { FileInputStream fis = null; try { - fis = new FileInputStream(fileName); // open the file int in = 0; String s = ""; // init a empty word @@ -65,11 +64,12 @@ public Map getDictionary() { public static void main(String[] args) { // you can replace the filePath with yours CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); - Map dictionary - = cw.getDictionary(); // get the words dictionary: {word: frequency} + Map dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency} // we change the map to list for convenient sort - List> list = new ArrayList<>(dictionary.entrySet()); + List> list = new ArrayList<>( + dictionary.entrySet() + ); // sort by lambda valueComparator list.sort(Comparator.comparing(m -> m.getValue())); diff --git a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java index 17100b2ab611..0c1889af8222 100644 --- a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java +++ b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java @@ -4,7 +4,12 @@ class TowerOfHanoi { - public static void shift(int n, String startPole, String intermediatePole, String endPole) { + public static void shift( + int n, + String startPole, + String intermediatePole, + String endPole + ) { // if n becomes zero the program returns thus ending the loop. if (n != 0) { // Shift function is called in recursion for swapping the n-1 disc from the startPole to the diff --git a/src/main/java/com/thealgorithms/others/TwoPointers.java b/src/main/java/com/thealgorithms/others/TwoPointers.java index 814ac1bfb1a4..c5b57f344c28 100644 --- a/src/main/java/com/thealgorithms/others/TwoPointers.java +++ b/src/main/java/com/thealgorithms/others/TwoPointers.java @@ -12,12 +12,12 @@ class TwoPointers { public static void main(String[] args) { - int[] arr = {10, 20, 35, 50, 75, 80}; + int[] arr = { 10, 20, 35, 50, 75, 80 }; int key = 70; assert isPairedSum(arr, key); /* 20 + 60 == 70 */ - arr = new int[]{1, 2, 3, 4, 5, 6, 7}; + arr = new int[] { 1, 2, 3, 4, 5, 6, 7 }; key = 13; assert isPairedSum(arr, key); /* 6 + 7 == 13 */ diff --git a/src/main/java/com/thealgorithms/others/Verhoeff.java b/src/main/java/com/thealgorithms/others/Verhoeff.java index 760ef0e16b68..e60881089214 100644 --- a/src/main/java/com/thealgorithms/others/Verhoeff.java +++ b/src/main/java/com/thealgorithms/others/Verhoeff.java @@ -35,23 +35,34 @@ public class Verhoeff { * Dihedral group
*/ private static final byte[][] MULTIPLICATION_TABLE = { - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, - {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, - {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, - {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, - {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, - {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, - {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, - {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, - {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, - {9, 8, 7, 6, 5, 4, 3, 2, 1, 0} + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, + { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, + { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 }, + { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 }, + { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 }, + { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 }, + { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 }, + { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 }, + { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, + { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ - private static final byte[] MULTIPLICATIVE_INVERSE = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; + private static final byte[] MULTIPLICATIVE_INVERSE = { + 0, + 4, + 3, + 2, + 1, + 5, + 6, + 7, + 8, + 9, + }; /** * The permutation table {@code p}. Applies a permutation to each digit @@ -60,14 +71,14 @@ public class Verhoeff { * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, - {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, - {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, - {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, - {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, - {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, - {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, - {7, 0, 4, 6, 9, 1, 3, 2, 5, 8} + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, + { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, + { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 }, + { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 }, + { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 }, + { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 }, + { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, + { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }, }; /** @@ -137,26 +148,32 @@ public static void main(String[] args) { private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) - ? "valid" - : "not valid"; + ? "valid" + : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); - System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); + System.out.println( + "Generate and add checksum to initial value '" + + input + + "'. Result: '" + + result + + "'" + ); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { - throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); + throw new IllegalArgumentException( + "Input '" + input + "' contains not only digits" + ); } } private static int[] toIntArray(String string) { - return string.chars() - .map(i -> Character.digit(i, 10)) - .toArray(); + return string.chars().map(i -> Character.digit(i, 10)).toArray(); } } diff --git a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java index 25367a972468..418c1c70a440 100644 --- a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java +++ b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java @@ -5,12 +5,14 @@ public class HammingDistance { - - - public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) { - - if(senderBits.length() != receiverBits.length()) { - throw new IllegalArgumentException("Sender and Receiver bits should be same"); + public int getHammingDistanceBetweenBits( + String senderBits, + String receiverBits + ) { + if (senderBits.length() != receiverBits.length()) { + throw new IllegalArgumentException( + "Sender and Receiver bits should be same" + ); } List byteArray = new ArrayList<>(); @@ -18,20 +20,19 @@ public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) byteArray.add(senderBits.getBytes()); byteArray.add(receiverBits.getBytes()); - byte[] senderData = byteArray.get(0); byte[] receiverData = byteArray.get(1); int totalErrorBitCount = 0; - for(int i = 0; i < senderData.length; i++){ - totalErrorBitCount += senderData[i] ^ receiverData[i]; + for (int i = 0; i < senderData.length; i++) { + totalErrorBitCount += senderData[i] ^ receiverData[i]; } - if(totalErrorBitCount == 0){ + if (totalErrorBitCount == 0) { System.out.println("No Error bit in data segments"); - } else{ - System.out.println("Total Error bit count "+totalErrorBitCount); + } else { + System.out.println("Total Error bit count " + totalErrorBitCount); } return totalErrorBitCount; } diff --git a/src/main/java/com/thealgorithms/others/countSetBits.java b/src/main/java/com/thealgorithms/others/countSetBits.java index 33be26fd2b05..fe71e1d7426b 100644 --- a/src/main/java/com/thealgorithms/others/countSetBits.java +++ b/src/main/java/com/thealgorithms/others/countSetBits.java @@ -1,6 +1,7 @@ package com.thealgorithms.others; public class countSetBits { + /** * The below algorithm is called as Brian Kernighan's algorithm * We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit. @@ -35,12 +36,12 @@ public class countSetBits { * @param num takes Long number whose number of set bit is to be found * @return the count of set bits in the binary equivalent */ - public long countsetBits(long num){ - long cnt=0; - while(num>0){ + public long countsetBits(long num) { + long cnt = 0; + while (num > 0) { cnt++; - num&=(num-1); + num &= (num - 1); } return cnt; } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 5bfe92ee86cb..18ec2c0c4ee7 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -2,11 +2,11 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Binary search is one of the most popular algorithms The algorithm finds the @@ -43,7 +43,12 @@ public > int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private > int search(T array[], T key, int left, int right) { + private > int search( + T array[], + T key, + int left, + int right + ) { if (right < left) { return -1; // this means that the key not found } @@ -68,12 +73,12 @@ public static void main(String[] args) { int size = 100; int maxElement = 100000; - Integer[] integers - = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[]::new); + Integer[] integers = IntStream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .boxed() + .toArray(Integer[]::new); // The element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -82,13 +87,22 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index a4616e4d11c5..aae8f58e438a 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -1,4 +1,5 @@ package com.thealgorithms.searches; + /* To apply this method, the provided array must be strictly sorted. In this method, two pointers, one at 0th row & the other at the last row are taken & the searching is done on the basis of the middle element of the middle column. @@ -6,69 +7,81 @@ that element are ignored (because the elements above it will also be smaller than the target), else that element is greater than the target, then the rows below it are ignored. */ -public class BinarySearch2dArray -{ - static int[] BinarySearch(int[][] arr, int target){ +public class BinarySearch2dArray { + static int[] BinarySearch(int[][] arr, int target) { int rowCount = arr.length, colCount = arr[0].length; - if (rowCount == 1){ + if (rowCount == 1) { return binarySearch(arr, target, 0, 0, colCount); } - int startRow = 0, endRow = rowCount - 1, midCol = colCount/2; - - while (startRow < endRow - 1){ + int startRow = 0, endRow = rowCount - 1, midCol = colCount / 2; - int midRow = startRow + (endRow - startRow) / 2; //getting the index of middle row + while (startRow < endRow - 1) { + int midRow = startRow + (endRow - startRow) / 2; //getting the index of middle row - if (arr[midRow][midCol] == target){ - return new int[] {midRow, midCol}; - } - else if (arr[midRow][midCol] < target) - startRow = midRow; - else - endRow = midRow; + if (arr[midRow][midCol] == target) { + return new int[] { midRow, midCol }; + } else if (arr[midRow][midCol] < target) startRow = + midRow; else endRow = midRow; } - /* + /* if the above search fails to find the target element, these conditions will be used to find the target element, which further uses the binary search algorithm in the places which were left unexplored. */ - if (arr[startRow][midCol] == target) - return new int[] {startRow, midCol}; - - if (arr[endRow][midCol] == target) - return new int[] {endRow, midCol}; - - if (target <= arr[startRow][midCol-1]) - return binarySearch(arr, target, startRow, 0, midCol-1); - - if (target >= arr[startRow][midCol+1] && target <= arr[startRow][colCount-1]) - return binarySearch(arr,target, startRow, midCol+1, colCount-1); - - if (target <= arr[endRow][midCol-1]) - return binarySearch(arr, target, endRow, 0, midCol-1); - - else - return binarySearch(arr,target, endRow, midCol+1, colCount-1); + if (arr[startRow][midCol] == target) return new int[] { + startRow, + midCol, + }; + + if (arr[endRow][midCol] == target) return new int[] { endRow, midCol }; + + if (target <= arr[startRow][midCol - 1]) return binarySearch( + arr, + target, + startRow, + 0, + midCol - 1 + ); + + if ( + target >= arr[startRow][midCol + 1] && + target <= arr[startRow][colCount - 1] + ) return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); + + if (target <= arr[endRow][midCol - 1]) return binarySearch( + arr, + target, + endRow, + 0, + midCol - 1 + ); else return binarySearch( + arr, + target, + endRow, + midCol + 1, + colCount - 1 + ); } - static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd){ - - while (colStart <= colEnd){ - + static int[] binarySearch( + int[][] arr, + int target, + int row, + int colStart, + int colEnd + ) { + while (colStart <= colEnd) { int midIndex = colStart + (colEnd - colStart) / 2; - if (arr[row][midIndex] == target) - return new int[] {row, midIndex}; - - else if (arr[row][midIndex] < target) - colStart = midIndex + 1; - else - colEnd = midIndex - 1; + if (arr[row][midIndex] == target) return new int[] { + row, + midIndex, + }; else if (arr[row][midIndex] < target) colStart = + midIndex + 1; else colEnd = midIndex - 1; } - return new int[] {-1, -1}; + return new int[] { -1, -1 }; } } - diff --git a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java index 0cb05f6f3b3d..2907e204c99f 100644 --- a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java @@ -1,7 +1,6 @@ package com.thealgorithms.searches; import com.thealgorithms.searches.DepthFirstSearch.Node; - import java.util.ArrayDeque; import java.util.List; import java.util.Objects; @@ -38,24 +37,33 @@ public static Optional search(final Node node, final String name) { public static void assertThat(final Object actual, final Object expected) { if (!Objects.equals(actual, expected)) { - throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); + throw new AssertionError( + String.format("expected=%s but was actual=%s", expected, actual) + ); } } public static void main(final String[] args) { - final Node rootNode = new Node("A", List.of( - new Node("B", List.of(new Node("D"), new Node("F", List.of( - new Node("H"), new Node("I") - )))), + final Node rootNode = new Node( + "A", + List.of( + new Node( + "B", + List.of( + new Node("D"), + new Node("F", List.of(new Node("H"), new Node("I"))) + ) + ), new Node("C", List.of(new Node("G"))), new Node("E") - )); + ) + ); { final String expected = "I"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -64,7 +72,7 @@ public static void main(final String[] args) { final String expected = "G"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -73,7 +81,7 @@ public static void main(final String[] args) { final String expected = "E"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } diff --git a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java index f355ee30392c..94a3d55ffcd0 100644 --- a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java @@ -40,33 +40,43 @@ public static Optional search(final Node node, final String name) { return Optional.of(node); } - return node.getSubNodes() - .stream() - .map(value -> search(value, name)) - .flatMap(Optional::stream) - .findAny(); + return node + .getSubNodes() + .stream() + .map(value -> search(value, name)) + .flatMap(Optional::stream) + .findAny(); } public static void assertThat(final Object actual, final Object expected) { if (!Objects.equals(actual, expected)) { - throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); + throw new AssertionError( + String.format("expected=%s but was actual=%s", expected, actual) + ); } } public static void main(final String[] args) { - final Node rootNode = new Node("A", List.of( - new Node("B", List.of(new Node("D"), new Node("F", List.of( - new Node("H"), new Node("I") - )))), + final Node rootNode = new Node( + "A", + List.of( + new Node( + "B", + List.of( + new Node("D"), + new Node("F", List.of(new Node("H"), new Node("I"))) + ) + ), new Node("C", List.of(new Node("G"))), new Node("E") - )); + ) + ); { final String expected = "I"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -75,7 +85,7 @@ public static void main(final String[] args) { final String expected = "G"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -84,7 +94,7 @@ public static void main(final String[] args) { final String expected = "E"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java index 3592f50cbe28..f1fc7705f35c 100644 --- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java +++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java @@ -1,12 +1,12 @@ package com.thealgorithms.searches; +import static java.lang.String.format; + +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; - -import static java.lang.String.format; class ExponentialSearch implements SearchAlgorithm { @@ -16,12 +16,12 @@ public static void main(String[] args) { int size = 100; int maxElement = 100000; - Integer[] integers - = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[]::new); + Integer[] integers = IntStream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .boxed() + .toArray(Integer[]::new); // The element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -30,15 +30,23 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); - + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } @Override @@ -56,6 +64,11 @@ public > int find(T[] array, T key) { range = range * 2; } - return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key); + return Arrays.binarySearch( + array, + range / 2, + Math.min(range, array.length), + key + ); } } diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index fdd45cb628a2..bd4af6e528a8 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -3,12 +3,12 @@ import com.thealgorithms.devutils.searches.SearchAlgorithm; /* -* Fibonacci Search is a popular algorithm which finds the position of a target value in -* a sorted array -* -* The time complexity for this search algorithm is O(log3(n)) -* The space complexity for this search algorithm is O(1) -* @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) + * Fibonacci Search is a popular algorithm which finds the position of a target value in + * a sorted array + * + * The time complexity for this search algorithm is O(log3(n)) + * The space complexity for this search algorithm is O(1) + * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) */ public class FibonacciSearch implements SearchAlgorithm { @@ -59,7 +59,7 @@ public > int find(T[] array, T key) { // Driver Program public static void main(String[] args) { - Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; + Integer[] integers = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; int size = integers.length; Integer shouldBeFound = 128; @@ -67,7 +67,14 @@ public static void main(String[] args) { int atIndex = fsearch.find(integers, shouldBeFound); System.out.println( - "Should be found: " + shouldBeFound + ". Found " + integers[atIndex] + " at index " + atIndex + ". An array length " + size); + "Should be found: " + + shouldBeFound + + ". Found " + + integers[atIndex] + + " at index " + + atIndex + + ". An array length " + + size + ); } - } diff --git a/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java index ccdb1439e4d4..df2d2e42bfd7 100644 --- a/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java +++ b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java @@ -33,9 +33,10 @@ public static void main(String[] args) { a[i] = sc.nextInt(); } - System.out.println("The array has been rotated " + rotated(a) + " times"); + System.out.println( + "The array has been rotated " + rotated(a) + " times" + ); sc.close(); - } public static int rotated(int[] a) { diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java index 0ac16685d72b..bb53389a113d 100644 --- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java +++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java @@ -32,7 +32,12 @@ public int find(int array[], int key) { while (start <= end && key >= array[start] && key <= array[end]) { // Probing the position with keeping // uniform distribution in mind. - int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); + int pos = + start + + ( + ((end - start) / (array[end] - array[start])) * + (key - array[start]) + ); // Condition of target found if (array[pos] == key) { @@ -55,7 +60,11 @@ public static void main(String[] args) { Random r = new Random(); int size = 100; int maxElement = 100000; - int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); + int[] integers = IntStream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .toArray(); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -64,13 +73,22 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - String.format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java index ce375df24a94..7f71ba3dd12a 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -2,10 +2,10 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Binary search is one of the most popular algorithms This class represents @@ -60,8 +60,11 @@ public static void main(String[] args) { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers - = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + Integer[] integers = Stream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .toArray(Integer[]::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -70,13 +73,22 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - String.format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java index 09139578e2bb..176091229112 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java @@ -2,10 +2,10 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * A iterative version of a ternary search algorithm This is better way to @@ -31,7 +31,6 @@ public > int find(T[] array, T key) { int right = array.length - 1; while (right > left) { - int leftCmp = array[left].compareTo(key); int rightCmp = array[right].compareTo(key); if (leftCmp == 0) { @@ -59,8 +58,11 @@ public static void main(String[] args) { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers - = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + Integer[] integers = Stream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .toArray(Integer[]::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -69,13 +71,22 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/JumpSearch.java b/src/main/java/com/thealgorithms/searches/JumpSearch.java index f499cf8079cc..36bbb39370d0 100644 --- a/src/main/java/com/thealgorithms/searches/JumpSearch.java +++ b/src/main/java/com/thealgorithms/searches/JumpSearch.java @@ -6,7 +6,7 @@ public class JumpSearch implements SearchAlgorithm { public static void main(String[] args) { JumpSearch jumpSearch = new JumpSearch(); - Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int i = 0; i < array.length; i++) { assert jumpSearch.find(array, i) == i; } diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java index 0f3239ceafd0..223bc06699ac 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -1,20 +1,20 @@ package com.thealgorithms.searches; class KMPSearch { - int KMPSearch(String pat, String txt) - { + + int KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); - + // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] - + // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); - + int i = 0; // index for txt[] while ((N - i) >= (M - j)) { if (pat.charAt(j) == txt.charAt(i)) { @@ -22,62 +22,48 @@ int KMPSearch(String pat, String txt) i++; } if (j == M) { - System.out.println("Found pattern " - + "at index " + (i - j)); + System.out.println("Found pattern " + "at index " + (i - j)); int index = (i - j); j = lps[j - 1]; return index; - } - // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway - if (j != 0) - j = lps[j - 1]; - else - i = i + 1; + if (j != 0) j = lps[j - 1]; else i = i + 1; } } System.out.println("No pattern found"); - return -1; + return -1; } - - void computeLPSArray(String pat, int M, int lps[]) - { + + void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 - + // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; - } - else // (pat[i] != pat[len]) - { + } else { // (pat[i] != pat[len]) // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; - // Also, note that we do not increment // i here - } - else // if (len == 0) - { + } else { // if (len == 0) lps[i] = len; i++; } } } } - - } // This code has been contributed by Amit Khandelwal. diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java index 330b68fdac34..bd97d0a9c7d9 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearch.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java @@ -1,8 +1,8 @@ package com.thealgorithms.searches; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Random; import java.util.stream.Stream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Linear search is the easiest search algorithm It works with sorted and @@ -42,8 +42,10 @@ public static void main(String[] args) { Random r = new Random(); int size = 200; int maxElement = 100; - Integer[] integers - = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new); + Integer[] integers = Stream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .toArray(Integer[]::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -52,8 +54,13 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - String.format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java index 686135255e27..98638ef4cbe1 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java @@ -3,6 +3,7 @@ import java.util.Scanner; public class LinearSearchThread { + public static void main(String[] args) { int[] list = new int[200]; for (int j = 0; j < list.length; j++) { @@ -28,14 +29,15 @@ public static void main(String[] args) { t1.join(); t2.join(); t3.join(); - } catch (InterruptedException e) { - } - boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); + } catch (InterruptedException e) {} + boolean found = + t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); System.out.println("Found = " + found); } } class Searcher extends Thread { + private final int[] arr; private final int left, right; private final int x; diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index 1fc9b24b0777..0822ae6df007 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -2,10 +2,10 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * The LowerBound method is used to return an index pointing to the first @@ -35,12 +35,12 @@ public static void main(String[] args) { int size = 100; int maxElement = 100000; - Integer[] integers - = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[]::new); + Integer[] integers = IntStream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .boxed() + .toArray(Integer[]::new); // The element for which the lower bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -49,14 +49,23 @@ public static void main(String[] args) { int atIndex = search.find(integers, val); System.out.println( - format( - "Val: %d. Lower Bound Found %d at index %d. An array length %d", - val, integers[atIndex], atIndex, size)); + format( + "Val: %d. Lower Bound Found %d at index %d. An array length %d", + val, + integers[atIndex], + atIndex, + size + ) + ); boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val; System.out.println( - format( - "Lower Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck)); + format( + "Lower Bound found at an index: %d. Is greater or max element: %b", + atIndex, + toCheck + ) + ); } /** @@ -79,7 +88,12 @@ public > int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private > int search(T[] array, T key, int left, int right) { + private > int search( + T[] array, + T key, + int left, + int right + ) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index d6f6c756bc8b..3765d871bdf1 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -1,7 +1,7 @@ package com.thealgorithms.searches; -import java.util.Collections; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.Random; @@ -23,8 +23,7 @@ public class Node { int score; int visitCount; - public Node() { - } + public Node() {} public Node(Node parent, boolean isPlayersTurn) { this.parent = parent; @@ -78,7 +77,10 @@ public Node monteCarloTreeSearch(Node rootNode) { winnerNode = getWinnerNode(rootNode); printScores(rootNode); - System.out.format("\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1); + System.out.format( + "\nThe optimal node is: %02d\n", + rootNode.childNodes.indexOf(winnerNode) + 1 + ); return winnerNode; } @@ -118,8 +120,13 @@ public Node getPromisingNode(Node rootNode) { break; } - uctTemp = ((double) childNode.score / childNode.visitCount) - + 1.41 * Math.sqrt(Math.log(promisingNode.visitCount) / (double) childNode.visitCount); + uctTemp = + ((double) childNode.score / childNode.visitCount) + + 1.41 * + Math.sqrt( + Math.log(promisingNode.visitCount) / + (double) childNode.visitCount + ); if (uctTemp > uctIndex) { uctIndex = uctTemp; @@ -148,7 +155,7 @@ public void simulateRandomPlay(Node promisingNode) { // To use the MCTS algorithm correctly this should be a simulation of the nodes' current // state of the game until it finishes (if possible) and use an evaluation function to // determine how good or bad the play was. - // e.g. Play tic tac toe choosing random squares until the game ends. + // e.g. Play tic tac toe choosing random squares until the game ends. promisingNode.playerWon = (rand.nextInt(6) == 0); isPlayerWinner = promisingNode.playerWon; @@ -158,8 +165,10 @@ public void simulateRandomPlay(Node promisingNode) { tempNode.visitCount++; // Add wining scores to bouth player and opponent depending on the turn. - if ((tempNode.isPlayersTurn && isPlayerWinner) - || (!tempNode.isPlayersTurn && !isPlayerWinner)) { + if ( + (tempNode.isPlayersTurn && isPlayerWinner) || + (!tempNode.isPlayersTurn && !isPlayerWinner) + ) { tempNode.score += WIN_SCORE; } @@ -168,15 +177,24 @@ public void simulateRandomPlay(Node promisingNode) { } public Node getWinnerNode(Node rootNode) { - return Collections.max(rootNode.childNodes, Comparator.comparing(c -> c.score)); + return Collections.max( + rootNode.childNodes, + Comparator.comparing(c -> c.score) + ); } public void printScores(Node rootNode) { System.out.println("N.\tScore\t\tVisits"); for (int i = 0; i < rootNode.childNodes.size(); i++) { - System.out.println(String.format("%02d\t%d\t\t%d", i + 1, - rootNode.childNodes.get(i).score, rootNode.childNodes.get(i).visitCount)); + System.out.println( + String.format( + "%02d\t%d\t\t%d", + i + 1, + rootNode.childNodes.get(i).score, + rootNode.childNodes.get(i).visitCount + ) + ); } } } diff --git a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java index 8ce01575b67d..416ddf6e1182 100644 --- a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java @@ -22,7 +22,7 @@ static int binarySearch(int[] arr, int target) { public static void main(String[] args) { PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); - int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; assert BinarySearch.binarySearch(array, -1) == -1; assert BinarySearch.binarySearch(array, 11) == -1; } diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java index fee11cabbcee..9747a8179343 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -45,19 +45,21 @@ public static > T select(List list, int n) { return list.get(index); } - private static > int selectIndex(List list, int n) { + private static > int selectIndex( + List list, + int n + ) { return selectIndex(list, 0, list.size() - 1, n); } private static > int selectIndex( - List list, - int left, - int right, - int n + List list, + int left, + int right, + int n ) { while (true) { - if (left == right) - return left; + if (left == right) return left; int pivotIndex = pivot(list, left, right); pivotIndex = partition(list, left, right, pivotIndex, n); if (n == pivotIndex) { @@ -71,11 +73,11 @@ private static > int selectIndex( } private static > int partition( - List list, - int left, - int right, - int pivotIndex, - int n + List list, + int left, + int right, + int pivotIndex, + int n ) { T pivotValue = list.get(pivotIndex); Collections.swap(list, pivotIndex, right); @@ -99,15 +101,13 @@ private static > int partition( Collections.swap(list, right, storeIndexEq); - return (n < storeIndex) - ? storeIndex - : Math.min(n, storeIndexEq); + return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq); } private static > int pivot( - List list, - int left, - int right + List list, + int left, + int right ) { if (right - left < 5) { return partition5(list, left, right); @@ -129,9 +129,9 @@ private static > int pivot( } private static > int partition5( - List list, - int left, - int right + List list, + int left, + int right ) { List ts = list.subList(left, right); ts.sort(Comparator.naturalOrder()); diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index 1da9bbc1f477..cda1bfec051f 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -1,77 +1,66 @@ package com.thealgorithms.searches; -// Following program is a Java implementation + +// Following program is a Java implementation // of Rabin Karp Algorithm given in the CLRS book - -public class RabinKarpAlgorithm -{ + +public class RabinKarpAlgorithm { + // d is the number of characters in the input alphabet - public final static int d = 256; - + public static final int d = 256; + /* pat -> pattern txt -> text q -> A prime number */ - public int search(String pat, String txt, int q) - { - int index = -1; //note: -1 here represent not found, it is not an index + public int search(String pat, String txt, int q) { + int index = -1; //note: -1 here represent not found, it is not an index int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; - + // The value of h would be "pow(d, M-1)%q" - for (i = 0; i < M-1; i++) - h = (h*d)%q; - + for (i = 0; i < M - 1; i++) h = (h * d) % q; + // Calculate the hash value of pattern and first // window of text - for (i = 0; i < M; i++) - { - p = (d*p + pat.charAt(i))%q; - t = (d*t + txt.charAt(i))%q; + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; } - + // Slide the pattern over text one by one - for (i = 0; i <= N - M; i++) - { - + for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one - if ( p == t ) - { + if (p == t) { /* Check for characters one by one */ - for (j = 0; j < M; j++) - { - if (txt.charAt(i+j) != pat.charAt(j)) - break; + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) break; } - + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { System.out.println("Pattern found at index " + i); - index= i; - return index ; + index = i; + return index; } } - + // Calculate hash value for next window of text: Remove // leading digit, add trailing digit - if ( i < N-M ) - { - t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; - + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + // We might get negative value of t, converting it // to positive - if (t < 0) - t = (t + q); + if (t < 0) t = (t + q); } } return index; // return -1 if pattern does not found } - } - // This code is contributed by nuclode diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 719a60d31f8a..5bcda7dd8d1f 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -29,9 +29,8 @@ public class SaddlebackSearch { * -1 -1. */ private static int[] find(int arr[][], int row, int col, int key) { - // array to store the answer row and column - int ans[] = {-1, -1}; + int ans[] = { -1, -1 }; if (row < 0 || col >= arr[row].length) { return ans; } diff --git a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java index 399499f57ed9..362fef91d53a 100644 --- a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java @@ -23,7 +23,9 @@ public class SquareRootBinarySearch { */ public static void main(String args[]) { Scanner sc = new Scanner(System.in); - System.out.print("Enter a number you want to calculate square root of : "); + System.out.print( + "Enter a number you want to calculate square root of : " + ); int num = sc.nextInt(); long ans = squareRoot(num); System.out.println("The square root is : " + ans); diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index 47bb690b191a..170b3e104b45 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -2,10 +2,10 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * A ternary search algorithm is a technique in computer science for finding the @@ -41,7 +41,12 @@ public > int find(T[] arr, T value) { * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ - private > int ternarySearch(T[] arr, T key, int start, int end) { + private > int ternarySearch( + T[] arr, + T key, + int start, + int end + ) { if (start > end) { return -1; } @@ -54,11 +59,15 @@ private > int ternarySearch(T[] arr, T key, int start, i return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; - } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { + } /* Search the first (1/3) rd part of the array.*/else if ( + key.compareTo(arr[mid1]) < 0 + ) { return ternarySearch(arr, key, start, --mid1); - } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { + } /* Search 3rd (1/3)rd part of the array */else if ( + key.compareTo(arr[mid2]) > 0 + ) { return ternarySearch(arr, key, ++mid2, end); - } /* Search middle (1/3)rd part of the array */ else { + } /* Search middle (1/3)rd part of the array */else { return ternarySearch(arr, key, mid1, mid2); } } @@ -68,8 +77,11 @@ public static void main(String[] args) { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers - = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + Integer[] integers = Stream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .toArray(Integer[]::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -78,13 +90,22 @@ public static void main(String[] args) { int atIndex = search.find(integers, shouldBeFound); System.out.println( - format( - "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, + integers[atIndex], + atIndex, + size + ) + ); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println( - format( - "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + format( + "Found by system method at an index: %d. Is equal: %b", + toCheck, + toCheck == atIndex + ) + ); } } diff --git a/src/main/java/com/thealgorithms/searches/UnionFind.java b/src/main/java/com/thealgorithms/searches/UnionFind.java index d32e4fd3ec1f..ec0a694bb282 100644 --- a/src/main/java/com/thealgorithms/searches/UnionFind.java +++ b/src/main/java/com/thealgorithms/searches/UnionFind.java @@ -61,19 +61,27 @@ public String toString() { // Tests public static void main(String[] args) { UnionFind uf = new UnionFind(5); - System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):"); + System.out.println( + "init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):" + ); System.out.println(uf); uf.union(1, 2); - System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):"); + System.out.println( + "union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):" + ); System.out.println(uf); uf.union(3, 4); - System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); + System.out.println( + "union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" + ); System.out.println(uf); uf.find(4); - System.out.println("find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); + System.out.println( + "find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" + ); System.out.println(uf); System.out.println("count (should print '3'):"); diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java index cae38363eb0d..0b5cfa09091d 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -2,10 +2,10 @@ import static java.lang.String.format; +import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; -import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * The UpperBound method is used to return an index pointing to the first @@ -35,12 +35,12 @@ public static void main(String[] args) { int size = 100; int maxElement = 100000; - Integer[] integers - = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[]::new); + Integer[] integers = IntStream + .generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .boxed() + .toArray(Integer[]::new); // The element for which the upper bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -49,14 +49,23 @@ public static void main(String[] args) { int atIndex = search.find(integers, val); System.out.println( - format( - "Val: %d. Upper Bound Found %d at index %d. An array length %d", - val, integers[atIndex], atIndex, size)); + format( + "Val: %d. Upper Bound Found %d at index %d. An array length %d", + val, + integers[atIndex], + atIndex, + size + ) + ); boolean toCheck = integers[atIndex] > val || integers[size - 1] < val; System.out.println( - format( - "Upper Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck)); + format( + "Upper Bound found at an index: %d. Is greater or max element: %b", + atIndex, + toCheck + ) + ); } /** @@ -79,7 +88,12 @@ public > int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private > int search(T[] array, T key, int left, int right) { + private > int search( + T[] array, + T key, + int left, + int right + ) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java index 1a2b1159cdae..1c2dce65c953 100644 --- a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java @@ -1,32 +1,29 @@ package com.thealgorithms.sorts; -public class BinaryInsertionSort{ - - - // Binary Insertion Sort method - public int[] binaryInsertSort(int[] array){ - - for(int i = 1; i < array.length; i++){ - - int temp=array[i]; - int low = 0; - int high = i - 1; - - while(low <= high){ - int mid = (low + high) / 2; - if(temp < array[mid]){ - high = mid - 1; - }else{ +public class BinaryInsertionSort { + + // Binary Insertion Sort method + public int[] binaryInsertSort(int[] array) { + for (int i = 1; i < array.length; i++) { + int temp = array[i]; + int low = 0; + int high = i - 1; + + while (low <= high) { + int mid = (low + high) / 2; + if (temp < array[mid]) { + high = mid - 1; + } else { low = mid + 1; - } + } } - - for(int j = i; j >= low + 1; j--){ - array[j] = array[j - 1]; - } - - array[low] = temp; - } + + for (int j = i; j >= low + 1; j--) { + array[j] = array[j - 1]; + } + + array[low] = temp; + } return array; } } diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java index 4f780ebdfe04..35acaf4de1ec 100644 --- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java +++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java @@ -69,7 +69,7 @@ static void printArray(int arr[]) { } public static void main(String args[]) { - int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; + int a[] = { 3, 7, 4, 8, 6, 2, 1, 5 }; int up = 1; BitonicSort ob = new BitonicSort(); ob.sort(a, a.length, up); diff --git a/src/main/java/com/thealgorithms/sorts/BogoSort.java b/src/main/java/com/thealgorithms/sorts/BogoSort.java index 75f1e84367c3..26a2a3a16463 100644 --- a/src/main/java/com/thealgorithms/sorts/BogoSort.java +++ b/src/main/java/com/thealgorithms/sorts/BogoSort.java @@ -39,7 +39,7 @@ public > T[] sort(T[] array) { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; BogoSort bogoSort = new BogoSort(); @@ -47,7 +47,7 @@ public static void main(String[] args) { SortUtils.print(bogoSort.sort(integers)); // String Input - String[] strings = {"c", "a", "e", "b", "d"}; + String[] strings = { "c", "a", "e", "b", "d" }; SortUtils.print(bogoSort.sort(strings)); } diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java index 10197969e853..c95f549a180f 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java @@ -41,7 +41,10 @@ public > T[] sort(T[] unsorted) { * @param unsorted array contains elements * @param len length of given array */ - private static > void bubbleSort(T[] unsorted, int len) { + private static > void bubbleSort( + T[] unsorted, + int len + ) { boolean swapped = false; /* flag to check if array is sorted or not */ for (int i = 0; i < len - 1; ++i) { diff --git a/src/main/java/com/thealgorithms/sorts/CircleSort.java b/src/main/java/com/thealgorithms/sorts/CircleSort.java index 7dcd63f46cb1..2ad09d15bf8a 100644 --- a/src/main/java/com/thealgorithms/sorts/CircleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CircleSort.java @@ -5,7 +5,7 @@ public class CircleSort implements SortAlgorithm { /* This method implements the circle sort - * @param array The array to be sorted + * @param array The array to be sorted */ @Override public > T[] sort(T[] array) { @@ -15,11 +15,15 @@ public > T[] sort(T[] array) { } /* This method implements the cyclic sort recursive version - * @param array The array to be sorted - * @param the left boundary of the part currently being sorted - * @param the right boundary of the part currently being sorted + * @param array The array to be sorted + * @param the left boundary of the part currently being sorted + * @param the right boundary of the part currently being sorted */ - private > Boolean doSort(T[] array, int left, int right) { + private > Boolean doSort( + T[] array, + int left, + int right + ) { Boolean swapped = false; if (left == right) { @@ -54,13 +58,13 @@ private > Boolean doSort(T[] array, int left, int right) public static void main(String[] args) { CircleSort CSort = new CircleSort(); - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; CSort.sort(arr); for (int i = 0; i < arr.length - 1; ++i) { assert arr[i] <= arr[i + 1]; } - String[] stringArray = {"c", "a", "e", "b", "d"}; + String[] stringArray = { "c", "a", "e", "b", "d" }; CSort.sort(stringArray); for (int i = 0; i < stringArray.length - 1; ++i) { assert arr[i].compareTo(arr[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java index 6bf98dbc8bc3..474fa3d79cd3 100644 --- a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java +++ b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java @@ -13,7 +13,6 @@ class CocktailShakerSort implements SortAlgorithm { */ @Override public > T[] sort(T[] array) { - int length = array.length; int left = 0; int right = length - 1; @@ -44,14 +43,14 @@ public > T[] sort(T[] array) { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; CocktailShakerSort shakerSort = new CocktailShakerSort(); // Output => 1 4 6 9 12 23 54 78 231 SortUtils.print(shakerSort.sort(integers)); // String Input - String[] strings = {"c", "a", "e", "b", "d"}; + String[] strings = { "c", "a", "e", "b", "d" }; SortUtils.print(shakerSort.sort(strings)); } } diff --git a/src/main/java/com/thealgorithms/sorts/CombSort.java b/src/main/java/com/thealgorithms/sorts/CombSort.java index 9bd3fb181c33..7ddce43df9f5 100644 --- a/src/main/java/com/thealgorithms/sorts/CombSort.java +++ b/src/main/java/com/thealgorithms/sorts/CombSort.java @@ -64,7 +64,26 @@ public > T[] sort(T[] arr) { // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); - Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; + Integer[] arr = { + 8, + 4, + 1, + 56, + 3, + -44, + -1, + 0, + 36, + 34, + 8, + 12, + -66, + -78, + 23, + -6, + 28, + 0, + }; ob.sort(arr); System.out.println("sorted array"); diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 47e91d880a21..570fd3e83b94 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -29,7 +29,6 @@ public > T[] sort(T[] unsorted) { */ @Override public > List sort(List list) { - Map frequency = new TreeMap<>(); // The final output array List sortedArray = new ArrayList<>(list.size()); @@ -54,19 +53,25 @@ public > List sort(List list) { * @param list The list to be sorted */ private static > List streamSort(List list) { - return list.stream() - .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) - .entrySet() - .stream() - .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) - .collect(toList()); + return list + .stream() + .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) + .entrySet() + .stream() + .flatMap(entry -> + IntStream + .rangeClosed(1, entry.getValue()) + .mapToObj(t -> entry.getKey()) + ) + .collect(toList()); } // Driver Program public static void main(String[] args) { // Integer Input - List unsortedInts - = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); + List unsortedInts = Stream + .of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12) + .collect(toList()); CountingSort countingSort = new CountingSort(); System.out.println("Before Sorting:"); @@ -81,8 +86,9 @@ public static void main(String[] args) { System.out.println("\n------------------------------\n"); // String Input - List unsortedStrings - = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); + List unsortedStrings = Stream + .of("c", "a", "e", "b", "d", "a", "f", "g", "c") + .collect(toList()); System.out.println("Before Sorting:"); print(unsortedStrings); diff --git a/src/main/java/com/thealgorithms/sorts/CycleSort.java b/src/main/java/com/thealgorithms/sorts/CycleSort.java index 8e463c811ce7..6d21888e4135 100644 --- a/src/main/java/com/thealgorithms/sorts/CycleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CycleSort.java @@ -74,7 +74,23 @@ private > T replace(T[] arr, int pos, T item) { } public static void main(String[] args) { - Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; + Integer arr[] = { + 4, + 23, + 6, + 78, + 1, + 26, + 11, + 23, + 0, + -6, + 3, + 54, + 231, + 9, + 12, + }; CycleSort cycleSort = new CycleSort(); cycleSort.sort(arr); diff --git a/src/main/java/com/thealgorithms/sorts/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java index b02bfc54ef67..912b673409e9 100644 --- a/src/main/java/com/thealgorithms/sorts/DNFSort.java +++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java @@ -10,24 +10,26 @@ static void sort012(int a[], int arr_size) { int mid = 0, temp = 0; while (mid <= high) { switch (a[mid]) { - case 0: { - temp = a[low]; - a[low] = a[mid]; - a[mid] = temp; - low++; - mid++; - break; - } + case 0: + { + temp = a[low]; + a[low] = a[mid]; + a[mid] = temp; + low++; + mid++; + break; + } case 1: mid++; break; - case 2: { - temp = a[mid]; - a[mid] = a[high]; - a[high] = temp; - high--; - break; - } + case 2: + { + temp = a[mid]; + a[mid] = a[high]; + a[high] = temp; + high--; + break; + } } } } @@ -42,7 +44,7 @@ static void printArray(int arr[], int arr_size) { /*Driver function to check for above functions*/ public static void main(String[] args) { - int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java index a2e32c2f0ecc..5a2c8a01d09f 100644 --- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java +++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java @@ -15,30 +15,36 @@ public class DutchNationalFlagSort implements SortAlgorithm { @Override public > T[] sort(T[] unsorted) { - return dutch_national_flag_sort(unsorted, unsorted[(int) Math.ceil((unsorted.length)/2.0) -1]); + return dutch_national_flag_sort( + unsorted, + unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1] + ); } public > T[] sort(T[] unsorted, T intendedMiddle) { return dutch_national_flag_sort(unsorted, intendedMiddle); } - private > T[] dutch_national_flag_sort(T[] arr, T intendedMiddle){ + private > T[] dutch_national_flag_sort( + T[] arr, + T intendedMiddle + ) { int i = 0; int j = 0; int k = arr.length - 1; - while( j <= k){ - if ( 0 > arr[j].compareTo(intendedMiddle)){ + while (j <= k) { + if (0 > arr[j].compareTo(intendedMiddle)) { SortUtils.swap(arr, i, j); j++; i++; - } else if (0 < arr[j].compareTo(intendedMiddle)){ + } else if (0 < arr[j].compareTo(intendedMiddle)) { SortUtils.swap(arr, j, k); k--; } else { j++; } } - return arr; + return arr; } } diff --git a/src/main/java/com/thealgorithms/sorts/GnomeSort.java b/src/main/java/com/thealgorithms/sorts/GnomeSort.java index fcdd4a917667..33a13d5bb2d4 100644 --- a/src/main/java/com/thealgorithms/sorts/GnomeSort.java +++ b/src/main/java/com/thealgorithms/sorts/GnomeSort.java @@ -29,8 +29,38 @@ public > T[] sort(T[] arr) { } public static void main(String[] args) { - Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; - String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; + Integer[] integers = { + 4, + 23, + 6, + 78, + 1, + 26, + 11, + 23, + 0, + -6, + 3, + 54, + 231, + 9, + 12, + }; + String[] strings = { + "c", + "a", + "e", + "b", + "d", + "dd", + "da", + "zz", + "AA", + "aa", + "aB", + "Hb", + "Z", + }; GnomeSort gnomeSort = new GnomeSort(); gnomeSort.sort(integers); diff --git a/src/main/java/com/thealgorithms/sorts/HeapSort.java b/src/main/java/com/thealgorithms/sorts/HeapSort.java index 92669a7be9ec..1a96eaa39e99 100644 --- a/src/main/java/com/thealgorithms/sorts/HeapSort.java +++ b/src/main/java/com/thealgorithms/sorts/HeapSort.java @@ -99,7 +99,9 @@ public > List sort(List unsorted) { int size = unsorted.size(); @SuppressWarnings("unchecked") - Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); + Heap heap = new Heap<>( + unsorted.toArray((T[]) new Comparable[unsorted.size()]) + ); heap.makeMinHeap(0); // make min heap using index 0 as root. List sorted = new ArrayList<>(size); @@ -117,7 +119,7 @@ public > List sort(List unsorted) { * @param args the command line arguments */ public static void main(String[] args) { - Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] heap = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; HeapSort heapSort = new HeapSort(); print(heapSort.sort(heap)); } diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index cde6d7bee57a..9fec4d408fb6 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -31,13 +31,13 @@ public > T[] sort(T[] array) { * Driver Code */ public static void main(String[] args) { - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; InsertionSort sort = new InsertionSort(); sort.sort(integers); print(integers); /* [1, 4, 6, 9, 12, 23, 54, 78, 231] */ - String[] strings = {"c", "a", "e", "b", "d"}; + String[] strings = { "c", "a", "e", "b", "d" }; sort.sort(strings); print(strings); /* [a, b, c, d, e] */ diff --git a/src/main/java/com/thealgorithms/sorts/LinkList_Sort.java b/src/main/java/com/thealgorithms/sorts/LinkList_Sort.java index 2480091621a9..d81218a72e88 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkList_Sort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkList_Sort.java @@ -5,11 +5,13 @@ /** Program description - To sort the LinkList as per sorting technique */ package com.thealgorithms.sorts; + import java.util.*; + public class LinkList_Sort { - public static boolean isSorted(int p[] , int option) { - try (Scanner sc = new Scanner(System.in)) { - } + + public static boolean isSorted(int p[], int option) { + try (Scanner sc = new Scanner(System.in)) {} int a[] = p; // Array is taken as input from test class int b[] = p; @@ -24,62 +26,51 @@ public static boolean isSorted(int p[] , int option) { // New nodes are created and values are added fresh = new Node(); // Node class is called fresh.val = a[i]; // Node val is stored - if (start == null) - start = fresh; - else - prev.next = fresh; + if (start == null) start = fresh; else prev.next = fresh; prev = fresh; } start = nm.sort_by_mergesort(start); // method is being called - int i=0; - for (ptr = start;ptr != null; ptr = ptr.next) { - a[i++]=ptr.val; + int i = 0; + for (ptr = start; ptr != null; ptr = ptr.next) { + a[i++] = ptr.val; // storing the sorted values in the array } Arrays.sort(b); // array b is sorted and it will return true when checked with sorted list - LinkList_Sort uu=new LinkList_Sort(); - if(uu.compare(a,b)) - { + LinkList_Sort uu = new LinkList_Sort(); + if (uu.compare(a, b)) { return true; - } - else - { + } else { return false; } - // The given array and the expected array is checked if both are same then true is displayed else false is displayed + // The given array and the expected array is checked if both are same then true is displayed else false is displayed case 2: Node start1 = null, prev1 = null, fresh1, ptr1; for (int i1 = 0; i1 < a.length; i1++) { // New nodes are created and values are added fresh1 = new Node(); // New node is created fresh1.val = a[i1]; // Value is stored in the value part of the node - if (start1 == null) - start1 = fresh1; - else - prev1.next = fresh1; + if (start1 == null) start1 = fresh1; else prev1.next = + fresh1; prev1 = fresh1; } Task1 kk = new Task1(); start1 = kk.sort_by_insertionsort(start1); // method is being called - int i1=0; + int i1 = 0; for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { - a[i1++]=ptr1.val; + a[i1++] = ptr1.val; // storing the sorted values in the array } - LinkList_Sort uu1=new LinkList_Sort(); + LinkList_Sort uu1 = new LinkList_Sort(); // array b is not sorted and it will return false when checked with sorted list - if(uu1.compare(a,b)) - { + if (uu1.compare(a, b)) { return true; - } - else - { + } else { return false; } - // The given array and the expected array is checked if both are same then true is displayed else false is displayed + // The given array and the expected array is checked if both are same then true is displayed else false is displayed case 3: Task2 mm = new Task2(); Node start2 = null, prev2 = null, fresh2, ptr2; @@ -87,31 +78,26 @@ public static boolean isSorted(int p[] , int option) { // New nodes are created and values are added fresh2 = new Node(); // Node class is created fresh2.val = a[i2]; // Value is stored in the value part of the Node - if (start2 == null) - start2 = fresh2; - else - prev2.next = fresh2; + if (start2 == null) start2 = fresh2; else prev2.next = + fresh2; prev2 = fresh2; } start2 = mm.sort_by_heapsort(start2); // method is being called - int i3=0; + int i3 = 0; for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { - a[i3++]=ptr2.val; + a[i3++] = ptr2.val; // storing the sorted values in the array } Arrays.sort(b); // array b is sorted and it will return true when checked with sorted list - LinkList_Sort uu2=new LinkList_Sort(); - if(uu2.compare(a,b)) - { + LinkList_Sort uu2 = new LinkList_Sort(); + if (uu2.compare(a, b)) { return true; - } - else - { + } else { return false; } - // The given array and the expected array is checked if both are same then true is displayed else false is displayed + // The given array and the expected array is checked if both are same then true is displayed else false is displayed default: // default is used incase user puts a unauthorized value System.out.println("Wrong choice"); @@ -119,12 +105,10 @@ public static boolean isSorted(int p[] , int option) { // Switch case is used to call the classes as per the user requirement return false; } - boolean compare(int a[] , int b[]) - { - for(int i=0;i= n[i]) - b[k++] = n[i++]; - else - b[k++] = n[j++]; + if (n[j] >= n[i]) b[k++] = n[i++]; else b[k++] = n[j++]; } // Smallest number is stored after checking from both the arrays while (i <= m) { @@ -215,10 +197,11 @@ void task1(int n[], int s, int m, int e) { } // The method task and task1 is used to sort the linklist using merge sort } + class Task1 { + public Node sort_by_insertionsort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); int a[] = new int[c]; // Array of size c is created @@ -256,11 +239,11 @@ static int count(Node head) { } class Task2 { + static int a[]; public Node sort_by_heapsort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); a = new int[c]; // Array of size c is created @@ -307,10 +290,8 @@ void task1(int n[], int k, int i) { int p = i; int l = 2 * i + 1; int r = 2 * i + 2; - if (l < k && n[l] > n[p]) - p = l; - if (r < k && n[r] > n[p]) - p = r; + if (l < k && n[l] > n[p]) p = l; + if (r < k && n[r] > n[p]) p = r; if (p != i) { int d = n[p]; n[p] = n[i]; @@ -319,4 +300,4 @@ void task1(int n[], int k, int i) { } } // The method task and task1 is used to sort the linklist using heap sort -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/sorts/MergeSort.java b/src/main/java/com/thealgorithms/sorts/MergeSort.java index ce50a4344006..b62e32b092de 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSort.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSort.java @@ -25,7 +25,11 @@ public > T[] sort(T[] unsorted) { * @param left the first index of the array. * @param right the last index of the array. */ - private static > void doSort(T[] arr, int left, int right) { + private static > void doSort( + T[] arr, + int left, + int right + ) { if (left < right) { int mid = (left + right) >>> 1; doSort(arr, left, mid); @@ -43,7 +47,12 @@ private static > void doSort(T[] arr, int left, int righ * @param right the last index of the array merges two parts of an array in * increasing order. */ - private static > void merge(T[] arr, int left, int mid, int right) { + private static > void merge( + T[] arr, + int left, + int mid, + int right + ) { int length = right - left + 1; @SuppressWarnings("unchecked") T[] temp = (T[]) new Comparable[length]; @@ -76,13 +85,13 @@ private static > void merge(T[] arr, int left, int mid, public static void main(String[] args) { MergeSort mergeSort = new MergeSort(); - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; mergeSort.sort(arr); for (int i = 0; i < arr.length - 1; ++i) { assert arr[i] <= arr[i + 1]; } - String[] stringArray = {"c", "a", "e", "b", "d"}; + String[] stringArray = { "c", "a", "e", "b", "d" }; mergeSort.sort(stringArray); for (int i = 0; i < stringArray.length - 1; ++i) { assert arr[i].compareTo(arr[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java index f4df83726577..3953b5ed1b8c 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; -import java.util.Arrays; import java.util.*; +import java.util.Arrays; /*This code implements the mergeSort algorithm without extra space For understanding about mergesort visit :https://www.geeksforgeeks.org/merge-sort/ @@ -14,49 +14,48 @@ public static void call_merge_sort(int a[], int n) { } public static void merge_sort(int a[], int start, int end, int maxele) { //this function divides the array into 2 halves - if (start < end) { int mid = (start + end) / 2; merge_sort(a, start, mid, maxele); merge_sort(a, mid + 1, end, maxele); implement_merge_sort(a, start, mid, end, maxele); - } } - public static void implement_merge_sort(int a[], int start, int mid, int end, int maxele) { //implementation of mergesort + public static void implement_merge_sort( + int a[], + int start, + int mid, + int end, + int maxele + ) { //implementation of mergesort int i = start; int j = mid + 1; int k = start; while (i <= mid && j <= end) { if (a[i] % maxele <= a[j] % maxele) { - a[k] = a[k] + (a[i] - % maxele) * maxele; + a[k] = a[k] + (a[i] % maxele) * maxele; k++; i++; } else { - a[k] = a[k] + (a[j] - % maxele) * maxele; + a[k] = a[k] + (a[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { - a[k] = a[k] + (a[i] - % maxele) * maxele; + a[k] = a[k] + (a[i] % maxele) * maxele; k++; i++; } while (j <= end) { - a[k] = a[k] + (a[j] - % maxele) * maxele; + a[k] = a[k] + (a[j] % maxele) * maxele; k++; j++; } for (i = start; i <= end; i++) { a[i] = a[i] / maxele; } - } public static void main(String args[]) { diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java index 7e81a8303ef2..9d77827c4c3e 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; public class MergeSortRecursive { @@ -18,7 +18,6 @@ public void mergeSort() { } private static List merge(List arr) { - // base condition if (arr.size() <= 1) { return arr; @@ -36,7 +35,10 @@ private static List merge(List arr) { return sort(arrA, arrB); } - private static List sort(List unsortedA, List unsortedB) { + private static List sort( + List unsortedA, + List unsortedB + ) { if (unsortedA.size() <= 0 && unsortedB.size() <= 0) { return new ArrayList<>(); } @@ -52,7 +54,9 @@ private static List sort(List unsortedA, List unsorte add(unsortedA.get(0)); } }; - newAl.addAll(sort(unsortedA.subList(1, unsortedA.size()), unsortedB)); + newAl.addAll( + sort(unsortedA.subList(1, unsortedA.size()), unsortedB) + ); return newAl; } else { List newAl = new ArrayList() { @@ -60,17 +64,20 @@ private static List sort(List unsortedA, List unsorte add(unsortedB.get(0)); } }; - newAl.addAll(sort(unsortedA, unsortedB.subList(1, unsortedB.size()))); + newAl.addAll( + sort(unsortedA, unsortedB.subList(1, unsortedB.size())) + ); return newAl; } } - } class App { public static void main(String[] args) { - MergeSortRecursive sort = new MergeSortRecursive(new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9))); + MergeSortRecursive sort = new MergeSortRecursive( + new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9)) + ); sort.mergeSort(); } } diff --git a/src/main/java/com/thealgorithms/sorts/PancakeSort.java b/src/main/java/com/thealgorithms/sorts/PancakeSort.java index 1d0b76fc04c7..c5e59a0215b7 100644 --- a/src/main/java/com/thealgorithms/sorts/PancakeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PancakeSort.java @@ -29,9 +29,35 @@ public > T[] sort(T[] array) { } public static void main(String[] args) { - Integer[] arr = { - 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1 + 10, + 9, + 8, + 7, + 6, + 15, + 14, + 7, + 4, + 3, + 8, + 6, + 3, + 1, + 2, + -2, + -5, + -8, + -3, + -1, + 13, + 12, + 11, + 5, + 4, + 3, + 2, + 1, }; PancakeSort pancakeSort = new PancakeSort(); System.out.println("After sorting:"); diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java index 5025b7f6b62b..ce1aa7746b02 100644 --- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -1,42 +1,43 @@ package com.thealgorithms.sorts; -import java.util.*; import static com.thealgorithms.sorts.SortUtils.*; +import java.util.*; + public class PigeonholeSort { + /* This code implements the pigeonhole sort algorithm for the integer array, but we can also implement this for string arrays too. See https://www.geeksforgeeks.org/pigeonhole-sort/ */ - void sort(Integer[] array){ + void sort(Integer[] array) { int maxElement = array[0]; - for (int element: array) { + for (int element : array) { if (element > maxElement) maxElement = element; } int numOfPigeonholes = 1 + maxElement; - ArrayList[] pigeonHole = new ArrayList[numOfPigeonholes]; + ArrayList[] pigeonHole = new ArrayList[numOfPigeonholes]; - for (int k=0; k(); } - for (int t: array) { + for (int t : array) { pigeonHole[t].add(t); } - int k=0; - for (ArrayList ph: pigeonHole) { - for (int elements: ph) { - array[k]=elements; - k=k+1; + int k = 0; + for (ArrayList ph : pigeonHole) { + for (int elements : ph) { + array[k] = elements; + k = k + 1; } } } - public static void main(String[] args) - { + public static void main(String[] args) { PigeonholeSort pigeonholeSort = new PigeonholeSort(); Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 }; @@ -44,10 +45,10 @@ public static void main(String[] args) print(arr); pigeonholeSort.sort(arr); - + System.out.print("Sorted order is : "); for (int i = 0; i < arr.length; i++) { - assert (arr[i]) <= (arr[i+1]); + assert (arr[i]) <= (arr[i + 1]); } print(arr); } diff --git a/src/main/java/com/thealgorithms/sorts/QuickSort.java b/src/main/java/com/thealgorithms/sorts/QuickSort.java index b168677ee973..94ed869a901d 100644 --- a/src/main/java/com/thealgorithms/sorts/QuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/QuickSort.java @@ -27,7 +27,11 @@ public > T[] sort(T[] array) { * @param right The last index of an array * @param array The array to be sorted */ - private static > void doSort(T[] array, int left, int right) { + private static > void doSort( + T[] array, + int left, + int right + ) { if (left < right) { int pivot = randomPartition(array, left, right); doSort(array, left, pivot - 1); @@ -43,7 +47,11 @@ private static > void doSort(T[] array, int left, int ri * @param right The last index of an array * @return the partition index of the array */ - private static > int randomPartition(T[] array, int left, int right) { + private static > int randomPartition( + T[] array, + int left, + int right + ) { int randomIndex = left + (int) (Math.random() * (right - left + 1)); swap(array, randomIndex, right); return partition(array, left, right); @@ -57,7 +65,11 @@ private static > int randomPartition(T[] array, int left * @param right The last index of an array Finds the partition index of an * array */ - private static > int partition(T[] array, int left, int right) { + private static > int partition( + T[] array, + int left, + int right + ) { int mid = (left + right) >>> 1; T pivot = array[mid]; diff --git a/src/main/java/com/thealgorithms/sorts/RadixSort.java b/src/main/java/com/thealgorithms/sorts/RadixSort.java index 080e386a46c2..93d579142501 100644 --- a/src/main/java/com/thealgorithms/sorts/RadixSort.java +++ b/src/main/java/com/thealgorithms/sorts/RadixSort.java @@ -39,7 +39,6 @@ private static void countSort(int[] arr, int n, int exp) { } private static void radixsort(int[] arr, int n) { - int m = getMax(arr, n); for (int exp = 1; m / exp > 0; exp *= 10) { @@ -54,7 +53,7 @@ static void print(int[] arr, int n) { } public static void main(String[] args) { - int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; + int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; int n = arr.length; radixsort(arr, n); print(arr, n); diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java index e2248987259f..3c4dfe250ebb 100644 --- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java +++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java @@ -32,15 +32,14 @@ public > T[] sort(T[] arr) { * Driver Code */ public static void main(String[] args) { - - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; SelectionSort selectionSort = new SelectionSort(); Integer[] sorted = selectionSort.sort(arr); for (int i = 0; i < sorted.length - 1; ++i) { assert sorted[i] <= sorted[i + 1]; } - String[] strings = {"c", "a", "e", "b", "d"}; + String[] strings = { "c", "a", "e", "b", "d" }; String[] sortedStrings = selectionSort.sort(strings); for (int i = 0; i < sortedStrings.length - 1; ++i) { assert strings[i].compareTo(strings[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/ShellSort.java b/src/main/java/com/thealgorithms/sorts/ShellSort.java index 5f41a5440388..fe2c387fc8c1 100644 --- a/src/main/java/com/thealgorithms/sorts/ShellSort.java +++ b/src/main/java/com/thealgorithms/sorts/ShellSort.java @@ -36,7 +36,7 @@ public > T[] sort(T[] array) { /* Driver Code */ public static void main(String[] args) { - Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + Integer[] toSort = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; ShellSort sort = new ShellSort(); sort.sort(toSort); diff --git a/src/main/java/com/thealgorithms/sorts/SimpleSort.java b/src/main/java/com/thealgorithms/sorts/SimpleSort.java index 4ae7082df779..1255f3929300 100644 --- a/src/main/java/com/thealgorithms/sorts/SimpleSort.java +++ b/src/main/java/com/thealgorithms/sorts/SimpleSort.java @@ -23,7 +23,7 @@ public > T[] sort(T[] array) { public static void main(String[] args) { // ==== Int ======= - Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; + Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; System.out.print("unsorted: "); print(a); System.out.println(); @@ -34,7 +34,16 @@ public static void main(String[] args) { System.out.println(); // ==== String ======= - String[] b = {"banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"}; + String[] b = { + "banana", + "berry", + "orange", + "grape", + "peach", + "cherry", + "apple", + "pineapple", + }; System.out.print("unsorted: "); print(b); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/SlowSort.java b/src/main/java/com/thealgorithms/sorts/SlowSort.java index bce97683d496..db683fbf3e5c 100644 --- a/src/main/java/com/thealgorithms/sorts/SlowSort.java +++ b/src/main/java/com/thealgorithms/sorts/SlowSort.java @@ -30,7 +30,7 @@ private > void sort(T[] array, int i, int j) { public static void main(String[] args) { SlowSort slowSort = new SlowSort(); - Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202, 98}; + Integer[] integerArray = { 8, 84, 53, 953, 64, 2, 202, 98 }; // Print integerArray unsorted SortUtils.print(integerArray); @@ -38,7 +38,7 @@ public static void main(String[] args) { // Print integerArray sorted SortUtils.print(integerArray); - String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; + String[] stringArray = { "g", "d", "a", "b", "f", "c", "e" }; // Print stringArray unsorted SortUtils.print(stringArray); diff --git a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java index 4df4e47e4702..85886b743973 100644 --- a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java +++ b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java @@ -9,7 +9,6 @@ * @author Podshivalov Nikita (https://github.com/nikitap492) */ public interface SortAlgorithm { - /** * Main method arrays sorting algorithms * @@ -26,6 +25,8 @@ public interface SortAlgorithm { */ @SuppressWarnings("unchecked") default > List sort(List unsorted) { - return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); + return Arrays.asList( + sort(unsorted.toArray((T[]) new Comparable[unsorted.size()])) + ); } } diff --git a/src/main/java/com/thealgorithms/sorts/SortUtils.java b/src/main/java/com/thealgorithms/sorts/SortUtils.java index c3df99513e17..27774103861c 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtils.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtils.java @@ -65,7 +65,11 @@ static > boolean greaterOrEqual(T v, T w) { * @param toPrint - a list which should be printed */ static void print(List toPrint) { - toPrint.stream().map(Object::toString).map(str -> str + " ").forEach(System.out::print); + toPrint + .stream() + .map(Object::toString) + .map(str -> str + " ") + .forEach(System.out::print); System.out.println(); } diff --git a/src/main/java/com/thealgorithms/sorts/StoogeSort.java b/src/main/java/com/thealgorithms/sorts/StoogeSort.java index 330f9752d1e4..0089eaede161 100644 --- a/src/main/java/com/thealgorithms/sorts/StoogeSort.java +++ b/src/main/java/com/thealgorithms/sorts/StoogeSort.java @@ -12,7 +12,11 @@ public > T[] sort(T[] unsortedArray) { return unsortedArray; } - public > T[] sort(T[] unsortedArray, int start, int end) { + public > T[] sort( + T[] unsortedArray, + int start, + int end + ) { if (SortUtils.less(unsortedArray[end - 1], unsortedArray[start])) { T temp = unsortedArray[start]; unsortedArray[start] = unsortedArray[end - 1]; @@ -32,7 +36,7 @@ public > T[] sort(T[] unsortedArray, int start, int end) public static void main(String[] args) { StoogeSort stoogeSort = new StoogeSort(); - Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202}; + Integer[] integerArray = { 8, 84, 53, 953, 64, 2, 202 }; // Print integerArray unsorted SortUtils.print(integerArray); @@ -40,7 +44,7 @@ public static void main(String[] args) { // Print integerArray sorted SortUtils.print(integerArray); - String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; + String[] stringArray = { "g", "d", "a", "b", "f", "c", "e" }; // Print stringArray unsorted SortUtils.print(stringArray); diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 8b31f7c4ec77..3e7b02f2c896 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -1,42 +1,45 @@ package com.thealgorithms.sorts; + import java.util.Iterator; import java.util.LinkedList; - -public class StrandSort{ - // note: the input list is destroyed - public static > - LinkedList strandSort(LinkedList list){ - if(list.size() <= 1) return list; - - LinkedList result = new LinkedList(); - while(list.size() > 0){ - LinkedList sorted = new LinkedList(); - sorted.add(list.removeFirst()); //same as remove() or remove(0) - for(Iterator it = list.iterator(); it.hasNext(); ){ - E elem = it.next(); - if(sorted.peekLast().compareTo(elem) <= 0){ - sorted.addLast(elem); //same as add(elem) or add(0, elem) - it.remove(); - } - } - result = merge(sorted, result); - } - return result; - } - - private static > - LinkedList merge(LinkedList left, LinkedList right){ - LinkedList result = new LinkedList(); - while(!left.isEmpty() && !right.isEmpty()){ - //change the direction of this comparison to change the direction of the sort - if(left.peek().compareTo(right.peek()) <= 0) - result.add(left.remove()); - else - result.add(right.remove()); - } - result.addAll(left); - result.addAll(right); - return result; - } +public class StrandSort { + + // note: the input list is destroyed + public static > LinkedList strandSort( + LinkedList list + ) { + if (list.size() <= 1) return list; + + LinkedList result = new LinkedList(); + while (list.size() > 0) { + LinkedList sorted = new LinkedList(); + sorted.add(list.removeFirst()); //same as remove() or remove(0) + for (Iterator it = list.iterator(); it.hasNext();) { + E elem = it.next(); + if (sorted.peekLast().compareTo(elem) <= 0) { + sorted.addLast(elem); //same as add(elem) or add(0, elem) + it.remove(); + } + } + result = merge(sorted, result); + } + return result; + } + + private static > LinkedList merge( + LinkedList left, + LinkedList right + ) { + LinkedList result = new LinkedList(); + while (!left.isEmpty() && !right.isEmpty()) { + //change the direction of this comparison to change the direction of the sort + if (left.peek().compareTo(right.peek()) <= 0) result.add( + left.remove() + ); else result.add(right.remove()); + } + result.addAll(left); + result.addAll(right); + return result; + } } diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java index 5550f70d7bd3..718de04eeb8b 100644 --- a/src/main/java/com/thealgorithms/sorts/SwapSort.java +++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java @@ -17,7 +17,8 @@ public > T[] sort(T[] array) { int index = 0; while (index < LENGTH - 1) { - int amountSmallerElements = this.getSmallerElementCount(array, index); + int amountSmallerElements = + this.getSmallerElementCount(array, index); if (amountSmallerElements > 0 && index != amountSmallerElements) { T element = array[index]; @@ -31,7 +32,10 @@ public > T[] sort(T[] array) { return array; } - private > int getSmallerElementCount(T[] array, int index) { + private > int getSmallerElementCount( + T[] array, + int index + ) { int counter = 0; for (int i = 0; i < array.length; i++) { if (less(array[i], array[index])) { @@ -44,7 +48,7 @@ private > int getSmallerElementCount(T[] array, int inde public static void main(String[] args) { // ==== Int ======= - Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; + Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; System.out.print("unsorted: "); print(a); System.out.println(); @@ -55,7 +59,16 @@ public static void main(String[] args) { System.out.println(); // ==== String ======= - String[] b = {"banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"}; + String[] b = { + "banana", + "berry", + "orange", + "grape", + "peach", + "cherry", + "apple", + "pineapple", + }; System.out.print("unsorted: "); print(b); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/TimSort.java b/src/main/java/com/thealgorithms/sorts/TimSort.java index bd824a614193..e2961e151954 100644 --- a/src/main/java/com/thealgorithms/sorts/TimSort.java +++ b/src/main/java/com/thealgorithms/sorts/TimSort.java @@ -90,7 +90,6 @@ public void insertion_sort(int[] array, int start_idx, int end_idx) { * @param end: Ending index of the second run(chunk). */ public void merge_runs(int array[], int start, int mid, int end) { - int first_array_size = mid - start + 1, second_array_size = end - mid; int array1[] = new int[first_array_size], array2[] = new int[second_array_size]; int i = 0, j = 0, k = 0; @@ -142,13 +141,28 @@ public void algorithm() { // Applying insertion sort on RUNS. for (int i = 0; i < this.array_length; i += this.RUN) { - this.insertion_sort(this.array, i, Math.min(i + this.RUN, (this.array_length - 1))); + this.insertion_sort( + this.array, + i, + Math.min(i + this.RUN, (this.array_length - 1)) + ); } - for (int split = this.RUN; split < this.array_length; split = 2 * split) { - for (int start_idx = 0; start_idx < this.array_length; start_idx += 2 * split) { + for ( + int split = this.RUN; + split < this.array_length; + split = 2 * split + ) { + for ( + int start_idx = 0; + start_idx < this.array_length; + start_idx += 2 * split + ) { int mid = start_idx + split - 1; - int end_idx = Math.min((start_idx + 2 * split - 1), (this.array_length - 1)); + int end_idx = Math.min( + (start_idx + 2 * split - 1), + (this.array_length - 1) + ); this.merge_runs(this.array, start_idx, mid, end_idx); } @@ -173,7 +187,7 @@ public void showArrayElements() { * @brief A method to test the sorting algorithm */ static void test() { - int[] array = {4, 1, 3, 17, 12, 11, 8}; + int[] array = { 4, 1, 3, 17, 12, 11, 8 }; TimSort sorterObj1 = new TimSort(); TimSort sorterObj2 = new TimSort(50); TimSort sorterObj3 = new TimSort(array); @@ -184,17 +198,23 @@ static void test() { // Testing the first array for (int i = 0; i < sorterObj1.array_length - 1; i++) { - assert ((sorterObj1.array[i] <= sorterObj1.array[i + 1])) : "Array is not sorted"; + assert ( + (sorterObj1.array[i] <= sorterObj1.array[i + 1]) + ) : "Array is not sorted"; } // Testing the second array. for (int i = 0; i < sorterObj2.array_length - 1; i++) { - assert ((sorterObj2.array[i] <= sorterObj2.array[i + 1])) : "Array is not sorted"; + assert ( + (sorterObj2.array[i] <= sorterObj2.array[i + 1]) + ) : "Array is not sorted"; } // Testing the third array. for (int i = 0; i < sorterObj3.array_length - 1; i++) { - assert ((sorterObj3.array[i] <= sorterObj3.array[i + 1])) : "Array is not sorted"; + assert ( + (sorterObj3.array[i] <= sorterObj3.array[i + 1]) + ) : "Array is not sorted"; } } diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index 40f4b856c7c8..b72a3d77766f 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -14,54 +14,57 @@ */ public class TopologicalSort { - /* + /* * Enum to represent the colors for the depth first search * */ private enum Color { - WHITE, GRAY, BLACK + WHITE, + GRAY, + BLACK, } - /* + /* * Class to represent vertices * */ private static class Vertex { + /* - * Name of vertex - * */ + * Name of vertex + * */ public final String label; /* - * Weight of vertex - * (more accurately defined as the time that a vertex has begun a visit in DFS) - * */ + * Weight of vertex + * (more accurately defined as the time that a vertex has begun a visit in DFS) + * */ public int weight; /* - * The time that the vertex has finished a visit in DFS - * */ + * The time that the vertex has finished a visit in DFS + * */ public int finished; /* - * π parent of the vertex - * */ + * π parent of the vertex + * */ public Vertex predecessor; /* - * Represents the category of visit in DFS - * */ + * Represents the category of visit in DFS + * */ public Color color = Color.WHITE; /* - * The array of names of descendant vertices - * */ + * The array of names of descendant vertices + * */ public final ArrayList next = new ArrayList<>(); public Vertex(String label) { this.label = label; } - } + } - /* + /* * Graph class uses the adjacency list representation * */ static class Graph { @@ -76,17 +79,21 @@ static class Graph { * */ public void addEdge(String label, String... next) { adj.put(label, new Vertex(label)); - if (!next[0].isEmpty()) - Collections.addAll(adj.get(label).next, next); + if (!next[0].isEmpty()) Collections.addAll( + adj.get(label).next, + next + ); } } static class BackEdgeException extends RuntimeException { public BackEdgeException(String backEdge) { - super("This graph contains a cycle. No linear ordering is possible. " + backEdge); + super( + "This graph contains a cycle. No linear ordering is possible. " + + backEdge + ); } - } /* @@ -137,24 +144,27 @@ private static String sort(Graph graph, Vertex u, LinkedList list) { time++; u.weight = time; u.color = Color.GRAY; - graph.adj.get(u.label).next.forEach(label -> { - if (graph.adj.get(label).color == Color.WHITE) { - graph.adj.get(label).predecessor = u; - list.addFirst(sort(graph, graph.adj.get(label), list)); - } else if (graph.adj.get(label).color == Color.GRAY) { - /* - * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v - * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f - * - * In many cases, we will not know u.f, but v.color denotes the type of edge - * */ - throw new BackEdgeException("Back edge: " + u.label + " -> " + label); - } - }); + graph.adj + .get(u.label) + .next.forEach(label -> { + if (graph.adj.get(label).color == Color.WHITE) { + graph.adj.get(label).predecessor = u; + list.addFirst(sort(graph, graph.adj.get(label), list)); + } else if (graph.adj.get(label).color == Color.GRAY) { + /* + * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v + * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f + * + * In many cases, we will not know u.f, but v.color denotes the type of edge + * */ + throw new BackEdgeException( + "Back edge: " + u.label + " -> " + label + ); + } + }); u.color = Color.BLACK; time++; u.finished = time; return u.label; } } - diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index 664585833a01..ca9d4c80c85e 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -1,8 +1,8 @@ package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.print; -import com.thealgorithms.datastructures.trees.BSTRecursiveGeneric; +import com.thealgorithms.datastructures.trees.BSTRecursiveGeneric; import java.util.List; /** @@ -51,7 +51,9 @@ private > T[] doTreeSortArray(T[] unsortedArray) { return unsortedArray; } - private > List doTreeSortList(List unsortedList) { + private > List doTreeSortList( + List unsortedList + ) { // create a generic BST tree BSTRecursiveGeneric tree = new BSTRecursiveGeneric(); @@ -69,7 +71,7 @@ public static void main(String[] args) { // ==== Integer Array ======= System.out.println("Testing for Integer Array...."); - Integer[] a = {3, -7, 45, 1, 343, -5, 2, 9}; + Integer[] a = { 3, -7, 45, 1, 343, -5, 2, 9 }; System.out.print(String.format("%-10s", "unsorted: ")); print(a); a = treeSort.sort(a); @@ -89,7 +91,16 @@ public static void main(String[] args) { // ==== String Array ======= System.out.println("Testing for String Array...."); - String[] b = {"banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"}; + String[] b = { + "banana", + "berry", + "orange", + "grape", + "peach", + "cherry", + "apple", + "pineapple", + }; System.out.print(String.format("%-10s", "unsorted: ")); print(b); b = treeSort.sort(b); @@ -99,13 +110,20 @@ public static void main(String[] args) { // ==== String List ======= System.out.println("Testing for String List...."); - List stringList = List.of("banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"); + List stringList = List.of( + "banana", + "berry", + "orange", + "grape", + "peach", + "cherry", + "apple", + "pineapple" + ); System.out.print(String.format("%-10s", "unsorted: ")); print(stringList); stringList = treeSort.sort(stringList); System.out.print(String.format("%-10s", "sorted: ")); print(stringList); - } - } diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java index b368c74422a9..c69fcdbe91ed 100644 --- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java +++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java @@ -1,11 +1,11 @@ package com.thealgorithms.sorts; -import java.util.Arrays; - import static com.thealgorithms.maths.Ceil.ceil; import static com.thealgorithms.maths.Floor.floor; import static com.thealgorithms.searches.QuickSelect.select; +import java.util.Arrays; + /** * A wiggle sort implementation based on John L.s' answer in * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity @@ -14,6 +14,7 @@ * but there are some exceptions that won't be caught, for example [1, 2, 2]. */ public class WiggleSort implements SortAlgorithm { + @Override public > T[] sort(T[] unsorted) { return wiggleSort(unsorted); @@ -30,7 +31,10 @@ private int mapIndex(int index, int n) { * @param median defines the groups * @param extends interface Comparable */ - private > void triColorSort(T[] sortThis, T median) { + private > void triColorSort( + T[] sortThis, + T median + ) { int n = sortThis.length; int i = 0; int j = 0; @@ -53,7 +57,11 @@ private > T[] wiggleSort(T[] sortThis) { // find the median using quickSelect (if the result isn't in the array, use the next greater value) T median; - median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0)); + median = + select( + Arrays.asList(sortThis), + (int) floor(sortThis.length / 2.0) + ); int numMedians = 0; @@ -64,19 +72,25 @@ private > T[] wiggleSort(T[] sortThis) { } // added condition preventing off-by-one errors for odd arrays. // https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1 - if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) { + if ( + sortThis.length % 2 == 1 && + numMedians == ceil(sortThis.length / 2.0) + ) { T smallestValue = select(Arrays.asList(sortThis), 0); if (!(0 == smallestValue.compareTo(median))) { - throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, " + - "the median has to be the smallest values in the array."); + throw new IllegalArgumentException( + "For odd Arrays if the median appears ceil(n/2) times, " + + "the median has to be the smallest values in the array." + ); } } if (numMedians > ceil(sortThis.length / 2.0)) { - throw new IllegalArgumentException("No more than half the number of values may be the same."); - + throw new IllegalArgumentException( + "No more than half the number of values may be the same." + ); } triColorSort(sortThis, median); return sortThis; } -} \ No newline at end of file +} diff --git a/src/main/java/com/thealgorithms/strings/Alphabetical.java b/src/main/java/com/thealgorithms/strings/Alphabetical.java index fde17c883917..09d533eaad1a 100644 --- a/src/main/java/com/thealgorithms/strings/Alphabetical.java +++ b/src/main/java/com/thealgorithms/strings/Alphabetical.java @@ -25,7 +25,10 @@ public static void main(String[] args) { public static boolean isAlphabetical(String s) { s = s.toLowerCase(); for (int i = 0; i < s.length() - 1; ++i) { - if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { + if ( + !Character.isLetter(s.charAt(i)) || + !(s.charAt(i) <= s.charAt(i + 1)) + ) { return false; } } diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 7ab6b1277624..6ac104426271 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.HashMap; - /** * An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, * typically using all the original letters exactly once.[1] @@ -12,17 +11,25 @@ * Reference from https://en.wikipedia.org/wiki/Anagram */ public class Anagrams { + // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time. public static void main(String[] args) { String first = "deal"; String second = "lead"; // All the below methods takes input but doesn't return any output to the main method. Anagrams nm = new Anagrams(); - System.out.println(nm.approach2(first, second)); /* To activate methods for different approaches*/ - System.out.println(nm.approach1(first, second)); /* To activate methods for different approaches*/ - System.out.println(nm.approach3(first, second)); /* To activate methods for different approaches*/ - System.out.println(nm.approach4(first, second)); /* To activate methods for different approaches*/ - + System.out.println( + nm.approach2(first, second) + );/* To activate methods for different approaches*/ + System.out.println( + nm.approach1(first, second) + );/* To activate methods for different approaches*/ + System.out.println( + nm.approach3(first, second) + );/* To activate methods for different approaches*/ + System.out.println( + nm.approach4(first, second) + );/* To activate methods for different approaches*/ /** * OUTPUT : * first string ="deal" second string ="lead" @@ -46,7 +53,9 @@ boolean approach1(String s, String t) { char c[] = s.toCharArray(); char d[] = t.toCharArray(); Arrays.sort(c); - Arrays.sort(d); /* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */ + Arrays.sort( + d + );/* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */ if (Arrays.equals(c, d)) { return true; } else { @@ -92,8 +101,7 @@ boolean approach3(String s, String t) { b[t.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { - if (a[i] != b[i]) - return false; + if (a[i] != b[i]) return false; } return true; } @@ -111,7 +119,6 @@ boolean approach4(String s, String t) { nm.put(c, nm.getOrDefault(c, 0) + 1); } for (char c : t.toCharArray()) { - kk.put(c, kk.getOrDefault(c, 0) + 1); } // It checks for equal frequencies diff --git a/src/main/java/com/thealgorithms/strings/CheckVowels.java b/src/main/java/com/thealgorithms/strings/CheckVowels.java index af95f5945582..bd6861785fdd 100644 --- a/src/main/java/com/thealgorithms/strings/CheckVowels.java +++ b/src/main/java/com/thealgorithms/strings/CheckVowels.java @@ -10,7 +10,10 @@ * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order */ public class CheckVowels { - private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); + + private static final Set VOWELS = new HashSet<>( + Arrays.asList('a', 'e', 'i', 'o', 'u') + ); /** * Check if a string is has vowels or not diff --git a/src/main/java/com/thealgorithms/strings/HammingDistance.java b/src/main/java/com/thealgorithms/strings/HammingDistance.java index e85dca88cad2..a6f6db19475c 100644 --- a/src/main/java/com/thealgorithms/strings/HammingDistance.java +++ b/src/main/java/com/thealgorithms/strings/HammingDistance.java @@ -14,14 +14,15 @@ public class HammingDistance { * @return {@code int} hamming distance * @throws Exception */ - public static int calculateHammingDistance(String s1, String s2) throws Exception { + public static int calculateHammingDistance(String s1, String s2) + throws Exception { if (s1.length() != s2.length()) { throw new Exception("String lengths must be equal"); } - + int stringLength = s1.length(); int counter = 0; - + for (int i = 0; i < stringLength; i++) { if (s1.charAt(i) != s2.charAt(i)) { counter++; diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index d886c9f47ae5..cc35dbbbf26f 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -92,22 +92,26 @@ public static Integer getLastComparisons() { * @param text text String * @return index of first occurrence of the pattern in the text */ - private static int firstOccurrence(String pattern, String text, boolean caseSensitive) { + private static int firstOccurrence( + String pattern, + String text, + boolean caseSensitive + ) { shiftValues = calcShiftValues(pattern); // build the bad symbol table comparisons = 0; // reset comparisons - int textIndex - = pattern.length() - 1; // align pattern with text start and get index of the last character + int textIndex = pattern.length() - 1; // align pattern with text start and get index of the last character // while pattern is not out of text bounds while (textIndex < text.length()) { - // try to match pattern with current part of the text starting from last character int i = pattern.length() - 1; while (i >= 0) { comparisons++; char patternChar = pattern.charAt(i); - char textChar = text.charAt((textIndex + i) - (pattern.length() - 1)); + char textChar = text.charAt( + (textIndex + i) - (pattern.length() - 1) + ); if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern textIndex += getShiftValue(text.charAt(textIndex)); break; @@ -155,9 +159,7 @@ private static HashMap calcShiftValues(String pattern) { patternLength = pattern.length(); HashMap table = new HashMap<>(); - for (int i = pattern.length() - 2; - i >= 0; - i--) { // length - 2 is the index of the second to last character + for (int i = pattern.length() - 2; i >= 0; i--) { // length - 2 is the index of the second to last character char c = pattern.charAt(i); int finalI = i; table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI); diff --git a/src/main/java/com/thealgorithms/strings/Isomorphic.java b/src/main/java/com/thealgorithms/strings/Isomorphic.java index 661aee46e697..7a355dcafa06 100644 --- a/src/main/java/com/thealgorithms/strings/Isomorphic.java +++ b/src/main/java/com/thealgorithms/strings/Isomorphic.java @@ -1,33 +1,34 @@ package com.thealgorithms.strings; + import java.util.*; public class Isomorphic { - public static boolean checkStrings(String s, String t) { - if(s.length() != t.length()){ - return false; - } - // To mark the characters of string using MAP - // character of first string as KEY and another as VALUE - // now check occurence by keeping the track with SET data structure - Map characterMap = new HashMap(); - Set trackUinqueCharacter = new HashSet(); - - for(int i=0; i characterMap = new HashMap(); + Set trackUinqueCharacter = new HashSet(); + + for (int i = 0; i < s.length(); i++) { + if (characterMap.containsKey(s.charAt(i))) { + if (t.charAt(i) != characterMap.get(s.charAt(i))) { + return false; + } + } else { + if (trackUinqueCharacter.contains(t.charAt(i))) { + return false; + } + + characterMap.put(s.charAt(i), t.charAt(i)); } - - characterMap.put(s.charAt(i), t.charAt(i)); + trackUinqueCharacter.add(t.charAt(i)); } - trackUinqueCharacter.add(t.charAt(i)); + return true; } - return true; - } } diff --git a/src/main/java/com/thealgorithms/strings/List_all_Possible_Words_From_Phone_Digits.java b/src/main/java/com/thealgorithms/strings/List_all_Possible_Words_From_Phone_Digits.java index 4677fd84885e..7cb3b4aacf5a 100644 --- a/src/main/java/com/thealgorithms/strings/List_all_Possible_Words_From_Phone_Digits.java +++ b/src/main/java/com/thealgorithms/strings/List_all_Possible_Words_From_Phone_Digits.java @@ -6,53 +6,50 @@ public class List_all_Possible_Words_From_Phone_Digits { static Character[][] numberToCharMap; - private static List printWords(int[] numbers, - int len, - int numIndex, - String s) { + private static List printWords( + int[] numbers, + int len, + int numIndex, + String s + ) { if (len == numIndex) { return new ArrayList<>(Collections.singleton(s)); } List stringList = new ArrayList<>(); - for (int i = 0; - i < numberToCharMap[numbers[numIndex]].length; i++) { - String sCopy - = String.copyValueOf(s.toCharArray()); - sCopy = sCopy.concat( - numberToCharMap[numbers[numIndex]][i].toString()); - stringList.addAll(printWords(numbers, len, - numIndex + 1, - sCopy)); + for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) { + String sCopy = String.copyValueOf(s.toCharArray()); + sCopy = + sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString()); + stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy)); } return stringList; } private static void printWords(int[] numbers) { generateNumberToCharMap(); - List stringList - = printWords(numbers, numbers.length, 0, ""); + List stringList = printWords(numbers, numbers.length, 0, ""); stringList.stream().forEach(System.out::println); } private static void generateNumberToCharMap() { numberToCharMap = new Character[10][5]; - numberToCharMap[0] = new Character[]{'\0'}; - numberToCharMap[1] = new Character[]{'\0'}; - numberToCharMap[2] = new Character[]{'a', 'b', 'c'}; - numberToCharMap[3] = new Character[]{'d', 'e', 'f'}; - numberToCharMap[4] = new Character[]{'g', 'h', 'i'}; - numberToCharMap[5] = new Character[]{'j', 'k', 'l'}; - numberToCharMap[6] = new Character[]{'m', 'n', 'o'}; - numberToCharMap[7] = new Character[]{'p', 'q', 'r', 's'}; - numberToCharMap[8] = new Character[]{'t', 'u', 'v'}; - numberToCharMap[9] = new Character[]{'w', 'x', 'y', 'z'}; + numberToCharMap[0] = new Character[] { '\0' }; + numberToCharMap[1] = new Character[] { '\0' }; + numberToCharMap[2] = new Character[] { 'a', 'b', 'c' }; + numberToCharMap[3] = new Character[] { 'd', 'e', 'f' }; + numberToCharMap[4] = new Character[] { 'g', 'h', 'i' }; + numberToCharMap[5] = new Character[] { 'j', 'k', 'l' }; + numberToCharMap[6] = new Character[] { 'm', 'n', 'o' }; + numberToCharMap[7] = new Character[] { 'p', 'q', 'r', 's' }; + numberToCharMap[8] = new Character[] { 't', 'u', 'v' }; + numberToCharMap[9] = new Character[] { 'w', 'x', 'y', 'z' }; } -// Driver code + // Driver code public static void main(String[] args) { - int number[] = {2, 3, 4}; + int number[] = { 2, 3, 4 }; printWords(number); } } diff --git a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java index ddfa5b8c4bcc..e2c7d9078ab4 100644 --- a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java @@ -11,7 +11,9 @@ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the string: "); str = sc.nextLine(); - System.out.println("Longest substring is : " + s.longestPalindrome(str)); + System.out.println( + "Longest substring is : " + s.longestPalindrome(str) + ); } } diff --git a/src/main/java/com/thealgorithms/strings/Lower.java b/src/main/java/com/thealgorithms/strings/Lower.java index ef3902b15df3..c5288d1a0a2b 100644 --- a/src/main/java/com/thealgorithms/strings/Lower.java +++ b/src/main/java/com/thealgorithms/strings/Lower.java @@ -6,7 +6,7 @@ public class Lower { * Driver Code */ public static void main(String[] args) { - String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; + String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; for (String s : strings) { assert toLowerCase(s).equals(s.toLowerCase()); } @@ -21,7 +21,10 @@ public static void main(String[] args) { public static String toLowerCase(String s) { char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { - if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { + if ( + Character.isLetter(values[i]) && + Character.isUpperCase(values[i]) + ) { values[i] = Character.toLowerCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/Palindrome.java b/src/main/java/com/thealgorithms/strings/Palindrome.java index 839a1a2aafca..30a7e08deb0a 100644 --- a/src/main/java/com/thealgorithms/strings/Palindrome.java +++ b/src/main/java/com/thealgorithms/strings/Palindrome.java @@ -9,14 +9,18 @@ class Palindrome { * Driver Code */ public static void main(String[] args) { - String[] palindromes = {null, "", "aba", "123321"}; + String[] palindromes = { null, "", "aba", "123321" }; for (String s : palindromes) { - assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s); + assert isPalindrome(s) && + isPalindromeRecursion(s) && + isPalindrome1(s); } - String[] notPalindromes = {"abb", "abc", "abc123"}; + String[] notPalindromes = { "abb", "abc", "abc123" }; for (String s : notPalindromes) { - assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s); + assert !isPalindrome(s) && + !isPalindromeRecursion(s) && + !isPalindrome1(s); } } @@ -28,7 +32,10 @@ public static void main(String[] args) { * {@code false} */ public static boolean isPalindrome(String s) { - return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString()); + return ( + (s == null || s.length() <= 1) || + s.equals(new StringBuilder(s).reverse().toString()) + ); } /** diff --git a/src/main/java/com/thealgorithms/strings/PermuteString.java b/src/main/java/com/thealgorithms/strings/PermuteString.java index 1239ab3dbf28..b7705c9bc77e 100644 --- a/src/main/java/com/thealgorithms/strings/PermuteString.java +++ b/src/main/java/com/thealgorithms/strings/PermuteString.java @@ -13,7 +13,7 @@ */ public class PermuteString { - //Function for swapping the characters at position I with character at position j + //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b = a.toCharArray(); char ch; @@ -30,18 +30,18 @@ public static void main(String[] args) { generatePermutation(str, 0, len); } - //Function for generating different permutations of the string + //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { - //Prints the permutations + //Prints the permutations if (start == end - 1) { System.out.println(str); } else { for (int i = start; i < end; i++) { - //Swapping the string by fixing a character + //Swapping the string by fixing a character str = swapString(str, start, i); - //Recursively calling function generatePermutation() for rest of the characters + //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str, start + 1, end); - //Backtracking and swapping the characters again. + //Backtracking and swapping the characters again. str = swapString(str, start, i); } } diff --git a/src/main/java/com/thealgorithms/strings/ReverseString.java b/src/main/java/com/thealgorithms/strings/ReverseString.java index 155316f62ae5..c5f54f745470 100644 --- a/src/main/java/com/thealgorithms/strings/ReverseString.java +++ b/src/main/java/com/thealgorithms/strings/ReverseString.java @@ -27,7 +27,6 @@ public static String reverse(String str) { * @return reversed string */ public static String reverse2(String str) { - if (str == null || str.isEmpty()) { return str; } diff --git a/src/main/java/com/thealgorithms/strings/Upper.java b/src/main/java/com/thealgorithms/strings/Upper.java index 8f306a20e8f0..35558462d9cb 100644 --- a/src/main/java/com/thealgorithms/strings/Upper.java +++ b/src/main/java/com/thealgorithms/strings/Upper.java @@ -6,7 +6,7 @@ public class Upper { * Driver Code */ public static void main(String[] args) { - String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; + String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; for (String s : strings) { assert toUpperCase(s).equals(s.toUpperCase()); } @@ -24,7 +24,10 @@ public static String toUpperCase(String s) { } char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { - if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { + if ( + Character.isLetter(values[i]) && + Character.isLowerCase(values[i]) + ) { values[i] = Character.toUpperCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java index c98f26efd7df..c8c5fd7345c0 100644 --- a/src/main/java/com/thealgorithms/strings/WordLadder.java +++ b/src/main/java/com/thealgorithms/strings/WordLadder.java @@ -1,10 +1,10 @@ package com.thealgorithms.strings; -import java.util.List; import java.util.Arrays; +import java.util.HashSet; import java.util.LinkedList; +import java.util.List; import java.util.Queue; -import java.util.HashSet; /* **Problem Statement:** @@ -40,13 +40,14 @@ class WordLadder { * Driver Code */ public static void main(String[] args) { - String beginWord = "hit"; String endWord = "cog"; - String words[] = {"hot", "dot", "dog", "lot", "log", "cog"}; + String words[] = { "hot", "dot", "dog", "lot", "log", "cog" }; List wordList = Arrays.asList(words); - System.out.println("Ladder Length: " + ladderLength(beginWord, endWord, wordList)); + System.out.println( + "Ladder Length: " + ladderLength(beginWord, endWord, wordList) + ); } /** @@ -59,7 +60,11 @@ public static void main(String[] args) { * @return ladderLength: This function will return the ladderLength(level) * if the endword is there. Otherwise, will return the length as 0. */ - public static int ladderLength(String beginWord, String endWord, List wordList) { + public static int ladderLength( + String beginWord, + String endWord, + List wordList + ) { HashSet set = new HashSet(); for (String word : wordList) { set.add(word); diff --git a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java index 8cb456ae5538..7549dd2a7a0b 100644 --- a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java +++ b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java @@ -1,47 +1,40 @@ -package com.thealgorithms.strings ; -import java.util.HashMap ; +package com.thealgorithms.strings; + +import java.util.HashMap; + class longestNonRepeativeSubstring { public static int lengthOfLongestSubstring(String s) { - - int max = 0 , start = 0 , i = 0 ; - HashMap< Character , Integer > map = new HashMap<>() ; - - while ( i < s.length() ) { + int max = 0, start = 0, i = 0; + HashMap map = new HashMap<>(); - char temp = s.charAt( i ) ; + while (i < s.length()) { + char temp = s.charAt(i); // adding key to map if not present - if ( ! map.containsKey( temp ) ) - map.put( temp , 0 ) ; - + if (!map.containsKey(temp)) map.put(temp, 0); // checking if the first value is the dublicate value - else if ( s.charAt( start ) == temp ) - start++ ; - + else if (s.charAt(start) == temp) start++; // checking if the previous value is dublicate value - else if ( s.charAt( i - 1 ) == temp ) { - if ( max < map.size() ) max = map.size() ; - map = new HashMap<>() ; - start = i ; - i-- ; + else if (s.charAt(i - 1) == temp) { + if (max < map.size()) max = map.size(); + map = new HashMap<>(); + start = i; + i--; } - // last possible place where dublicate value can be is between start and i else { - if ( max < map.size() ) max = map.size() ; - while ( s.charAt( start ) != temp ) { - map.remove( s.charAt( start ) ) ; - start++ ; + if (max < map.size()) max = map.size(); + while (s.charAt(start) != temp) { + map.remove(s.charAt(start)); + start++; } - start++ ; + start++; } - i++ ; - + i++; } - if ( max < map.size() ) max = map.size() ; - return max ; + if (max < map.size()) max = map.size(); + return max; } - } diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java index e0e019706de8..a1d6761415e2 100644 --- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java +++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java @@ -1,30 +1,31 @@ package com.thealgorithms.strings.zigZagPattern; + class zigZagPattern { public static String encode(String s, int numRows) { - if ( numRows < 2 || s.length() < numRows ) return s ; - int start = 0 , index = 0 , height = 1 , depth = numRows ; - char[] zigZagedArray = new char[ s.length() ] ; - while ( depth != 0 ) { - int pointer = start , height_space = 2 + ( ( height - 2 ) * 2 ) , depth_space = 2 + ( ( depth - 2 ) * 2 ) ; - boolean bool = true ; - while ( pointer < s.length() ) { - zigZagedArray[index++] = s.charAt( pointer ) ; - if ( height_space == 0 ) pointer += depth_space ; - else if ( depth_space == 0 ) pointer += height_space ; - else if ( bool ) { - pointer += depth_space ; - bool = false ; + if (numRows < 2 || s.length() < numRows) return s; + int start = 0, index = 0, height = 1, depth = numRows; + char[] zigZagedArray = new char[s.length()]; + while (depth != 0) { + int pointer = start, height_space = + 2 + ((height - 2) * 2), depth_space = 2 + ((depth - 2) * 2); + boolean bool = true; + while (pointer < s.length()) { + zigZagedArray[index++] = s.charAt(pointer); + if (height_space == 0) pointer += depth_space; else if ( + depth_space == 0 + ) pointer += height_space; else if (bool) { + pointer += depth_space; + bool = false; } else { - pointer += height_space ; - bool = true ; + pointer += height_space; + bool = true; } } - height++ ; - depth-- ; - start++ ; + height++; + depth--; + start++; } - return new String( zigZagedArray ) ; + return new String(zigZagedArray); } - -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java index 19f7b10ae233..418383c8ce7b 100644 --- a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java @@ -1,30 +1,38 @@ package com.thealgorithms.backtracking; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.TreeSet; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class CombinationTest { + @Test - void testNoElement() - { - List> result = Combination.combination(new Integer[]{1, 2}, 0); + void testNoElement() { + List> result = Combination.combination( + new Integer[] { 1, 2 }, + 0 + ); assertTrue(result == null); } + @Test - void testLengthOne() - { - List> result = Combination.combination(new Integer[]{1, 2}, 1); + void testLengthOne() { + List> result = Combination.combination( + new Integer[] { 1, 2 }, + 1 + ); assertTrue(result.get(0).iterator().next() == 1); assertTrue(result.get(1).iterator().next() == 2); } + @Test - void testLengthTwo() - { - List> result = Combination.combination(new Integer[]{1, 2}, 2); + void testLengthTwo() { + List> result = Combination.combination( + new Integer[] { 1, 2 }, + 2 + ); Integer[] arr = result.get(0).toArray(new Integer[2]); assertTrue(arr[0] == 1); assertTrue(arr[1] == 2); diff --git a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java index 7b72e6b2f12d..437ddb2333a8 100644 --- a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java +++ b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java @@ -1,14 +1,13 @@ package com.thealgorithms.backtracking; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import org.junit.jupiter.api.Test; + class FloodFillTest { @Test - void testForEmptyImage() - { + void testForEmptyImage() { int image[][] = {}; int expected[][] = {}; @@ -16,91 +15,82 @@ void testForEmptyImage() assertArrayEquals(expected, image); } - @Test - void testForSingleElementImage() - { - int image[][] = {{1}}; - int expected[][] = {{3}}; + void testForSingleElementImage() { + int image[][] = { { 1 } }; + int expected[][] = { { 3 } }; FloodFill.floodFill(image, 0, 0, 3, 1); assertArrayEquals(expected, image); } - @Test - void testForImageOne() - { + void testForImageOne() { int image[][] = { - { 0,0,0,0,0,0,0 }, - { 0,3,3,3,3,0,0 }, - { 0,3,1,1,5,0,0 }, - { 0,3,1,1,5,5,3 }, - { 0,3,5,5,1,1,3 }, - { 0,0,0,5,1,1,3 }, - { 0,0,0,3,3,3,3 } + { 0, 0, 0, 0, 0, 0, 0 }, + { 0, 3, 3, 3, 3, 0, 0 }, + { 0, 3, 1, 1, 5, 0, 0 }, + { 0, 3, 1, 1, 5, 5, 3 }, + { 0, 3, 5, 5, 1, 1, 3 }, + { 0, 0, 0, 5, 1, 1, 3 }, + { 0, 0, 0, 3, 3, 3, 3 }, }; int expected[][] = { - { 0,0,0,0,0,0,0 }, - { 0,3,3,3,3,0,0 }, - { 0,3,2,2,5,0,0 }, - { 0,3,2,2,5,5,3 }, - { 0,3,5,5,2,2,3 }, - { 0,0,0,5,2,2,3 }, - { 0,0,0,3,3,3,3 } + { 0, 0, 0, 0, 0, 0, 0 }, + { 0, 3, 3, 3, 3, 0, 0 }, + { 0, 3, 2, 2, 5, 0, 0 }, + { 0, 3, 2, 2, 5, 5, 3 }, + { 0, 3, 5, 5, 2, 2, 3 }, + { 0, 0, 0, 5, 2, 2, 3 }, + { 0, 0, 0, 3, 3, 3, 3 }, }; - FloodFill.floodFill(image,2,2,2,1); + FloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } - @Test - void testForImageTwo() - { + void testForImageTwo() { int image[][] = { - { 0,0,1,1,0,0,0 }, - { 1,1,3,3,3,0,0 }, - { 1,3,1,1,5,0,0 }, - { 0,3,1,1,5,5,3 }, - { 0,3,5,5,1,1,3 }, - { 0,0,0,5,1,1,3 }, - { 0,0,0,1,3,1,3 } + { 0, 0, 1, 1, 0, 0, 0 }, + { 1, 1, 3, 3, 3, 0, 0 }, + { 1, 3, 1, 1, 5, 0, 0 }, + { 0, 3, 1, 1, 5, 5, 3 }, + { 0, 3, 5, 5, 1, 1, 3 }, + { 0, 0, 0, 5, 1, 1, 3 }, + { 0, 0, 0, 1, 3, 1, 3 }, }; int expected[][] = { - { 0,0,2,2,0,0,0 }, - { 2,2,3,3,3,0,0 }, - { 2,3,2,2,5,0,0 }, - { 0,3,2,2,5,5,3 }, - { 0,3,5,5,2,2,3 }, - { 0,0,0,5,2,2,3 }, - { 0,0,0,2,3,2,3 } + { 0, 0, 2, 2, 0, 0, 0 }, + { 2, 2, 3, 3, 3, 0, 0 }, + { 2, 3, 2, 2, 5, 0, 0 }, + { 0, 3, 2, 2, 5, 5, 3 }, + { 0, 3, 5, 5, 2, 2, 3 }, + { 0, 0, 0, 5, 2, 2, 3 }, + { 0, 0, 0, 2, 3, 2, 3 }, }; FloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } - @Test - void testForImageThree() - { + void testForImageThree() { int image[][] = { - { 1,1,2,3,1,1,1 }, - { 1,0,0,1,0,0,1 }, - { 1,1,1,0,3,1,2 } + { 1, 1, 2, 3, 1, 1, 1 }, + { 1, 0, 0, 1, 0, 0, 1 }, + { 1, 1, 1, 0, 3, 1, 2 }, }; int expected[][] = { - { 4,4,2,3,4,4,4 }, - { 4,0,0,4,0,0,4 }, - { 4,4,4,0,3,4,2 }, + { 4, 4, 2, 3, 4, 4, 4 }, + { 4, 0, 0, 4, 0, 0, 4 }, + { 4, 4, 4, 0, 3, 4, 2 }, }; FloodFill.floodFill(image, 0, 1, 4, 1); assertArrayEquals(expected, image); } - -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java index a6beb20911be..97dc4d1b8e42 100644 --- a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java @@ -1,8 +1,9 @@ package com.thealgorithms.backtracking; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + /** * @author onglipwei * @create 2022-08-03 5:17 AM @@ -11,8 +12,6 @@ public class MazeRecursionTest { @Test public void testMaze() { - - // First create a 2 dimensions array to mimic a maze map int[][] map = new int[8][7]; int[][] map2 = new int[8][7]; @@ -28,7 +27,6 @@ public void testMaze() { for (int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; - } // Now we have created a maze with its wall initialized @@ -38,41 +36,38 @@ public void testMaze() { map[3][2] = 1; //clone another map for setWay2 method - for (int i = 0; i < map.length;i++) { - for (int j = 0; j < map[i].length;j++) { - map2[i][j]=map[i][j]; + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[i].length; j++) { + map2[i][j] = map[i][j]; } } MazeRecursion.setWay(map, 1, 1); MazeRecursion.setWay2(map2, 1, 1); - - int expectedMap[][] = new int[][]{ - {1,1,1,1,1,1,1}, - {1,2,0,0,0,0,1}, - {1,2,2,2,0,0,1}, - {1,1,1,2,0,0,1}, - {1,0,0,2,0,0,1}, - {1,0,0,2,0,0,1}, - {1,0,0,2,2,2,1}, - {1,1,1,1,1,1,1} + int expectedMap[][] = new int[][] { + { 1, 1, 1, 1, 1, 1, 1 }, + { 1, 2, 0, 0, 0, 0, 1 }, + { 1, 2, 2, 2, 0, 0, 1 }, + { 1, 1, 1, 2, 0, 0, 1 }, + { 1, 0, 0, 2, 0, 0, 1 }, + { 1, 0, 0, 2, 0, 0, 1 }, + { 1, 0, 0, 2, 2, 2, 1 }, + { 1, 1, 1, 1, 1, 1, 1 }, }; - int expectedMap2[][] = new int[][]{ - {1,1,1,1,1,1,1}, - {1,2,2,2,2,2,1}, - {1,0,0,0,0,2,1}, - {1,1,1,0,0,2,1}, - {1,0,0,0,0,2,1}, - {1,0,0,0,0,2,1}, - {1,0,0,0,0,2,1}, - {1,1,1,1,1,1,1} + int expectedMap2[][] = new int[][] { + { 1, 1, 1, 1, 1, 1, 1 }, + { 1, 2, 2, 2, 2, 2, 1 }, + { 1, 0, 0, 0, 0, 2, 1 }, + { 1, 1, 1, 0, 0, 2, 1 }, + { 1, 0, 0, 0, 0, 2, 1 }, + { 1, 0, 0, 0, 0, 2, 1 }, + { 1, 0, 0, 0, 0, 2, 1 }, + { 1, 1, 1, 1, 1, 1, 1 }, }; assertArrayEquals(map, expectedMap); assertArrayEquals(map2, expectedMap2); - } - } diff --git a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java index 60916b3e6611..3d865da1b8ae 100644 --- a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java @@ -1,32 +1,31 @@ package com.thealgorithms.backtracking; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class PermutationTest { + @Test - void testNoElement() - { - List result = Permutation.permutation(new Integer[]{}); + void testNoElement() { + List result = Permutation.permutation(new Integer[] {}); assertEquals(result.get(0).length, 0); } + @Test - void testSingleElement() - { - List result = Permutation.permutation(new Integer[]{1}); + void testSingleElement() { + List result = Permutation.permutation(new Integer[] { 1 }); assertEquals(result.get(0)[0], 1); } + @Test - void testMultipleElements() - { - List result = Permutation.permutation(new Integer[]{1, 2}); - assertTrue(Arrays.equals(result.get(0), new Integer[]{1,2})); - assertTrue(Arrays.equals(result.get(1), new Integer[]{2,1})); + void testMultipleElements() { + List result = Permutation.permutation( + new Integer[] { 1, 2 } + ); + assertTrue(Arrays.equals(result.get(0), new Integer[] { 1, 2 })); + assertTrue(Arrays.equals(result.get(1), new Integer[] { 2, 1 })); } - - } diff --git a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java index 6af37f18bb4b..984457e3d921 100644 --- a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java +++ b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java @@ -6,38 +6,33 @@ class BlowfishTest { - Blowfish blowfish = new Blowfish(); - - @Test - void testEncrypt() { - - //given - String plainText = "123456abcd132536"; - String key = "aabb09182736ccdd"; - String expectedOutput = "d748ec383d3405f7"; - - //when - String cipherText = blowfish.encrypt(plainText, key); - - //then - assertEquals(expectedOutput, cipherText); - - } - - @Test - void testDecrypt() { - - //given - String cipherText = "d748ec383d3405f7"; - String key = "aabb09182736ccdd"; - String expectedOutput = "123456abcd132536"; - - //when - String plainText = blowfish.decrypt(cipherText, key); - - //then - assertEquals(expectedOutput, plainText); - - } - + Blowfish blowfish = new Blowfish(); + + @Test + void testEncrypt() { + //given + String plainText = "123456abcd132536"; + String key = "aabb09182736ccdd"; + String expectedOutput = "d748ec383d3405f7"; + + //when + String cipherText = blowfish.encrypt(plainText, key); + + //then + assertEquals(expectedOutput, cipherText); + } + + @Test + void testDecrypt() { + //given + String cipherText = "d748ec383d3405f7"; + String key = "aabb09182736ccdd"; + String expectedOutput = "123456abcd132536"; + + //when + String plainText = blowfish.decrypt(cipherText, key); + + //then + assertEquals(expectedOutput, plainText); + } } diff --git a/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java b/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java index c54adab63aca..543a2fe59685 100644 --- a/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java +++ b/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class PolybiusTest { @Test diff --git a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java index 5c1d0314aa8f..0ad4c9fb2974 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java @@ -1,87 +1,96 @@ package com.thealgorithms.ciphers.a5; -import org.junit.jupiter.api.Test; - -import java.util.BitSet; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import java.util.BitSet; +import org.junit.jupiter.api.Test; + // Basic tests for sanity check class LFSRTest { + // Represents 0100 1110 0010 1111 0100 1101 0111 1100 0001 1110 1011 1000 1000 1011 0011 1010 // But we start reverse way because bitset starts from most right (1010) - byte[] sessionKeyBytes = { 58, (byte) 139, (byte) 184, 30, 124, 77, 47, 78 }; + byte[] sessionKeyBytes = { + 58, + (byte) 139, + (byte) 184, + 30, + 124, + 77, + 47, + 78, + }; // Represents 11 1010 1011 0011 1100 1011 byte[] frameCounterBytes = { (byte) 203, (byte) 179, 58 }; @Test void initialize() { - BitSet sessionKey = BitSet.valueOf( sessionKeyBytes ); - BitSet frameCounter = BitSet.valueOf( frameCounterBytes ); - - BitSet expected = new BitSet( 19 ); - expected.set( 0 ); - expected.set( 1 ); - expected.set( 3 ); - expected.set( 4 ); - expected.set( 5 ); - expected.set( 7 ); - expected.set( 9 ); - expected.set( 10 ); - expected.set( 11 ); - expected.set( 12 ); - expected.set( 13 ); - expected.set( 15 ); - expected.set( 16 ); - expected.set( 17 ); - - LFSR lfsr0 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } ); - lfsr0.initialize( sessionKey, frameCounter ); - assertEquals( expected.toString(), lfsr0.toString() ); + BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); + BitSet frameCounter = BitSet.valueOf(frameCounterBytes); + + BitSet expected = new BitSet(19); + expected.set(0); + expected.set(1); + expected.set(3); + expected.set(4); + expected.set(5); + expected.set(7); + expected.set(9); + expected.set(10); + expected.set(11); + expected.set(12); + expected.set(13); + expected.set(15); + expected.set(16); + expected.set(17); + + LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + lfsr0.initialize(sessionKey, frameCounter); + assertEquals(expected.toString(), lfsr0.toString()); } @Test void clock() { - BitSet sessionKey = BitSet.valueOf( sessionKeyBytes ); - BitSet frameCounter = BitSet.valueOf( frameCounterBytes ); - - LFSR lfsr0 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } ); - lfsr0.initialize( sessionKey, frameCounter ); - - BitSet expected = new BitSet( 19 ); - expected.set( 0 ); - expected.set( 1 ); - expected.set( 2 ); - expected.set( 4 ); - expected.set( 5 ); - expected.set( 6 ); - expected.set( 8 ); - expected.set( 10 ); - expected.set( 11 ); - expected.set( 12 ); - expected.set( 13 ); - expected.set( 14 ); - expected.set( 16 ); - expected.set( 17 ); - expected.set( 18 ); + BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); + BitSet frameCounter = BitSet.valueOf(frameCounterBytes); + + LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + lfsr0.initialize(sessionKey, frameCounter); + + BitSet expected = new BitSet(19); + expected.set(0); + expected.set(1); + expected.set(2); + expected.set(4); + expected.set(5); + expected.set(6); + expected.set(8); + expected.set(10); + expected.set(11); + expected.set(12); + expected.set(13); + expected.set(14); + expected.set(16); + expected.set(17); + expected.set(18); lfsr0.clock(); - assertEquals( expected.toString(), lfsr0.toString() ); + assertEquals(expected.toString(), lfsr0.toString()); } @Test void getClockBit() { - BitSet sessionKey = BitSet.valueOf( sessionKeyBytes ); - BitSet frameCounter = BitSet.valueOf( frameCounterBytes ); + BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); + BitSet frameCounter = BitSet.valueOf(frameCounterBytes); - LFSR lfsr0 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } ); + LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); - assertFalse( lfsr0.getClockBit() ); + assertFalse(lfsr0.getClockBit()); - lfsr0.initialize( sessionKey, frameCounter ); + lfsr0.initialize(sessionKey, frameCounter); - assertFalse( lfsr0.getClockBit() ); + assertFalse(lfsr0.getClockBit()); } } diff --git a/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java b/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java index f2095814219a..d6b137406827 100644 --- a/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java +++ b/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java @@ -3,12 +3,11 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class BloomFilterTest { @Test - public void test1(){ - BloomFilter bloomFilter = new BloomFilter<>(3,10); + public void test1() { + BloomFilter bloomFilter = new BloomFilter<>(3, 10); bloomFilter.insert(3); bloomFilter.insert(17); @@ -17,8 +16,8 @@ public void test1(){ } @Test - public void test2(){ - BloomFilter bloomFilter = new BloomFilter<>(4,20); + public void test2() { + BloomFilter bloomFilter = new BloomFilter<>(4, 20); bloomFilter.insert("omar"); bloomFilter.insert("mahamid"); diff --git a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java index ccf99197fbff..14cbb63049f1 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java @@ -6,62 +6,59 @@ class LFUCacheTest { - @Test - void testLFUCacheWithIntegerValueShouldPass() { + @Test + void testLFUCacheWithIntegerValueShouldPass() { + LFUCache lfuCache = new LFUCache<>(5); + lfuCache.put(1, 10); + lfuCache.put(2, 20); + lfuCache.put(3, 30); + lfuCache.put(4, 40); + lfuCache.put(5, 50); - LFUCache lfuCache = new LFUCache<>(5); - lfuCache.put(1, 10); - lfuCache.put(2, 20); - lfuCache.put(3, 30); - lfuCache.put(4, 40); - lfuCache.put(5, 50); + //get method call will increase frequency of key 1 by 1 + assertEquals(10, lfuCache.get(1)); - //get method call will increase frequency of key 1 by 1 - assertEquals(10, lfuCache.get(1)); + //this operation will remove value with key as 2 + lfuCache.put(6, 60); - //this operation will remove value with key as 2 - lfuCache.put(6, 60); + //will return null as value with key 2 is now evicted + assertEquals(null, lfuCache.get(2)); - //will return null as value with key 2 is now evicted - assertEquals(null, lfuCache.get(2)); + //should return 60 + assertEquals(60, lfuCache.get(6)); - //should return 60 - assertEquals(60, lfuCache.get(6)); + //this operation will remove value with key as 3 + lfuCache.put(7, 70); - //this operation will remove value with key as 3 - lfuCache.put(7, 70); + assertEquals(null, lfuCache.get(2)); + assertEquals(70, lfuCache.get(7)); + } - assertEquals(null, lfuCache.get(2)); - assertEquals(70, lfuCache.get(7)); - } + @Test + void testLFUCacheWithStringValueShouldPass() { + LFUCache lfuCache = new LFUCache<>(5); + lfuCache.put(1, "Alpha"); + lfuCache.put(2, "Beta"); + lfuCache.put(3, "Gamma"); + lfuCache.put(4, "Delta"); + lfuCache.put(5, "Eplison"); - @Test - void testLFUCacheWithStringValueShouldPass() { + //get method call will increase frequency of key 1 by 1 + assertEquals("Alpha", lfuCache.get(1)); - LFUCache lfuCache = new LFUCache<>(5); - lfuCache.put(1, "Alpha"); - lfuCache.put(2, "Beta"); - lfuCache.put(3, "Gamma"); - lfuCache.put(4, "Delta"); - lfuCache.put(5, "Eplison"); + //this operation will remove value with key as 2 + lfuCache.put(6, "Digamma"); - //get method call will increase frequency of key 1 by 1 - assertEquals("Alpha", lfuCache.get(1)); + //will return null as value with key 2 is now evicted + assertEquals(null, lfuCache.get(2)); - //this operation will remove value with key as 2 - lfuCache.put(6, "Digamma"); + //should return string Digamma + assertEquals("Digamma", lfuCache.get(6)); - //will return null as value with key 2 is now evicted - assertEquals(null, lfuCache.get(2)); - - //should return string Digamma - assertEquals("Digamma", lfuCache.get(6)); - - //this operation will remove value with key as 3 - lfuCache.put(7, "Zeta"); - - assertEquals(null, lfuCache.get(2)); - assertEquals("Zeta", lfuCache.get(7)); - } + //this operation will remove value with key as 3 + lfuCache.put(7, "Zeta"); + assertEquals(null, lfuCache.get(2)); + assertEquals("Zeta", lfuCache.get(7)); + } } diff --git a/src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java index ca44f2ca4323..c56ada060022 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java @@ -13,11 +13,11 @@ public class LRUCacheTest { public void putAndGetIntegerValues() { LRUCache lruCache = new LRUCache<>(SIZE); - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { lruCache.put(i, i); } - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { assertEquals(i, lruCache.get(i)); } } @@ -26,11 +26,11 @@ public void putAndGetIntegerValues() { public void putAndGetStringValues() { LRUCache lruCache = new LRUCache<>(SIZE); - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { lruCache.put("key" + i, "value" + i); } - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { assertEquals("value" + i, lruCache.get("key" + i)); } } @@ -49,7 +49,7 @@ public void nullKeysAndValues() { public void overCapacity() { LRUCache mruCache = new LRUCache<>(SIZE); - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { mruCache.put(i, i); } diff --git a/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java index 6ff77aebf7ae..447feb38e788 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.caches; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.Test; + public class MRUCacheTest { private static final int SIZE = 5; @@ -13,11 +13,11 @@ public class MRUCacheTest { public void putAndGetIntegerValues() { MRUCache lruCache = new MRUCache<>(SIZE); - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { lruCache.put(i, i); } - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { assertEquals(i, lruCache.get(i)); } } @@ -26,11 +26,11 @@ public void putAndGetIntegerValues() { public void putAndGetStringValues() { MRUCache lruCache = new MRUCache<>(SIZE); - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { lruCache.put("key" + i, "value" + i); } - for(int i = 0; i < SIZE; i++) { + for (int i = 0; i < SIZE; i++) { assertEquals("value" + i, lruCache.get("key" + i)); } } @@ -49,7 +49,7 @@ public void nullKeysAndValues() { public void overCapacity() { MRUCache mruCache = new MRUCache<>(SIZE); - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { mruCache.put(i, i); } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java index 6b4c5102fc84..3746753b6c68 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java @@ -6,34 +6,40 @@ class HamiltonianCycleTest { - private HamiltonianCycle hamiltonianCycle = new HamiltonianCycle(); - - @Test - void testFindHamiltonianCycleShouldReturnHamiltonianCycle() { - int[] expectedArray = {0,1,2,4,3,0}; - int[][] inputArray = { - {0, 1, 0, 1, 0}, - {1, 0, 1, 1, 1}, - {0, 1, 0, 0, 1}, - {1, 1, 0, 0, 1}, - {0, 1, 1, 1, 0} - }; - - assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); - } - - @Test - void testFindHamiltonianCycleShouldReturnInfinityArray() { - int[] expectedArray = {-1,-1,-1,-1,-1,-1}; - - int[][] inputArray = { - {0, 1, 0, 1, 0}, - {1, 0, 1, 1, 1}, - {0, 1, 0, 0, 1}, - {1, 1, 0, 0, 0}, - {0, 1, 1, 0, 0} - }; - - assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); - } + private HamiltonianCycle hamiltonianCycle = new HamiltonianCycle(); + + @Test + void testFindHamiltonianCycleShouldReturnHamiltonianCycle() { + int[] expectedArray = { 0, 1, 2, 4, 3, 0 }; + int[][] inputArray = { + { 0, 1, 0, 1, 0 }, + { 1, 0, 1, 1, 1 }, + { 0, 1, 0, 0, 1 }, + { 1, 1, 0, 0, 1 }, + { 0, 1, 1, 1, 0 }, + }; + + assertArrayEquals( + expectedArray, + hamiltonianCycle.findHamiltonianCycle(inputArray) + ); + } + + @Test + void testFindHamiltonianCycleShouldReturnInfinityArray() { + int[] expectedArray = { -1, -1, -1, -1, -1, -1 }; + + int[][] inputArray = { + { 0, 1, 0, 1, 0 }, + { 1, 0, 1, 1, 1 }, + { 0, 1, 0, 0, 1 }, + { 1, 1, 0, 0, 0 }, + { 0, 1, 1, 0, 0 }, + }; + + assertArrayEquals( + expectedArray, + hamiltonianCycle.findHamiltonianCycle(inputArray) + ); + } } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java index 797db6cb8bdc..fc6655fa3d3e 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.hashmap; -import com.thealgorithms.datastructures.hashmap.hashing.HashMapCuckooHashing; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import com.thealgorithms.datastructures.hashmap.hashing.HashMapCuckooHashing; import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class HashMapCuckooHashingTest { @@ -55,8 +54,7 @@ void removeNone() { int initialSize = hashTable.getNumberOfKeysInTable(); try { hashTable.deleteKeyFromHashTable(3); - } - catch (Exception e){ + } catch (Exception e) { assertTrue(true); return; } @@ -93,12 +91,10 @@ void avoidInfiniteLoops() { assertTrue(hashTable.checkTableContainsKey(100)); } - private HashMapCuckooHashing createHashMapCuckooHashing() { HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10); - int[] values = {11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222}; + int[] values = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222 }; Arrays.stream(values).forEach(hashTable::insertKey2HashTable); return hashTable; } - -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java index dde9effb74ff..621b353b85df 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java @@ -1,10 +1,11 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class GenericHashMapUsingArrayListTest { + @Test void testGenericHashmapWhichUsesArrayAndBothKeyAndValueAreStrings() { GenericHashMapUsingArrayList map = new GenericHashMapUsingArrayList<>(); @@ -46,4 +47,4 @@ void testGenericHashmapWhichUsesArrayAndKeyIsIntegerValueIsString() { assertEquals("Washington DC", map.get(101)); assertTrue(map.containsKey(46)); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java index 1e2dfe2f2845..b4443da153b4 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java @@ -1,10 +1,11 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class GenericHashMapUsingArrayTest { + @Test void testGenericHashmapWhichUsesArrayAndBothKeyAndValueAreStrings() { GenericHashMapUsingArray map = new GenericHashMapUsingArray<>(); @@ -46,4 +47,4 @@ void testGenericHashmapWhichUsesArrayAndKeyIsIntegerValueIsString() { assertEquals("Washington DC", map.get(101)); assertTrue(map.containsKey(46)); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java index be72e28a132a..b414bab2b8a0 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java @@ -3,10 +3,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class FibonacciHeapTest{ +public class FibonacciHeapTest { @Test - void testHeap(){ + void testHeap() { FibonacciHeap fibonacciHeap = new FibonacciHeap(); fibonacciHeap.insert(5); fibonacciHeap.insert(3); diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java index 1bbe11527ec8..9214b613246c 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.lists; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; import java.util.stream.IntStream; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class SkipListTest { @@ -70,20 +69,33 @@ void removeFromTail() { @Test void checkSortedOnLowestLayer() { SkipList skipList = new SkipList<>(); - String[] values = {"d", "b", "a", "c"}; + String[] values = { "d", "b", "a", "c" }; Arrays.stream(values).forEach(skipList::add); print(skipList); - String[] actualOrder = IntStream.range(0, values.length) - .mapToObj(skipList::get) - .toArray(String[]::new); + String[] actualOrder = IntStream + .range(0, values.length) + .mapToObj(skipList::get) + .toArray(String[]::new); - assertArrayEquals(new String[]{"a", "b", "c", "d"}, actualOrder); + assertArrayEquals(new String[] { "a", "b", "c", "d" }, actualOrder); } private SkipList createSkipList() { SkipList skipList = new SkipList<>(); - String[] values = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}; + String[] values = { + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + }; Arrays.stream(values).forEach(skipList::add); return skipList; } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java index fbfbf00f9551..e4080373e340 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java @@ -1,24 +1,24 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class KDTreeTest { KDTree.Point pointOf(int x, int y) { - return new KDTree.Point(new int[]{x, y}); + return new KDTree.Point(new int[] { x, y }); } @Test void findMin() { int[][] coordinates = { - {30, 40}, - {5, 25}, - {70, 70}, - {10, 12}, - {50, 30}, - {35, 45} + { 30, 40 }, + { 5, 25 }, + { 70, 70 }, + { 10, 12 }, + { 50, 30 }, + { 35, 45 }, }; KDTree kdTree = new KDTree(coordinates); @@ -29,12 +29,12 @@ void findMin() { @Test void delete() { int[][] coordinates = { - {30, 40}, - {5, 25}, - {70, 70}, - {10, 12}, - {50, 30}, - {35, 45} + { 30, 40 }, + { 5, 25 }, + { 70, 70 }, + { 10, 12 }, + { 50, 30 }, + { 35, 45 }, }; KDTree kdTree = new KDTree(coordinates); @@ -46,12 +46,12 @@ void delete() { @Test void findNearest() { int[][] coordinates = { - {2, 3}, - {5, 4}, - {9, 6}, - {4, 7}, - {8, 1}, - {7, 2} + { 2, 3 }, + { 5, 4 }, + { 9, 6 }, + { 4, 7 }, + { 8, 1 }, + { 7, 2 }, }; KDTree kdTree = new KDTree(coordinates); @@ -60,5 +60,4 @@ void findNearest() { assertEquals(pointOf(2, 3), kdTree.findNearest(pointOf(1, 1))); assertEquals(pointOf(5, 4), kdTree.findNearest(pointOf(5, 5))); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java index 69153c7d2bca..bbec32a71c89 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java @@ -1,14 +1,14 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class LazySegmentTreeTest { @Test void build() { - int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRoot().getValue()); assertEquals(15, lazySegmentTree.getRoot().getLeft().getValue()); @@ -17,7 +17,7 @@ void build() { @Test void update() { - int[] arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + int[] arr = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(10, lazySegmentTree.getRoot().getValue()); @@ -36,7 +36,7 @@ void update() { @Test void get() { - int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRange(0, 10)); assertEquals(3, lazySegmentTree.getRange(0, 2)); @@ -46,7 +46,7 @@ void get() { @Test void updateAndGet() { - int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int[] arr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); for (int i = 0; i < 10; i++) for (int j = i + 1; j < 10; j++) { @@ -56,5 +56,4 @@ void updateAndGet() { assertEquals(0, lazySegmentTree.getRange(i, j)); } } - } diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java index 611df73bcffc..2da961d7ca32 100644 --- a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java +++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java @@ -1,11 +1,11 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + public class ADTFractionTest { private final ADTFraction fraction1 = new ADTFraction(3, 5); @@ -13,7 +13,10 @@ public class ADTFractionTest { @Test void testConstructorWithDenominatorEqualToZero() { - Exception exception = assertThrows(IllegalArgumentException.class, () -> new ADTFraction(1, 0)); + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> new ADTFraction(1, 0) + ); assertEquals("Denominator cannot be 0", exception.getMessage()); } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java index a68c1a81bd3c..78a8c09369e3 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class AbsoluteMaxTest { @Test @@ -15,7 +15,10 @@ void testGetMaxValue() { @Test void testGetMaxValueWithNoArguments() { - Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMax.getMaxValue()); + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> AbsoluteMax.getMaxValue() + ); assertEquals("Numbers array cannot be empty", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java index 571b080cd866..6322341da658 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class AbsoluteMinTest { @Test @@ -15,7 +15,10 @@ void testGetMinValue() { @Test void testGetMinValueWithNoArguments() { - Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> AbsoluteMin.getMinValue() + ); assertEquals("Numbers array cannot be empty", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java index 8b95eaec26fa..9f5a3730e272 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -1,18 +1,23 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class AbsoluteValueTest { @Test void testGetAbsValue() { - Stream.generate(() -> ThreadLocalRandom.current().nextInt()) - .limit(1000) - .forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); + Stream + .generate(() -> ThreadLocalRandom.current().nextInt()) + .limit(1000) + .forEach(number -> + assertEquals( + Math.abs(number), + AbsoluteValue.getAbsValue(number) + ) + ); } } diff --git a/src/test/java/com/thealgorithms/maths/AliquotSumTest.java b/src/test/java/com/thealgorithms/maths/AliquotSumTest.java index eca726ae271c..d3fef8d366f3 100644 --- a/src/test/java/com/thealgorithms/maths/AliquotSumTest.java +++ b/src/test/java/com/thealgorithms/maths/AliquotSumTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class AliquotSumTest { @Test diff --git a/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java b/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java index 380355857225..7c880750c410 100644 --- a/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java @@ -1,15 +1,15 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AmicableNumberTest { - - @Test - void testAmicableNumber() { - assertThat(AmicableNumber.isAmicableNumber(220, 284)).isTrue(); - assertThat(AmicableNumber.isAmicableNumber(1184, 1210)).isTrue(); - assertThat(AmicableNumber.isAmicableNumber(2620, 2924)).isTrue(); - } -} +package com.thealgorithms.maths; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class AmicableNumberTest { + + @Test + void testAmicableNumber() { + assertThat(AmicableNumber.isAmicableNumber(220, 284)).isTrue(); + assertThat(AmicableNumber.isAmicableNumber(1184, 1210)).isTrue(); + assertThat(AmicableNumber.isAmicableNumber(2620, 2924)).isTrue(); + } +} diff --git a/src/test/java/com/thealgorithms/maths/ArmstrongTest.java b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java index a833e41044f7..3b11b83de75f 100644 --- a/src/test/java/com/thealgorithms/maths/ArmstrongTest.java +++ b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; + /** * @author Vivek * @since 15/03/22 diff --git a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java index fa849bc22595..5ec7755ac35d 100644 --- a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java @@ -1,16 +1,16 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AutomorphicNumberTest{ - - @Test - void testAutomorphicNumber(){ - assertThat(AutomorphicNumber.isAutomorphic(625)).isTrue(); - assertThat(AutomorphicNumber.isAutomorphic(144)).isFalse(); - assertThat(AutomorphicNumber.isAutomorphic(9376)).isTrue(); - assertThat(AutomorphicNumber.isAutomorphic(169)).isFalse(); - } -} +package com.thealgorithms.maths; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class AutomorphicNumberTest { + + @Test + void testAutomorphicNumber() { + assertThat(AutomorphicNumber.isAutomorphic(625)).isTrue(); + assertThat(AutomorphicNumber.isAutomorphic(144)).isFalse(); + assertThat(AutomorphicNumber.isAutomorphic(9376)).isTrue(); + assertThat(AutomorphicNumber.isAutomorphic(169)).isFalse(); + } +} diff --git a/src/test/java/com/thealgorithms/maths/AverageTest.java b/src/test/java/com/thealgorithms/maths/AverageTest.java index 04d27ab4bcd1..2b82f6f9ed12 100644 --- a/src/test/java/com/thealgorithms/maths/AverageTest.java +++ b/src/test/java/com/thealgorithms/maths/AverageTest.java @@ -3,12 +3,12 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class AverageTest { - double [] numbers = {3, 6, 9, 12, 15, 18, 21}; + + double[] numbers = { 3, 6, 9, 12, 15, 18, 21 }; + @Test public void testAverage() { - Assertions.assertEquals(12, Average.average(numbers)); } } diff --git a/src/test/java/com/thealgorithms/maths/BinaryPowTest.java b/src/test/java/com/thealgorithms/maths/BinaryPowTest.java index ec4005d4ea65..f9b019e8fad4 100644 --- a/src/test/java/com/thealgorithms/maths/BinaryPowTest.java +++ b/src/test/java/com/thealgorithms/maths/BinaryPowTest.java @@ -1,16 +1,16 @@ -package com.thealgorithms.maths; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class BinaryPowTest { - - @Test - void testBinPow() { - assertEquals(4, BinaryPow.binPow(2, 2)); - assertEquals(256, BinaryPow.binPow(4, 4)); - assertEquals(729, BinaryPow.binPow(9, 3)); - assertEquals(262144, BinaryPow.binPow(8, 6)); - } -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class BinaryPowTest { + + @Test + void testBinPow() { + assertEquals(4, BinaryPow.binPow(2, 2)); + assertEquals(256, BinaryPow.binPow(4, 4)); + assertEquals(729, BinaryPow.binPow(9, 3)); + assertEquals(262144, BinaryPow.binPow(8, 6)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java b/src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java index f9a1c5e48921..58cfcbad57fb 100644 --- a/src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java +++ b/src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java @@ -1,18 +1,16 @@ -package com.thealgorithms.maths; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class BinomialCoefficientTest { - - @Test - void testBinomialCoefficient() { - - assertEquals(190, BinomialCoefficient.binomialCoefficient(20, 2)); - assertEquals(792, BinomialCoefficient.binomialCoefficient(12, 5)); - assertEquals(84, BinomialCoefficient.binomialCoefficient(9, 3)); - assertEquals(1, BinomialCoefficient.binomialCoefficient(17, 17)); - - } -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class BinomialCoefficientTest { + + @Test + void testBinomialCoefficient() { + assertEquals(190, BinomialCoefficient.binomialCoefficient(20, 2)); + assertEquals(792, BinomialCoefficient.binomialCoefficient(12, 5)); + assertEquals(84, BinomialCoefficient.binomialCoefficient(9, 3)); + assertEquals(1, BinomialCoefficient.binomialCoefficient(17, 17)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/CeilTest.java b/src/test/java/com/thealgorithms/maths/CeilTest.java index e57e23f19709..5596760a8c40 100644 --- a/src/test/java/com/thealgorithms/maths/CeilTest.java +++ b/src/test/java/com/thealgorithms/maths/CeilTest.java @@ -1,17 +1,17 @@ -package com.thealgorithms.maths; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class CeilTest { - - @Test - void testCeil() { - assertEquals(8, Ceil.ceil(7.057)); - assertEquals(8, Ceil.ceil(7.004)); - assertEquals(-13, Ceil.ceil(-13.004)); - assertEquals(1, Ceil.ceil(.98)); - assertEquals(-11, Ceil.ceil(-11.357)); - } -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CeilTest { + + @Test + void testCeil() { + assertEquals(8, Ceil.ceil(7.057)); + assertEquals(8, Ceil.ceil(7.004)); + assertEquals(-13, Ceil.ceil(-13.004)); + assertEquals(1, Ceil.ceil(.98)); + assertEquals(-11, Ceil.ceil(-11.357)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java index e63a956dc35f..504435aebce3 100644 --- a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java +++ b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; class CollatzConjectureTest { @@ -28,13 +27,34 @@ void nextNumberFromOddNumber() { @Test void collatzConjecture() { - final List expected = List.of(35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1); + final List expected = List.of( + 35, + 106, + 53, + 160, + 80, + 40, + 20, + 10, + 5, + 16, + 8, + 4, + 2, + 1 + ); assertIterableEquals(expected, cConjecture.collatzConjecture(35)); } @Test void sequenceOfNotNaturalFirstNumber() { - assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(0)); - assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(-1)); + assertThrows( + IllegalArgumentException.class, + () -> cConjecture.collatzConjecture(0) + ); + assertThrows( + IllegalArgumentException.class, + () -> cConjecture.collatzConjecture(-1) + ); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/maths/CombinationsTest.java b/src/test/java/com/thealgorithms/maths/CombinationsTest.java index 0bcefb7de8b5..f260b1e11494 100644 --- a/src/test/java/com/thealgorithms/maths/CombinationsTest.java +++ b/src/test/java/com/thealgorithms/maths/CombinationsTest.java @@ -1,30 +1,26 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class CombinationsTest { - - @Test - void testCombination() { - - assertEquals(1, Combinations.combinations(1, 1)); - assertEquals(252, Combinations.combinations(10, 5)); - assertEquals(20, Combinations.combinations(6, 3)); - assertEquals(15504, Combinations.combinations(20, 5)); - - } - - @Test - void testCombinationOptimised() { - - assertEquals(100, Combinations.combinationsOptimized(100, 1)); - assertEquals(1, Combinations.combinationsOptimized(1, 1)); - assertEquals(252, Combinations.combinationsOptimized(10, 5)); - assertEquals(20, Combinations.combinationsOptimized(6, 3)); - assertEquals(15504, Combinations.combinationsOptimized(20, 5)); - assertEquals(2535650040L, Combinations.combinationsOptimized(200, 5)); - - } -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CombinationsTest { + + @Test + void testCombination() { + assertEquals(1, Combinations.combinations(1, 1)); + assertEquals(252, Combinations.combinations(10, 5)); + assertEquals(20, Combinations.combinations(6, 3)); + assertEquals(15504, Combinations.combinations(20, 5)); + } + + @Test + void testCombinationOptimised() { + assertEquals(100, Combinations.combinationsOptimized(100, 1)); + assertEquals(1, Combinations.combinationsOptimized(1, 1)); + assertEquals(252, Combinations.combinationsOptimized(10, 5)); + assertEquals(20, Combinations.combinationsOptimized(6, 3)); + assertEquals(15504, Combinations.combinationsOptimized(20, 5)); + assertEquals(2535650040L, Combinations.combinationsOptimized(200, 5)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/DigitalRootTest.java b/src/test/java/com/thealgorithms/maths/DigitalRootTest.java index 7c10ed0d35b5..eeeeb5431507 100644 --- a/src/test/java/com/thealgorithms/maths/DigitalRootTest.java +++ b/src/test/java/com/thealgorithms/maths/DigitalRootTest.java @@ -1,20 +1,18 @@ -package com.thealgorithms.maths; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class DigitalRootTest { - - @Test - void testDigitalroot() { - - assertEquals(4, DigitalRoot.digitalRoot(4)); - assertEquals(9, DigitalRoot.digitalRoot(9)); - assertEquals(4, DigitalRoot.digitalRoot(49)); - assertEquals(6, DigitalRoot.digitalRoot(78)); - assertEquals(4, DigitalRoot.digitalRoot(1228)); - assertEquals(5, DigitalRoot.digitalRoot(71348)); - - } -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class DigitalRootTest { + + @Test + void testDigitalroot() { + assertEquals(4, DigitalRoot.digitalRoot(4)); + assertEquals(9, DigitalRoot.digitalRoot(9)); + assertEquals(4, DigitalRoot.digitalRoot(49)); + assertEquals(6, DigitalRoot.digitalRoot(78)); + assertEquals(4, DigitalRoot.digitalRoot(1228)); + assertEquals(5, DigitalRoot.digitalRoot(71348)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index 811eb4bf8239..1dfb92d0d1e3 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -6,80 +6,105 @@ import org.junit.jupiter.api.Test; public class DistanceFormulaTest { - @Test - void euclideanTest1() { - Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 1, 2, 2), 1.4142135623730951); - } - - @Test - void euclideanTest2() { - Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 3, 8, 0), 7.0710678118654755); - } - - @Test - void euclideanTest3() { - Assertions.assertEquals(DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), 110.91911467371168); - } - - @Test - void euclideanTest4() { - Assertions.assertEquals(DistanceFormula.euclideanDistance(1000, 13, 20000, 84), 19022.067605809836); - } - - @Test - public void manhattantest1() { - assertEquals(DistanceFormula.manhattanDistance(1, 2, 3, 4), 4); - } - - @Test - public void manhattantest2() { - assertEquals(DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), 18.8); - } - - @Test - public void manhattanTest3() { - assertEquals(DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), 26.442); - } - - @Test - public void hammingTest1() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 0, 0, 0, 0 }; - assertEquals(DistanceFormula.hammingDistance(array1, array2), 4); - } - - @Test - public void hammingTest2() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 1, 1, 1, 1 }; - assertEquals(DistanceFormula.hammingDistance(array1, array2), 0); - } - - @Test - public void hammingTest3() { - int[] array1 = { 1, 0, 0, 1, 1, 0, 1, 1, 0 }; - int[] array2 = { 0, 1, 0, 0, 1, 1, 1, 0, 0 }; - assertEquals(DistanceFormula.hammingDistance(array1, array2), 5); - } - - @Test - public void minkowskiTest1() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 1), 10); - } - - @Test - public void minkowskiTest2() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 2), 5.477225575051661); - } - - @Test - public void minkowskiTest3() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 3), 4.641588833612778); - } + + @Test + void euclideanTest1() { + Assertions.assertEquals( + DistanceFormula.euclideanDistance(1, 1, 2, 2), + 1.4142135623730951 + ); + } + + @Test + void euclideanTest2() { + Assertions.assertEquals( + DistanceFormula.euclideanDistance(1, 3, 8, 0), + 7.0710678118654755 + ); + } + + @Test + void euclideanTest3() { + Assertions.assertEquals( + DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), + 110.91911467371168 + ); + } + + @Test + void euclideanTest4() { + Assertions.assertEquals( + DistanceFormula.euclideanDistance(1000, 13, 20000, 84), + 19022.067605809836 + ); + } + + @Test + public void manhattantest1() { + assertEquals(DistanceFormula.manhattanDistance(1, 2, 3, 4), 4); + } + + @Test + public void manhattantest2() { + assertEquals( + DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), + 18.8 + ); + } + + @Test + public void manhattanTest3() { + assertEquals( + DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), + 26.442 + ); + } + + @Test + public void hammingTest1() { + int[] array1 = { 1, 1, 1, 1 }; + int[] array2 = { 0, 0, 0, 0 }; + assertEquals(DistanceFormula.hammingDistance(array1, array2), 4); + } + + @Test + public void hammingTest2() { + int[] array1 = { 1, 1, 1, 1 }; + int[] array2 = { 1, 1, 1, 1 }; + assertEquals(DistanceFormula.hammingDistance(array1, array2), 0); + } + + @Test + public void hammingTest3() { + int[] array1 = { 1, 0, 0, 1, 1, 0, 1, 1, 0 }; + int[] array2 = { 0, 1, 0, 0, 1, 1, 1, 0, 0 }; + assertEquals(DistanceFormula.hammingDistance(array1, array2), 5); + } + + @Test + public void minkowskiTest1() { + double[] array1 = { 1, 3, 8, 5 }; + double[] array2 = { 4, 2, 6, 9 }; + assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 1), 10); + } + + @Test + public void minkowskiTest2() { + double[] array1 = { 1, 3, 8, 5 }; + double[] array2 = { 4, 2, 6, 9 }; + assertEquals( + DistanceFormula.minkowskiDistance(array1, array2, 2), + 5.477225575051661 + ); + } + + @Test + public void minkowskiTest3() { + double[] array1 = { 1, 3, 8, 5 }; + double[] array2 = { 4, 2, 6, 9 }; + assertEquals( + DistanceFormula.minkowskiDistance(array1, array2, 3), + 4.641588833612778 + ); + } } diff --git a/src/test/java/com/thealgorithms/maths/FFTTest.java b/src/test/java/com/thealgorithms/maths/FFTTest.java index fcdf64aba197..dfb9ea532dee 100644 --- a/src/test/java/com/thealgorithms/maths/FFTTest.java +++ b/src/test/java/com/thealgorithms/maths/FFTTest.java @@ -1,147 +1,137 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; + import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + class FFTTest { // Testing the simple function getReal @Test - void getRealtest() - { - FFT.Complex complex = new FFT.Complex(1.0,1.0); - assertEquals(1.0,complex.getReal()); + void getRealtest() { + FFT.Complex complex = new FFT.Complex(1.0, 1.0); + assertEquals(1.0, complex.getReal()); } // Testing the simple function getImaginary @Test - void getImaginaryTest() - { + void getImaginaryTest() { FFT.Complex complex = new FFT.Complex(); - assertEquals(0.0,complex.getImaginary()); + assertEquals(0.0, complex.getImaginary()); } // Testing the function add, assertEqual test @Test - void addTest() - { - FFT.Complex complex1 = new FFT.Complex(1.0,1.0); - FFT.Complex complex2 = new FFT.Complex(2.0,2.0); + void addTest() { + FFT.Complex complex1 = new FFT.Complex(1.0, 1.0); + FFT.Complex complex2 = new FFT.Complex(2.0, 2.0); double add = complex1.add(complex2).getReal(); - assertEquals(3.0,add); + assertEquals(3.0, add); } // Testing the function add, assertNotEqual test @Test - void addFalseTest() - { - FFT.Complex complex1 = new FFT.Complex(1.0,1.0); - FFT.Complex complex2 = new FFT.Complex(2.0,2.0); + void addFalseTest() { + FFT.Complex complex1 = new FFT.Complex(1.0, 1.0); + FFT.Complex complex2 = new FFT.Complex(2.0, 2.0); double add = complex1.add(complex2).getReal(); - assertNotEquals(2.0,add); + assertNotEquals(2.0, add); } // Testing the function substract, assertEqual test @Test - void subtractTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); - FFT.Complex complex2 = new FFT.Complex(1.0,1.0); + void subtractTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); + FFT.Complex complex2 = new FFT.Complex(1.0, 1.0); double sub = complex1.subtract(complex2).getReal(); - assertEquals(1.0,sub); + assertEquals(1.0, sub); } // Testing the function multiply complex, assertEqual test @Test - void multiplyWithComplexTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); - FFT.Complex complex2 = new FFT.Complex(1.0,1.0); + void multiplyWithComplexTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); + FFT.Complex complex2 = new FFT.Complex(1.0, 1.0); double multiReal = complex1.multiply(complex2).getReal(); double multiImg = complex1.multiply(complex2).getImaginary(); - assertEquals(0.0,multiReal); - assertEquals(4.0,multiImg); + assertEquals(0.0, multiReal); + assertEquals(4.0, multiImg); } // Testing the function multiply scalar, assertEqual test @Test - void multiplyWithScalarTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); + void multiplyWithScalarTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); double multiReal = complex1.multiply(2).getReal(); double multiImg = complex1.multiply(3).getImaginary(); - assertEquals(4.0,multiReal); - assertEquals(6.0,multiImg); + assertEquals(4.0, multiReal); + assertEquals(6.0, multiImg); } // Testing the function conjugate, assertEqual test @Test - void conjugateTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); + void conjugateTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); double conReal = complex1.conjugate().getReal(); double conImg = complex1.conjugate().getImaginary(); - assertEquals(2.0,conReal); - assertEquals(-2.0,conImg); + assertEquals(2.0, conReal); + assertEquals(-2.0, conImg); } // Testing the function abs, assertEqual test @Test - void abs() - { - FFT.Complex complex1 = new FFT.Complex(2.0,3.0); + void abs() { + FFT.Complex complex1 = new FFT.Complex(2.0, 3.0); double abs = complex1.abs(); - assertEquals(Math.sqrt(13),abs); + assertEquals(Math.sqrt(13), abs); } // Testing the function divide complex, assertEqual test. @Test - void divideWithComplexTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); - FFT.Complex complex2 = new FFT.Complex(1.0,2.0); + void divideWithComplexTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); + FFT.Complex complex2 = new FFT.Complex(1.0, 2.0); double divReal = complex1.divide(complex2).getReal(); double divImg = complex1.divide(complex2).getImaginary(); - assertEquals(1.2,divReal); - assertEquals(-0.4,divImg); + assertEquals(1.2, divReal); + assertEquals(-0.4, divImg); } // Testing the function divide scalar, assertEqual test. @Test - void divideWithScalarTest() - { - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); + void divideWithScalarTest() { + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); double divReal = complex1.divide(2).getReal(); double divImg = complex1.divide(2).getImaginary(); - assertEquals(1,divReal); - assertEquals(1,divImg); + assertEquals(1, divReal); + assertEquals(1, divImg); } // Testing the function fft, assertEqual test. // https://scistatcalc.blogspot.com/2013/12/fft-calculator.html used this link to // ensure the result @Test - void fft() - { + void fft() { ArrayList arr = new ArrayList(); - FFT.Complex complex1 = new FFT.Complex(2.0,2.0); - FFT.Complex complex2 = new FFT.Complex(1.0,3.0); - FFT.Complex complex3 = new FFT.Complex(3.0,1.0); - FFT.Complex complex4 = new FFT.Complex(2.0,2.0); + FFT.Complex complex1 = new FFT.Complex(2.0, 2.0); + FFT.Complex complex2 = new FFT.Complex(1.0, 3.0); + FFT.Complex complex3 = new FFT.Complex(3.0, 1.0); + FFT.Complex complex4 = new FFT.Complex(2.0, 2.0); arr.add(complex1); arr.add(complex2); arr.add(complex3); arr.add(complex4); - arr = FFT.fft(arr,false); - double realV1= arr.get(0).getReal(); - double realV2= arr.get(2).getReal(); + arr = FFT.fft(arr, false); + double realV1 = arr.get(0).getReal(); + double realV2 = arr.get(2).getReal(); double imgV1 = arr.get(0).getImaginary(); double imgV2 = arr.get(2).getImaginary(); - assertEquals(8.0,realV1); - assertEquals(2.0,realV2); + assertEquals(8.0, realV1); + assertEquals(2.0, realV2); assertEquals(8.0, imgV1); - assertEquals(-2.0,imgV2); + assertEquals(-2.0, imgV2); } } diff --git a/src/test/java/com/thealgorithms/maths/FactorialTest.java b/src/test/java/com/thealgorithms/maths/FactorialTest.java index 0eee66c371bd..18c58fad8280 100644 --- a/src/test/java/com/thealgorithms/maths/FactorialTest.java +++ b/src/test/java/com/thealgorithms/maths/FactorialTest.java @@ -1,16 +1,14 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - - - -public class FactorialTest { - - @Test - public void test() { - Factorial fact = new Factorial(); - assertEquals(120,fact.factorial(5)); - } - -} \ No newline at end of file +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +public class FactorialTest { + + @Test + public void test() { + Factorial fact = new Factorial(); + assertEquals(120, fact.factorial(5)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/FastInverseSqrtTests.java b/src/test/java/com/thealgorithms/maths/FastInverseSqrtTests.java index 6c64ba4442a7..6e664f54307f 100644 --- a/src/test/java/com/thealgorithms/maths/FastInverseSqrtTests.java +++ b/src/test/java/com/thealgorithms/maths/FastInverseSqrtTests.java @@ -1,56 +1,50 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class FastInverseSqrtTests { + @Test - void testForOneElement() - { - assertFalse(FastInverseSqrt.inverseSqrt(1332)); + void testForOneElement() { + assertFalse(FastInverseSqrt.inverseSqrt(1332)); // calls for the 2nd inverse method } - @Test - void testForsecond() - { - assertFalse(FastInverseSqrt.inverseSqrt(1332f)); + + @Test + void testForsecond() { + assertFalse(FastInverseSqrt.inverseSqrt(1332f)); // calls for the 1st inverse method - } - - @Test - void testForThird() - { - assertFalse(FastInverseSqrt.inverseSqrt(1)); - } - - @Test - void testForFourth() - { - assertFalse(FastInverseSqrt.inverseSqrt(1f)); - } - - @Test - void testForFifth() - { - assertFalse(FastInverseSqrt.inverseSqrt(4522)); - } - - @Test - void testForSixth() - { - assertFalse(FastInverseSqrt.inverseSqrt(4522f)); - } - - @Test - void testForSeventh() - { - assertFalse(FastInverseSqrt.inverseSqrt(21)); - } - - @Test - void testForEighth() - { - assertFalse(FastInverseSqrt.inverseSqrt(21f)); - } + } + + @Test + void testForThird() { + assertFalse(FastInverseSqrt.inverseSqrt(1)); + } + + @Test + void testForFourth() { + assertFalse(FastInverseSqrt.inverseSqrt(1f)); + } + + @Test + void testForFifth() { + assertFalse(FastInverseSqrt.inverseSqrt(4522)); + } + + @Test + void testForSixth() { + assertFalse(FastInverseSqrt.inverseSqrt(4522f)); + } + + @Test + void testForSeventh() { + assertFalse(FastInverseSqrt.inverseSqrt(21)); + } + + @Test + void testForEighth() { + assertFalse(FastInverseSqrt.inverseSqrt(21f)); + } } diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java index cc6577f0aa3d..43daaeac0f49 100644 --- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java @@ -1,12 +1,16 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class FindMaxTest { - + @Test - public void testFindMaxValue(){ - assertEquals(10, FindMax.findMax(new int[] {1,2,3,4,5,6,7,8,9,10})); + public void testFindMaxValue() { + assertEquals( + 10, + FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) + ); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java index d125151613fd..48fcb277d96f 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java @@ -1,21 +1,26 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class FindMinTest { - @Test - public void testFindMinValue(){ - assertEquals(1, FindMin.findMin(new int[] {1,2,3,4,5,6,7,8,9,10})); - } - @Test - public void test1(){ - assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9})); - } - - @Test - public void test2(){ - assertEquals(0, FindMin.findMin(new int[] {0, 192, 384, 576})); - } + @Test + public void testFindMinValue() { + assertEquals( + 1, + FindMin.findMin(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) + ); + } + + @Test + public void test1() { + assertEquals(1, FindMin.findMin(new int[] { 1, 3, 5, 7, 9 })); + } + + @Test + public void test2() { + assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 })); + } } diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index 3f4d9393465d..e18d3ea82951 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -4,19 +4,29 @@ import org.junit.jupiter.api.Test; public class GCDTest { + @Test void test1() { - Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1,0)); + Assertions.assertThrows( + ArithmeticException.class, + () -> GCD.gcd(-1, 0) + ); } @Test void test2() { - Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2)); + Assertions.assertThrows( + ArithmeticException.class, + () -> GCD.gcd(10, -2) + ); } @Test void test3() { - Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3)); + Assertions.assertThrows( + ArithmeticException.class, + () -> GCD.gcd(-5, -3) + ); } @Test diff --git a/src/test/java/com/thealgorithms/maths/GaussianTest.java b/src/test/java/com/thealgorithms/maths/GaussianTest.java index 85e3b7e888f7..16b8da1338e7 100644 --- a/src/test/java/com/thealgorithms/maths/GaussianTest.java +++ b/src/test/java/com/thealgorithms/maths/GaussianTest.java @@ -1,17 +1,16 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; - import static com.thealgorithms.maths.Gaussian.gaussian; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + public class GaussianTest { // easy pass test for the whole class. Matrix of 2*3. @Test - void passTest1() - { + void passTest1() { ArrayList list = new ArrayList(); ArrayList gaussian = new ArrayList(); ArrayList answer = new ArrayList(); @@ -25,8 +24,8 @@ void passTest1() list.add(2.0); list.add(1.0); list.add(1.0); - gaussian=gaussian(matrixSize,list); + gaussian = gaussian(matrixSize, list); - assertEquals(answer,gaussian); + assertEquals(answer, gaussian); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java index 44328399f8b9..c3ccde86c4ce 100644 --- a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java @@ -4,24 +4,30 @@ import org.junit.jupiter.api.Test; public class HeronsFormulaTest { - @Test - void test1() - { - Assertions.assertEquals(HeronsFormula.Herons(3,4,5), 6.0); - } - @Test - void test2() - { - Assertions.assertEquals(HeronsFormula.Herons(24,30,18), 216.0); - } - @Test - void test3() - { - Assertions.assertEquals(HeronsFormula.Herons(1,1,1), 0.4330127018922193); - } - @Test - void test4() - { - Assertions.assertEquals(HeronsFormula.Herons(4,5,8), 8.181534085976786); - } + + @Test + void test1() { + Assertions.assertEquals(HeronsFormula.Herons(3, 4, 5), 6.0); + } + + @Test + void test2() { + Assertions.assertEquals(HeronsFormula.Herons(24, 30, 18), 216.0); + } + + @Test + void test3() { + Assertions.assertEquals( + HeronsFormula.Herons(1, 1, 1), + 0.4330127018922193 + ); + } + + @Test + void test4() { + Assertions.assertEquals( + HeronsFormula.Herons(4, 5, 8), + 8.181534085976786 + ); + } } diff --git a/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java b/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java index 66f091c1dbc9..650b8dd578f7 100644 --- a/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java +++ b/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java @@ -1,15 +1,14 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class JosephusProblemTest { - - @Test - void testJosephusProblem(){ - assertEquals(3, JosephusProblem.findTheWinner(5,2)); - assertEquals(5, JosephusProblem.findTheWinner(6,4)); - } - -} +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class JosephusProblemTest { + + @Test + void testJosephusProblem() { + assertEquals(3, JosephusProblem.findTheWinner(5, 2)); + assertEquals(5, JosephusProblem.findTheWinner(6, 4)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java index 1d08f810f05e..98c7baa2f8b9 100644 --- a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java @@ -1,70 +1,87 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; -public class KaprekarNumbersTest { - - @Test - void testFor1() - { - assertTrue(KaprekarNumbers.isKaprekarNumber(1)); - } +import java.util.ArrayList; +import org.junit.jupiter.api.Test; - @Test - void testFor45() - { - assertTrue(KaprekarNumbers.isKaprekarNumber(45)); - } +public class KaprekarNumbersTest { - @Test - void testFor297() - { - assertTrue(KaprekarNumbers.isKaprekarNumber(297)); - } + @Test + void testFor1() { + assertTrue(KaprekarNumbers.isKaprekarNumber(1)); + } - @Test - void testFor2223() - { - assertTrue(KaprekarNumbers.isKaprekarNumber(2223)); - } + @Test + void testFor45() { + assertTrue(KaprekarNumbers.isKaprekarNumber(45)); + } - @Test - void testFor857143() - { - assertTrue(KaprekarNumbers.isKaprekarNumber(857143)); - } + @Test + void testFor297() { + assertTrue(KaprekarNumbers.isKaprekarNumber(297)); + } + @Test + void testFor2223() { + assertTrue(KaprekarNumbers.isKaprekarNumber(2223)); + } - @Test - void testFor3() - { - assertFalse(KaprekarNumbers.isKaprekarNumber(3)); - } + @Test + void testFor857143() { + assertTrue(KaprekarNumbers.isKaprekarNumber(857143)); + } - @Test - void testFor26() - { - assertFalse(KaprekarNumbers.isKaprekarNumber(26)); - } + @Test + void testFor3() { + assertFalse(KaprekarNumbers.isKaprekarNumber(3)); + } - @Test - void testFor98() - { - assertFalse(KaprekarNumbers.isKaprekarNumber(98)); - } + @Test + void testFor26() { + assertFalse(KaprekarNumbers.isKaprekarNumber(26)); + } - @Test - void testForRangeOfNumber() { try { - ArrayList rangedNumbers = KaprekarNumbers.kaprekarNumberInRange(1,100000); - long[] allTheNumbers = {1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4950, 5050, 7272, 7777, 9999, 17344, 22222, 77778, 82656, 95121, 99999}; - for (long i:allTheNumbers) { - assert rangedNumbers.contains(i); - } - } catch (Exception e) { - assert false; - } - } + @Test + void testFor98() { + assertFalse(KaprekarNumbers.isKaprekarNumber(98)); + } -} \ No newline at end of file + @Test + void testForRangeOfNumber() { + try { + ArrayList rangedNumbers = KaprekarNumbers.kaprekarNumberInRange( + 1, + 100000 + ); + long[] allTheNumbers = { + 1, + 9, + 45, + 55, + 99, + 297, + 703, + 999, + 2223, + 2728, + 4950, + 5050, + 7272, + 7777, + 9999, + 17344, + 22222, + 77778, + 82656, + 95121, + 99999, + }; + for (long i : allTheNumbers) { + assert rangedNumbers.contains(i); + } + } catch (Exception e) { + assert false; + } + } +} diff --git a/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java b/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java index e239004e23d6..d6baec2e97a7 100644 --- a/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java +++ b/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java @@ -4,24 +4,24 @@ import org.junit.jupiter.api.Test; public class LeastCommonMultipleTest { - /* - * Test for first number greater than second number - */ - @Test - public void testForFirst() { - int result = LeastCommonMultiple.lcm(6,8); - int expected = 24; - Assertions.assertEquals(result, expected); - } - /* - * Test for second number greater than first number - */ - @Test - public void testForSecond() { - int result = LeastCommonMultiple.lcm(8,6); - int expected = 24; - Assertions.assertEquals(result, expected); - } + /* + * Test for first number greater than second number + */ + @Test + public void testForFirst() { + int result = LeastCommonMultiple.lcm(6, 8); + int expected = 24; + Assertions.assertEquals(result, expected); + } + /* + * Test for second number greater than first number + */ + @Test + public void testForSecond() { + int result = LeastCommonMultiple.lcm(8, 6); + int expected = 24; + Assertions.assertEquals(result, expected); + } } diff --git a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java index 0959b6167499..d8fd39d99339 100644 --- a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java @@ -6,61 +6,67 @@ class LiouvilleLambdaFunctionTest { - @Test - void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() { - //given - int number = 0; - String expectedMessage = "Number must be greater than zero."; + @Test + void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() { + //given + int number = 0; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - }); - String actualMessage = exception.getMessage(); + //when + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> { + LiouvilleLambdaFunction.liouvilleLambda(number); + } + ); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + //then + assertEquals(expectedMessage, actualMessage); + } - @Test - void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() { - //given - int number = -1; - String expectedMessage = "Number must be greater than zero."; + @Test + void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() { + //given + int number = -1; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - }); - String actualMessage = exception.getMessage(); + //when + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> { + LiouvilleLambdaFunction.liouvilleLambda(number); + } + ); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + //then + assertEquals(expectedMessage, actualMessage); + } - @Test - void testLiouvilleLambdaMustReturnNegativeOne() { - //given - int number = 11; - int expectedOutput = -1; + @Test + void testLiouvilleLambdaMustReturnNegativeOne() { + //given + int number = 11; + int expectedOutput = -1; - //when - int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); + //when + int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then - assertEquals(expectedOutput, actualOutput); - } + //then + assertEquals(expectedOutput, actualOutput); + } - @Test - void testLiouvilleLambdaMustReturnPositiveOne() { - //given - int number = 10; - int expectedOutput = 1; + @Test + void testLiouvilleLambdaMustReturnPositiveOne() { + //given + int number = 10; + int expectedOutput = 1; - //when - int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); + //when + int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then - assertEquals(expectedOutput, actualOutput); - } + //then + assertEquals(expectedOutput, actualOutput); + } } diff --git a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java index d97a1aeca848..f5897c2b8815 100644 --- a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java @@ -6,58 +6,158 @@ class MobiusFunctionTest { - @Test - void testMobiusForZero() { - //given - int number = 0; - String expectedMessage = "Number must be greater than zero."; - - //when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { - MobiusFunction.mobius(number); - }); - String actualMessage = exception.getMessage(); - - //then - assertEquals(expectedMessage, actualMessage); - } - - @Test - void testMobiusForNegativeNumber() { - //given - int number = -1; - String expectedMessage = "Number must be greater than zero."; - - //when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { - MobiusFunction.mobius(number); - }); - String actualMessage = exception.getMessage(); - - //then - assertEquals(expectedMessage, actualMessage); - } - - @Test - void testMobiusFunction(){ - int[] expectedResultArray = { - 1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, - 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, - 0, 1, 0, -1, 0, 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, -1, 1, - 0, 0, 1, -1, -1, 0, 0, 1, -1, 0, 1, 1, 1, 0, -1, 0, 1, 0, 1, 1, 1, 0, -1, 0, 0, 0 - }; - - for(int i = 1; i <= 100; i++) { - - //given - int expectedValue = expectedResultArray[i-1]; - - //when - int actualValue = MobiusFunction.mobius(i); - - //then - assertEquals(expectedValue,actualValue); - } - } + @Test + void testMobiusForZero() { + //given + int number = 0; + String expectedMessage = "Number must be greater than zero."; + //when + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> { + MobiusFunction.mobius(number); + } + ); + String actualMessage = exception.getMessage(); + + //then + assertEquals(expectedMessage, actualMessage); + } + + @Test + void testMobiusForNegativeNumber() { + //given + int number = -1; + String expectedMessage = "Number must be greater than zero."; + + //when + Exception exception = assertThrows( + IllegalArgumentException.class, + () -> { + MobiusFunction.mobius(number); + } + ); + String actualMessage = exception.getMessage(); + + //then + assertEquals(expectedMessage, actualMessage); + } + + @Test + void testMobiusFunction() { + int[] expectedResultArray = { + 1, + -1, + -1, + 0, + -1, + 1, + -1, + 0, + 0, + 1, + -1, + 0, + -1, + 1, + 1, + 0, + -1, + 0, + -1, + 0, + 1, + 1, + -1, + 0, + 0, + 1, + 0, + 0, + -1, + -1, + -1, + 0, + 1, + 1, + 1, + 0, + -1, + 1, + 1, + 0, + -1, + -1, + -1, + 0, + 0, + 1, + -1, + 0, + 0, + 0, + 1, + 0, + -1, + 0, + 1, + 0, + 1, + 1, + -1, + 0, + -1, + 1, + 0, + 0, + 1, + -1, + -1, + 0, + 1, + -1, + -1, + 0, + -1, + 1, + 0, + 0, + 1, + -1, + -1, + 0, + 0, + 1, + -1, + 0, + 1, + 1, + 1, + 0, + -1, + 0, + 1, + 0, + 1, + 1, + 1, + 0, + -1, + 0, + 0, + 0, + }; + + for (int i = 1; i <= 100; i++) { + //given + int expectedValue = expectedResultArray[i - 1]; + + //when + int actualValue = MobiusFunction.mobius(i); + + //then + assertEquals(expectedValue, actualValue); + } + } } diff --git a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java index 7ec0229c653d..a01c11038684 100644 --- a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java +++ b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java @@ -1,33 +1,34 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class PascalTriangleTest { @Test void testForOne() { int[][] result = PascalTriangle.pascal(1); - int[][] expected = {{1}}; + int[][] expected = { { 1 } }; assertArrayEquals(result, expected); } @Test void testForTwo() { int[][] result = PascalTriangle.pascal(2); - int[][] expected = {{1, 0}, {1, 1}}; + int[][] expected = { { 1, 0 }, { 1, 1 } }; assertArrayEquals(result, expected); } @Test void testForFive() { int[][] result = PascalTriangle.pascal(5); - int[][] expected = {{1, 0, 0, 0, 0}, - {1, 1, 0, 0, 0}, - {1, 2, 1, 0, 0}, - {1, 3, 3, 1, 0}, - {1, 4, 6, 4, 1} + int[][] expected = { + { 1, 0, 0, 0, 0 }, + { 1, 1, 0, 0, 0 }, + { 1, 2, 1, 0, 0 }, + { 1, 3, 3, 1, 0 }, + { 1, 4, 6, 4, 1 }, }; assertArrayEquals(result, expected); } @@ -35,14 +36,15 @@ void testForFive() { @Test void testForEight() { int[][] result = PascalTriangle.pascal(8); - int[][] expected = {{1, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 0, 0, 0, 0, 0, 0}, - {1, 2, 1, 0, 0, 0, 0, 0}, - {1, 3, 3, 1, 0, 0, 0, 0}, - {1, 4, 6, 4, 1, 0, 0, 0}, - {1, 5, 10, 10, 5, 1, 0, 0}, - {1, 6, 15, 20, 15, 6, 1, 0}, - {1, 7, 21, 35, 35, 21, 7, 1} + int[][] expected = { + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 2, 1, 0, 0, 0, 0, 0 }, + { 1, 3, 3, 1, 0, 0, 0, 0 }, + { 1, 4, 6, 4, 1, 0, 0, 0 }, + { 1, 5, 10, 10, 5, 1, 0, 0 }, + { 1, 6, 15, 20, 15, 6, 1, 0 }, + { 1, 7, 21, 35, 35, 21, 7, 1 }, }; assertArrayEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java index 70f637363984..481260c9f1c9 100644 --- a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java +++ b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java @@ -1,37 +1,38 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +public class PerfectSquareTest { + + @Test + public void TestPerfectSquareifiscorrect() { + //Valid Partition + int number = 9; + + boolean result = PerfectSquare.isPerfectSquare(number); + + assertTrue(result); + } + + @Test + public void TestPerfectSquareifisnotcorrect() { + //Invalid Partition 1 + int number = 3; + + boolean result = PerfectSquare.isPerfectSquare(number); + + assertFalse(result); + } + + @Test + public void TestPerfectSquareifisNegativeNumber() { + //Invalid Partition 2 + int number = -10; + + boolean result = PerfectSquare.isPerfectSquare(number); -public class PerfectSquareTest{ - - @Test - public void TestPerfectSquareifiscorrect(){ - //Valid Partition - int number = 9; - - boolean result = PerfectSquare.isPerfectSquare(number); - - assertTrue(result); - } - - @Test - public void TestPerfectSquareifisnotcorrect(){ - //Invalid Partition 1 - int number = 3; - - boolean result = PerfectSquare.isPerfectSquare(number); - - assertFalse(result); - } - @Test - public void TestPerfectSquareifisNegativeNumber(){ - //Invalid Partition 2 - int number = -10; - - boolean result = PerfectSquare.isPerfectSquare(number); - - assertFalse(result); - } + assertFalse(result); + } } diff --git a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java index 757ababaf0df..d5d51600850c 100644 --- a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java +++ b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java @@ -7,45 +7,48 @@ class PollardRhoTest { - @Test - void testPollardRhoForNumber315MustReturn5() { - //given - int number = 315; - int expectedResult = 5; - - //when - int actualResult = PollardRho.pollardRho(number); - - //then - assertEquals(expectedResult, actualResult); - } - - @Test - void testPollardRhoForNumber187MustReturn11() { - //given - int number = 187; - int expectedResult = 11; - - //when - int actualResult = PollardRho.pollardRho(number); - - //then - assertEquals(expectedResult, actualResult); - } - - @Test - void testPollardRhoForNumber239MustThrowException() { - //given - int number = 239; - String expectedMessage = "GCD cannot be found."; - - //when - Exception exception = assertThrows(RuntimeException.class, () -> { - PollardRho.pollardRho(number); - }); - String actualMessage = exception.getMessage(); - - //then - assertEquals(expectedMessage, actualMessage); - } + @Test + void testPollardRhoForNumber315MustReturn5() { + //given + int number = 315; + int expectedResult = 5; + + //when + int actualResult = PollardRho.pollardRho(number); + + //then + assertEquals(expectedResult, actualResult); + } + + @Test + void testPollardRhoForNumber187MustReturn11() { + //given + int number = 187; + int expectedResult = 11; + + //when + int actualResult = PollardRho.pollardRho(number); + + //then + assertEquals(expectedResult, actualResult); + } + + @Test + void testPollardRhoForNumber239MustThrowException() { + //given + int number = 239; + String expectedMessage = "GCD cannot be found."; + + //when + Exception exception = assertThrows( + RuntimeException.class, + () -> { + PollardRho.pollardRho(number); + } + ); + String actualMessage = exception.getMessage(); + + //then + assertEquals(expectedMessage, actualMessage); + } } diff --git a/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java b/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java index 59fe78525346..c3e1634c51fe 100644 --- a/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java +++ b/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; public class PrimeCheckTest { + @Test void test1() { Assertions.assertTrue(PrimeCheck.isPrime(2)); diff --git a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java index 3f21a515fb53..2a1f6f6e01b9 100644 --- a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java +++ b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java @@ -3,34 +3,33 @@ import static org.junit.jupiter.api.Assertions.*; import java.util.List; - import org.junit.jupiter.api.Test; class PrimeFactorizationTest { - @Test - void testpFactorsMustReturnEmptyList() { - //given - int n = 0; - - //then - assertTrue(PrimeFactorization.pfactors(n).isEmpty()); - } - - @Test - void testpFactorsMustReturnNonEmptyList() { - //given - int n = 198; - int expectedListSize = 4; - - //when - List actualResultList = PrimeFactorization.pfactors(n); - - //then - assertEquals(expectedListSize, actualResultList.size()); - assertEquals(2, actualResultList.get(0)); - assertEquals(3, actualResultList.get(1)); - assertEquals(3, actualResultList.get(2)); - assertEquals(11, actualResultList.get(3)); - } + @Test + void testpFactorsMustReturnEmptyList() { + //given + int n = 0; + + //then + assertTrue(PrimeFactorization.pfactors(n).isEmpty()); + } + + @Test + void testpFactorsMustReturnNonEmptyList() { + //given + int n = 198; + int expectedListSize = 4; + + //when + List actualResultList = PrimeFactorization.pfactors(n); + + //then + assertEquals(expectedListSize, actualResultList.size()); + assertEquals(2, actualResultList.get(0)); + assertEquals(3, actualResultList.get(1)); + assertEquals(3, actualResultList.get(2)); + assertEquals(11, actualResultList.get(3)); + } } diff --git a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java index 9c735c6b8966..36a72c7ea138 100644 --- a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java @@ -1,34 +1,32 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class PronicNumberTest { @Test void testForPronicNumber() { - //given int number = 30; //when boolean result = PronicNumber.isPronic(number); - + //then assertTrue(result); } @Test void testForNonPronicNumber() { - //given int number = 21; //when boolean result = PronicNumber.isPronic(number); - + //then assertFalse(result); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java b/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java index b0d88da66223..2dc2643c5878 100644 --- a/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java +++ b/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java @@ -1,20 +1,21 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class PythagoreanTripleTest { + @Test - public void Testpythagoreantriple(){ - - assertEquals(true, PythagoreanTriple.isPythagTriple(3,4,5)); - assertEquals(true, PythagoreanTriple.isPythagTriple(6,8,10)); - assertEquals(true, PythagoreanTriple.isPythagTriple(9,12,15)); - assertEquals(true, PythagoreanTriple.isPythagTriple(12,16,20)); - assertEquals(true, PythagoreanTriple.isPythagTriple(15,20,25)); - assertEquals(true, PythagoreanTriple.isPythagTriple(18,24,30)); - assertEquals(false, PythagoreanTriple.isPythagTriple(5,20,30)); - assertEquals(false, PythagoreanTriple.isPythagTriple(6,8,100)); - assertEquals(false, PythagoreanTriple.isPythagTriple(-2,-2,2)); + public void Testpythagoreantriple() { + assertEquals(true, PythagoreanTriple.isPythagTriple(3, 4, 5)); + assertEquals(true, PythagoreanTriple.isPythagTriple(6, 8, 10)); + assertEquals(true, PythagoreanTriple.isPythagTriple(9, 12, 15)); + assertEquals(true, PythagoreanTriple.isPythagTriple(12, 16, 20)); + assertEquals(true, PythagoreanTriple.isPythagTriple(15, 20, 25)); + assertEquals(true, PythagoreanTriple.isPythagTriple(18, 24, 30)); + assertEquals(false, PythagoreanTriple.isPythagTriple(5, 20, 30)); + assertEquals(false, PythagoreanTriple.isPythagTriple(6, 8, 100)); + assertEquals(false, PythagoreanTriple.isPythagTriple(-2, -2, 2)); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java index 0158ff35ad2b..36fbba375793 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java @@ -1,23 +1,31 @@ package com.thealgorithms.maths; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class SquareRootWithNewtonRaphsonTestMethod -{ +public class SquareRootWithNewtonRaphsonTestMethod { + @Test - void testfor1(){ - Assertions.assertEquals(1,SquareRootWithNewtonRaphsonMethod.squareRoot(1)); + void testfor1() { + Assertions.assertEquals( + 1, + SquareRootWithNewtonRaphsonMethod.squareRoot(1) + ); } @Test - void testfor2(){ - Assertions.assertEquals(1.414213562373095,SquareRootWithNewtonRaphsonMethod.squareRoot(2)); + void testfor2() { + Assertions.assertEquals( + 1.414213562373095, + SquareRootWithNewtonRaphsonMethod.squareRoot(2) + ); } @Test - void testfor625(){ - Assertions.assertEquals(25.0,SquareRootWithNewtonRaphsonMethod.squareRoot(625)); + void testfor625() { + Assertions.assertEquals( + 25.0, + SquareRootWithNewtonRaphsonMethod.squareRoot(625) + ); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java index e5a1c27b985b..7e8d916c6aa1 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java @@ -4,23 +4,36 @@ import org.junit.jupiter.api.Test; public class SquareRootwithBabylonianMethodTest { + @Test - void testfor4(){ - Assertions.assertEquals(2,SquareRootWithBabylonianMethod.square_Root(4)); + void testfor4() { + Assertions.assertEquals( + 2, + SquareRootWithBabylonianMethod.square_Root(4) + ); } @Test - void testfor1(){ - Assertions.assertEquals(1,SquareRootWithBabylonianMethod.square_Root(1)); + void testfor1() { + Assertions.assertEquals( + 1, + SquareRootWithBabylonianMethod.square_Root(1) + ); } @Test - void testfor2(){ - Assertions.assertEquals(1.4142135381698608,SquareRootWithBabylonianMethod.square_Root(2)); + void testfor2() { + Assertions.assertEquals( + 1.4142135381698608, + SquareRootWithBabylonianMethod.square_Root(2) + ); } @Test - void testfor625(){ - Assertions.assertEquals(25,SquareRootWithBabylonianMethod.square_Root(625)); + void testfor625() { + Assertions.assertEquals( + 25, + SquareRootWithBabylonianMethod.square_Root(625) + ); } } diff --git a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java index 5a77376028b5..192b686c1d2a 100644 --- a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java @@ -3,30 +3,44 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class StandardDeviationTest{ - @Test - void test1() - { - double[] t1 = new double[]{1,1,1,1,1}; - Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); - } - @Test - void test2() - { - double[] t2 = new double[]{1,2,3,4,5,6,7,8,9,10}; - Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143); - } - @Test - void test3() - { - double[] t3= new double[]{1.1, 8.5, 20.3, 2.4, 6.2}; - Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265); - } - @Test - void test4() - { - double[] t4 = new double[]{3.14, 2.22222, 9.89898989, 100.00045, 56.7}; - Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775); - } +public class StandardDeviationTest { + + @Test + void test1() { + double[] t1 = new double[] { 1, 1, 1, 1, 1 }; + Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); + } + + @Test + void test2() { + double[] t2 = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + Assertions.assertEquals( + StandardDeviation.stdDev(t2), + 2.8722813232690143 + ); + } + + @Test + void test3() { + double[] t3 = new double[] { 1.1, 8.5, 20.3, 2.4, 6.2 }; + Assertions.assertEquals( + StandardDeviation.stdDev(t3), + 6.8308125431752265 + ); + } + + @Test + void test4() { + double[] t4 = new double[] { + 3.14, + 2.22222, + 9.89898989, + 100.00045, + 56.7, + }; + Assertions.assertEquals( + StandardDeviation.stdDev(t4), + 38.506117353865775 + ); + } } - diff --git a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java index 3ff05007fc66..b2a0dc608c88 100644 --- a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java @@ -3,25 +3,28 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class StandardScoreTest{ - @Test - void test1() - { - Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4); - } - @Test - void test2() - { - Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0); - } - @Test - void test3() - { - Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0); - } - @Test - void test4() - { - Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049); - } +public class StandardScoreTest { + + @Test + void test1() { + Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4); + } + + @Test + void test2() { + Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0); + } + + @Test + void test3() { + Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0); + } + + @Test + void test4() { + Assertions.assertEquals( + StandardScore.zScore(8.9, 3, 4.2), + 1.4047619047619049 + ); + } } diff --git a/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java index 2d4ff15627ab..99c03cfae720 100644 --- a/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java +++ b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java @@ -1,31 +1,31 @@ -package com.thealgorithms.maths; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class SumOfDigitsTest { - - SumOfDigits SoD = new SumOfDigits(); - - @Test - void testZero() { - assertEquals(0, SoD.sumOfDigits(0)); - assertEquals(0, SoD.sumOfDigitsRecursion(0)); - assertEquals(0, SoD.sumOfDigitsFast(0)); - } - - @Test - void testPositive() { - assertEquals(15, SoD.sumOfDigits(12345)); - assertEquals(15, SoD.sumOfDigitsRecursion(12345)); - assertEquals(15, SoD.sumOfDigitsFast(12345)); - } - - @Test - void testNegative() { - assertEquals(6, SoD.sumOfDigits(-123)); - assertEquals(6, SoD.sumOfDigitsRecursion(-123)); - assertEquals(6, SoD.sumOfDigitsFast(-123)); - } -} \ No newline at end of file +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class SumOfDigitsTest { + + SumOfDigits SoD = new SumOfDigits(); + + @Test + void testZero() { + assertEquals(0, SoD.sumOfDigits(0)); + assertEquals(0, SoD.sumOfDigitsRecursion(0)); + assertEquals(0, SoD.sumOfDigitsFast(0)); + } + + @Test + void testPositive() { + assertEquals(15, SoD.sumOfDigits(12345)); + assertEquals(15, SoD.sumOfDigitsRecursion(12345)); + assertEquals(15, SoD.sumOfDigitsFast(12345)); + } + + @Test + void testNegative() { + assertEquals(6, SoD.sumOfDigits(-123)); + assertEquals(6, SoD.sumOfDigitsRecursion(-123)); + assertEquals(6, SoD.sumOfDigitsFast(-123)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/TestArmstrong.java b/src/test/java/com/thealgorithms/maths/TestArmstrong.java index afc1ff8a4b61..60f4f2431189 100644 --- a/src/test/java/com/thealgorithms/maths/TestArmstrong.java +++ b/src/test/java/com/thealgorithms/maths/TestArmstrong.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; + public class TestArmstrong { @Test diff --git a/src/test/java/com/thealgorithms/maths/perimeterTest.java b/src/test/java/com/thealgorithms/maths/perimeterTest.java index bbb228d80717..5ace172657db 100644 --- a/src/test/java/com/thealgorithms/maths/perimeterTest.java +++ b/src/test/java/com/thealgorithms/maths/perimeterTest.java @@ -7,31 +7,34 @@ public class perimeterTest { //Perimeter of polygon @Test - void testcase1(){ - Assertions.assertEquals(20.0,Perimeter.perimeter_polygon(4,5)); + void testcase1() { + Assertions.assertEquals(20.0, Perimeter.perimeter_polygon(4, 5)); } + @Test - void testcase2(){ - Assertions.assertEquals(30.0,Perimeter.perimeter_polygon(5,6)); + void testcase2() { + Assertions.assertEquals(30.0, Perimeter.perimeter_polygon(5, 6)); } //Perimeter of Rectangle @Test - void testcase3(){ - Assertions.assertEquals(18.0,Perimeter.perimeter_rectangle(4,5)); + void testcase3() { + Assertions.assertEquals(18.0, Perimeter.perimeter_rectangle(4, 5)); } + @Test - void testcase4(){ - Assertions.assertEquals(14.0,Perimeter.perimeter_rectangle(4,3)); + void testcase4() { + Assertions.assertEquals(14.0, Perimeter.perimeter_rectangle(4, 3)); } //Circumference of a circle @Test - void testcase5(){ - Assertions.assertEquals(31.41592653589793,Perimeter.circumference(5)); + void testcase5() { + Assertions.assertEquals(31.41592653589793, Perimeter.circumference(5)); } + @Test - void testcase6(){ - Assertions.assertEquals(43.982297150257104,Perimeter.circumference(7)); + void testcase6() { + Assertions.assertEquals(43.982297150257104, Perimeter.circumference(7)); } } diff --git a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java index 773a5aabf5dc..ef350ffbeece 100644 --- a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java +++ b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java @@ -1,48 +1,47 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class ArrayLeftRotationTest { - @Test - void testForOneElement() { - int[] arr = {3}; - int[] result = ArrayLeftRotation.rotateLeft(arr, 3); - assertArrayEquals(arr, result); - } - - @Test - void testForZeroStep() { - int[] arr = {3, 1, 5, 8, 6}; - int[] result = ArrayLeftRotation.rotateLeft(arr, 0); - assertArrayEquals(arr, result); - } - - @Test - void testForEqualSizeStep() { - int[] arr = {3, 1, 5, 8, 6}; - int[] result = ArrayLeftRotation.rotateLeft(arr, 5); - assertArrayEquals(arr, result); - } - - @Test - void testForLowerSizeStep() { - int[] arr = {3, 1, 5, 8, 6}; - int n = 2; - int[] expected = {5, 8, 6, 3, 1}; - int[] result = ArrayLeftRotation.rotateLeft(arr, n); - assertArrayEquals(expected, result); - } - - @Test - void testForHigherSizeStep() { - int[] arr = {3, 1, 5, 8, 6}; - int n = 7; - int[] expected = {5, 8, 6, 3, 1}; - int[] result = ArrayLeftRotation.rotateLeft(arr, n); - assertArrayEquals(expected, result); - } - -} \ No newline at end of file + @Test + void testForOneElement() { + int[] arr = { 3 }; + int[] result = ArrayLeftRotation.rotateLeft(arr, 3); + assertArrayEquals(arr, result); + } + + @Test + void testForZeroStep() { + int[] arr = { 3, 1, 5, 8, 6 }; + int[] result = ArrayLeftRotation.rotateLeft(arr, 0); + assertArrayEquals(arr, result); + } + + @Test + void testForEqualSizeStep() { + int[] arr = { 3, 1, 5, 8, 6 }; + int[] result = ArrayLeftRotation.rotateLeft(arr, 5); + assertArrayEquals(arr, result); + } + + @Test + void testForLowerSizeStep() { + int[] arr = { 3, 1, 5, 8, 6 }; + int n = 2; + int[] expected = { 5, 8, 6, 3, 1 }; + int[] result = ArrayLeftRotation.rotateLeft(arr, n); + assertArrayEquals(expected, result); + } + + @Test + void testForHigherSizeStep() { + int[] arr = { 3, 1, 5, 8, 6 }; + int n = 7; + int[] expected = { 5, 8, 6, 3, 1 }; + int[] result = ArrayLeftRotation.rotateLeft(arr, n); + assertArrayEquals(expected, result); + } +} diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java index ecc66da69c33..35f1ef7ec399 100644 --- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java @@ -1,76 +1,69 @@ package com.thealgorithms.others; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * author Alexandros Lemonaris */ class BestFitCPUTest { - int [] sizeOfBlocks; - int [] sizeOfProcesses; + + int[] sizeOfBlocks; + int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); - ArrayList testMemAllocation ; - MemoryManagementAlgorithms bestFit = new BestFitCPU(); + ArrayList testMemAllocation; + MemoryManagementAlgorithms bestFit = new BestFitCPU(); @Test void testFitForUseOfOneBlock() { //test1 - 2 processes shall fit to one block instead of using a different block each - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 5, 15, 2}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 5, 15, 2 }; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(3, 0, 2, 2) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(3, 0, 2, 2)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForEqualProcecesses() { //test2 - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 10, 10, 10}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 10, 10, 10 }; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(3, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(3, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForNoEmptyBlockCell() { //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 12, 10, 7}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 12, 10, 7 }; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, 2) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForSameInputDifferentQuery() { //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 7, 10, 12}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 7, 10, 12 }; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForMoreBlocksNoFit() { //test5 for more blocks than processes - sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; - sizeOfProcesses = new int [] {10, 11}; + sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; + sizeOfProcesses = new int[] { 10, 11 }; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList( -255, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java index c5a02822605e..00cc1f534191 100644 --- a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java +++ b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java @@ -1,56 +1,58 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; + import com.thealgorithms.datastructures.stacks.CalculateMaxOfMin; +import org.junit.jupiter.api.Test; public class CalculateMaxOfMinTest { - @Test - void testForOneElement() { - int a[] = { 10, 20, 30, 50, 10, 70, 30 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 70); - } - - @Test - void testForTwoElements() { - int a[] = { 5, 3, 2, 6, 3, 2, 6 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 6); - } - - @Test - void testForThreeElements() { - int a[] = { 10, 10, 10, 10, 10, 10, 10 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 10); - } - - @Test - void testForFourElements() { - int a[] = { 70, 60, 50, 40, 30, 20 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 70); - } - - @Test - void testForFiveElements() { - int a[] = { 50 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 50); - } - - @Test - void testForSixElements() { - int a[] = { 1, 4, 7, 9, 2, 4, 6 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == 9); - } - - @Test - void testForSevenElements() { - int a[] = { -1, -5, -7, -9, -12, -14 }; - int k = CalculateMaxOfMin.calculateMaxOfMin(a); - assertTrue(k == -1); - } -} \ No newline at end of file + + @Test + void testForOneElement() { + int a[] = { 10, 20, 30, 50, 10, 70, 30 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 70); + } + + @Test + void testForTwoElements() { + int a[] = { 5, 3, 2, 6, 3, 2, 6 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 6); + } + + @Test + void testForThreeElements() { + int a[] = { 10, 10, 10, 10, 10, 10, 10 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 10); + } + + @Test + void testForFourElements() { + int a[] = { 70, 60, 50, 40, 30, 20 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 70); + } + + @Test + void testForFiveElements() { + int a[] = { 50 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 50); + } + + @Test + void testForSixElements() { + int a[] = { 1, 4, 7, 9, 2, 4, 6 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == 9); + } + + @Test + void testForSevenElements() { + int a[] = { -1, -5, -7, -9, -12, -14 }; + int k = CalculateMaxOfMin.calculateMaxOfMin(a); + assertTrue(k == -1); + } +} diff --git a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java index 1e1d2111240e..681573bb7eca 100644 --- a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java +++ b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java @@ -1,62 +1,57 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.dynamicprogramming.CountFriendsPairing; +import org.junit.jupiter.api.Test; + public class CountFriendsPairingTest { + + @Test + void testForOneElement() { + int a[] = { 1, 2, 2 }; + assertTrue(CountFriendsPairing.countFriendsPairing(3, a)); + } + + @Test + void testForTwoElements() { + int a[] = { 1, 2, 2, 3 }; + assertTrue(CountFriendsPairing.countFriendsPairing(4, a)); + } + + @Test + void testForThreeElements() { + int a[] = { 1, 2, 2, 3, 3 }; + assertTrue(CountFriendsPairing.countFriendsPairing(5, a)); + } + @Test - void testForOneElement() - { - int a[] = {1,2,2}; - assertTrue(CountFriendsPairing.countFriendsPairing(3,a)); - } - - @Test - void testForTwoElements() - { - int a[] = {1,2,2,3}; - assertTrue(CountFriendsPairing.countFriendsPairing(4,a)); - } - - @Test - void testForThreeElements() - { - int a[] = {1,2,2,3,3}; - assertTrue(CountFriendsPairing.countFriendsPairing(5,a)); - } - - @Test - void testForFourElements() - { - int a[] = {1,2,2,3,3,4}; - assertTrue(CountFriendsPairing.countFriendsPairing(6,a)); - } - - @Test - void testForFiveElements() - { - int a[] = {1,2,2,3,3,4,4}; - assertTrue(CountFriendsPairing.countFriendsPairing(7,a)); - } - - @Test - void testForSixElements() - { - int a[] = {1,2,2,3,3,4,4,4}; - assertTrue(CountFriendsPairing.countFriendsPairing(8,a)); - } - - @Test - void testForSevenElements() - { - int a[] = {1,2,2,3,3,4,4,4,5}; - assertTrue(CountFriendsPairing.countFriendsPairing(9,a)); - } - - @Test - void testForEightElements() - { - int a[] = {1,2,2,3,3,4,4,4,5,5}; - assertTrue(CountFriendsPairing.countFriendsPairing(10,a)); - } -} \ No newline at end of file + void testForFourElements() { + int a[] = { 1, 2, 2, 3, 3, 4 }; + assertTrue(CountFriendsPairing.countFriendsPairing(6, a)); + } + + @Test + void testForFiveElements() { + int a[] = { 1, 2, 2, 3, 3, 4, 4 }; + assertTrue(CountFriendsPairing.countFriendsPairing(7, a)); + } + + @Test + void testForSixElements() { + int a[] = { 1, 2, 2, 3, 3, 4, 4, 4 }; + assertTrue(CountFriendsPairing.countFriendsPairing(8, a)); + } + + @Test + void testForSevenElements() { + int a[] = { 1, 2, 2, 3, 3, 4, 4, 4, 5 }; + assertTrue(CountFriendsPairing.countFriendsPairing(9, a)); + } + + @Test + void testForEightElements() { + int a[] = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 }; + assertTrue(CountFriendsPairing.countFriendsPairing(10, a)); + } +} diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java index 18dae6807c0e..33b77350e077 100644 --- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java @@ -1,76 +1,69 @@ package com.thealgorithms.others; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * author Alexandros Lemonaris */ class FirstFitCPUTest { - int [] sizeOfBlocks; - int [] sizeOfProcesses; + + int[] sizeOfBlocks; + int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); - ArrayList testMemAllocation ; - MemoryManagementAlgorithms firstFit = new FirstFitCPU(); + ArrayList testMemAllocation; + MemoryManagementAlgorithms firstFit = new FirstFitCPU(); @Test void testFitForUseOfOneBlock() { //test1 - no use of one block for two processes - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 5, 15, 2}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 5, 15, 2 }; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(1, 0, 2, 1) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(1, 0, 2, 1)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForEqualProcecesses() { //test2 - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 10, 10, 10}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 10, 10, 10 }; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(1, 2, 3, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForNoEmptyBlockCell() { //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 12, 10, 7}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 12, 10, 7 }; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, 2) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForSameInputDifferentQuery() { //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 7, 10, 12}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 7, 10, 12 }; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForMoreBlocksNoFit() { //test5 for more blocks than processes - sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; - sizeOfProcesses = new int [] {10, 11}; + sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; + sizeOfProcesses = new int[] { 10, 11 }; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList( -255, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java index a4934b7ebb88..d740f01cc942 100644 --- a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java +++ b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java @@ -1,63 +1,57 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.dynamicprogramming.KadaneAlgorithm; +import org.junit.jupiter.api.Test; + public class KadaneAlogrithmTest { + + @Test + void testForOneElement() { + int a[] = { -1 }; + assertTrue(KadaneAlgorithm.max_Sum(a, -1)); + } + + @Test + void testForTwoElements() { + int a[] = { -2, 1 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 1)); + } + + @Test + void testForThreeElements() { + int a[] = { 5, 3, 12 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 20)); + } + @Test - void testForOneElement() - { - int a[]={-1}; - assertTrue(KadaneAlgorithm.max_Sum(a,-1)); - } - - @Test - void testForTwoElements() - { - int a[]={-2,1}; - assertTrue(KadaneAlgorithm.max_Sum(a,1)); - } - - @Test - void testForThreeElements() - { - int a[]={5,3,12}; - assertTrue(KadaneAlgorithm.max_Sum(a,20)); - } - - @Test - void testForFourElements() - { - int a[]={-1,-3,-7,-4}; - assertTrue(KadaneAlgorithm.max_Sum(a,-1)); - } - - @Test - void testForFiveElements() - { - int a[]={4,5,3,0,2}; - assertTrue(KadaneAlgorithm.max_Sum(a,14)); - } - - - @Test - void testForSixElements() - { - int a[]={-43,-45,47,12,87,-13}; - assertTrue(KadaneAlgorithm.max_Sum(a,146)); - } - - @Test - void testForSevenElements() - { - int a[]={9,8,2,23,13,6,7}; - assertTrue(KadaneAlgorithm.max_Sum(a,68)); - } - - @Test - void testForEightElements() - { - int a[]={9,-5,-5,-2,4,5,0,1}; - assertTrue(KadaneAlgorithm.max_Sum(a,10)); - } -} \ No newline at end of file + void testForFourElements() { + int a[] = { -1, -3, -7, -4 }; + assertTrue(KadaneAlgorithm.max_Sum(a, -1)); + } + + @Test + void testForFiveElements() { + int a[] = { 4, 5, 3, 0, 2 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 14)); + } + + @Test + void testForSixElements() { + int a[] = { -43, -45, 47, 12, 87, -13 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 146)); + } + + @Test + void testForSevenElements() { + int a[] = { 9, 8, 2, 23, 13, 6, 7 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 68)); + } + + @Test + void testForEightElements() { + int a[] = { 9, -5, -5, -2, 4, 5, 0, 1 }; + assertTrue(KadaneAlgorithm.max_Sum(a, 10)); + } +} diff --git a/src/test/java/com/thealgorithms/others/LinkListSortTest.java b/src/test/java/com/thealgorithms/others/LinkListSortTest.java index cd23997578fa..b5e985aad0aa 100644 --- a/src/test/java/com/thealgorithms/others/LinkListSortTest.java +++ b/src/test/java/com/thealgorithms/others/LinkListSortTest.java @@ -1,64 +1,57 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.sorts.LinkList_Sort; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; public class LinkListSortTest { - @Test - void testForOneElement() - { - int a[]={56}; - assertTrue(LinkList_Sort.isSorted(a,2)); - } - @Test - void testForTwoElements() - { - int a[]={6,4}; - assertTrue(LinkList_Sort.isSorted(a,1)); - } + @Test + void testForOneElement() { + int a[] = { 56 }; + assertTrue(LinkList_Sort.isSorted(a, 2)); + } - @Test - void testForThreeElements() - { - int a[]={875,253,12}; - assertTrue(LinkList_Sort.isSorted(a,3)); - } + @Test + void testForTwoElements() { + int a[] = { 6, 4 }; + assertTrue(LinkList_Sort.isSorted(a, 1)); + } - @Test - void testForFourElements() - { - int a[]={86,32,87,13}; - assertTrue(LinkList_Sort.isSorted(a,1)); - } + @Test + void testForThreeElements() { + int a[] = { 875, 253, 12 }; + assertTrue(LinkList_Sort.isSorted(a, 3)); + } - @Test - void testForFiveElements() - { - int a[]={6,5,3,0,9}; - assertTrue(LinkList_Sort.isSorted(a,1)); - } + @Test + void testForFourElements() { + int a[] = { 86, 32, 87, 13 }; + assertTrue(LinkList_Sort.isSorted(a, 1)); + } + @Test + void testForFiveElements() { + int a[] = { 6, 5, 3, 0, 9 }; + assertTrue(LinkList_Sort.isSorted(a, 1)); + } - @Test - void testForSixElements() - { - int a[]={9,65,432,32,47,327}; - assertTrue(LinkList_Sort.isSorted(a,3)); - } + @Test + void testForSixElements() { + int a[] = { 9, 65, 432, 32, 47, 327 }; + assertTrue(LinkList_Sort.isSorted(a, 3)); + } - @Test - void testForSevenElements() - { - int a[]={6,4,2,1,3,6,7}; - assertTrue(LinkList_Sort.isSorted(a,1)); + @Test + void testForSevenElements() { + int a[] = { 6, 4, 2, 1, 3, 6, 7 }; + assertTrue(LinkList_Sort.isSorted(a, 1)); } - @Test - void testForEightElements() - { - int a[]={123,234,145,764,322,367,768,34}; - assertTrue(LinkList_Sort.isSorted(a,2)); - } + @Test + void testForEightElements() { + int a[] = { 123, 234, 145, 764, 322, 367, 768, 34 }; + assertTrue(LinkList_Sort.isSorted(a, 2)); + } } diff --git a/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java b/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java index 134f4fbdf76f..660562a5506e 100644 --- a/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java +++ b/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java @@ -1,55 +1,49 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.dynamicprogramming.NewManShanksPrime; +import org.junit.jupiter.api.Test; + public class NewManShanksPrimeTest { + + @Test + void testOne() { + assertTrue(NewManShanksPrime.nthManShanksPrime(1, 1)); + } + + @Test + void testTwo() { + assertTrue(NewManShanksPrime.nthManShanksPrime(2, 3)); + } + + @Test + void testThree() { + assertTrue(NewManShanksPrime.nthManShanksPrime(3, 7)); + } + @Test - void testOne() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(1,1)); - } - - @Test - void testTwo() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(2,3)); - } - - @Test - void testThree() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(3,7)); - } - - @Test - void testFour() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(4,17)); - } - - @Test - void testFive() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(5,41)); - } - - @Test - void testSix() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(6,99)); - } - - @Test - void testSeven() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(7,239)); - } - - @Test - void testEight() - { - assertTrue(NewManShanksPrime.nthManShanksPrime(8,577)); - } - -} \ No newline at end of file + void testFour() { + assertTrue(NewManShanksPrime.nthManShanksPrime(4, 17)); + } + + @Test + void testFive() { + assertTrue(NewManShanksPrime.nthManShanksPrime(5, 41)); + } + + @Test + void testSix() { + assertTrue(NewManShanksPrime.nthManShanksPrime(6, 99)); + } + + @Test + void testSeven() { + assertTrue(NewManShanksPrime.nthManShanksPrime(7, 239)); + } + + @Test + void testEight() { + assertTrue(NewManShanksPrime.nthManShanksPrime(8, 577)); + } +} diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java index 5a9206df7b3b..bd1df90717aa 100644 --- a/src/test/java/com/thealgorithms/others/NextFitTest.java +++ b/src/test/java/com/thealgorithms/others/NextFitTest.java @@ -1,76 +1,69 @@ package com.thealgorithms.others; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * author Alexandros Lemonaris */ class NextFitCPUTest { - int [] sizeOfBlocks; - int [] sizeOfProcesses; + + int[] sizeOfBlocks; + int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); - ArrayList testMemAllocation ; - MemoryManagementAlgorithms nextFit = new NextFit(); + ArrayList testMemAllocation; + MemoryManagementAlgorithms nextFit = new NextFit(); @Test void testFitForUseOfOneBlock() { //test1 - third process does not fit because of algorithms procedure - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 5, 15, 2}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 5, 15, 2 }; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(1, 2, -255, 2) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, -255, 2)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForEqualProcecesses() { //test2 - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 10, 10, 10}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 10, 10, 10 }; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(1, 2, 3, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForNoEmptyBlockCell() { //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 12, 10, 7}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 12, 10, 7 }; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, 2) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForSameInputDifferentQuery() { //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 7, 10, 12}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 7, 10, 12 }; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(0, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForMoreBlocksNoFit() { //test5 for more blocks than processes - sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; - sizeOfProcesses = new int [] {10, 11}; + sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; + sizeOfProcesses = new int[] { 10, 11 }; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList( -255, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java index 31076898f70d..3bdcc9553231 100644 --- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java +++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java @@ -1,37 +1,43 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class PasswordGenTest { - @Test + + @Test public void failGenerationWithSameMinMaxLengthTest() { int length = 10; - assertThrows(IllegalArgumentException.class, ()-> { - PasswordGen.generatePassword(length, length); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + PasswordGen.generatePassword(length, length); + } + ); } @Test public void generateOneCharacterPassword() { String tempPassword = PasswordGen.generatePassword(1, 2); - assertTrue(tempPassword.length()==1); + assertTrue(tempPassword.length() == 1); } @Test public void failGenerationWithMinLengthSmallerThanMaxLengthTest() { int minLength = 10; int maxLength = 5; - assertThrows(IllegalArgumentException.class, ()-> { - PasswordGen.generatePassword(minLength, maxLength); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + PasswordGen.generatePassword(minLength, maxLength); + } + ); } @Test public void generatePasswordNonEmptyTest() { String tempPassword = PasswordGen.generatePassword(8, 16); - assertTrue(tempPassword.length()!=0); + assertTrue(tempPassword.length() != 0); } } diff --git a/src/test/java/com/thealgorithms/others/UniquePathsTests.java b/src/test/java/com/thealgorithms/others/UniquePathsTests.java index 5b147581844f..42a11c441dc7 100644 --- a/src/test/java/com/thealgorithms/others/UniquePathsTests.java +++ b/src/test/java/com/thealgorithms/others/UniquePathsTests.java @@ -1,56 +1,49 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.dynamicprogramming.UniquePaths; - +import org.junit.jupiter.api.Test; public class UniquePathsTests { + + @Test + void testForOneElement() { + assertTrue(UniquePaths.uniquePaths(3, 7, 28)); + } + + @Test + void testForTwoElements() { + assertTrue(UniquePaths.uniquePaths(3, 2, 3)); + } + + @Test + void testForThreeElements() { + assertTrue(UniquePaths.uniquePaths(3, 3, 6)); + } + @Test - void testForOneElement() - { - assertTrue(UniquePaths.uniquePaths(3,7,28)); - } - - @Test - void testForTwoElements() - { - assertTrue(UniquePaths.uniquePaths(3,2,3)); - } - - @Test - void testForThreeElements() - { - assertTrue(UniquePaths.uniquePaths(3,3,6)); - } - - @Test - void testForFourElements() - { - assertTrue(UniquePaths.uniquePaths(4,6,56)); - } - - @Test - void testForFiveElements() - { - assertTrue(UniquePaths.uniquePaths2(3,5,15)); - } - - @Test - void testForSixElements() - { - assertTrue(UniquePaths.uniquePaths2(6,2,6)); - } - - @Test - void testForSevenElements() - { - assertTrue(UniquePaths.uniquePaths2(5,9,495)); - } - - @Test - void testForEightElements() - { - assertTrue(UniquePaths.uniquePaths2(4,8,120)); - } -} \ No newline at end of file + void testForFourElements() { + assertTrue(UniquePaths.uniquePaths(4, 6, 56)); + } + + @Test + void testForFiveElements() { + assertTrue(UniquePaths.uniquePaths2(3, 5, 15)); + } + + @Test + void testForSixElements() { + assertTrue(UniquePaths.uniquePaths2(6, 2, 6)); + } + + @Test + void testForSevenElements() { + assertTrue(UniquePaths.uniquePaths2(5, 9, 495)); + } + + @Test + void testForEightElements() { + assertTrue(UniquePaths.uniquePaths2(4, 8, 120)); + } +} diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java index 5e9e2a78347e..5d27d0de1805 100644 --- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java @@ -1,87 +1,80 @@ package com.thealgorithms.others; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * author Alexandros Lemonaris */ class WorstFitCPUTest { - int [] sizeOfBlocks; - int [] sizeOfProcesses; + + int[] sizeOfBlocks; + int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); - ArrayList testMemAllocation ; - MemoryManagementAlgorithms worstFit = new WorstFitCPU(); + ArrayList testMemAllocation; + MemoryManagementAlgorithms worstFit = new WorstFitCPU(); @Test void testFitForUseOfOneBlock() { //test1 - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 5, 15, 2}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 5, 15, 2 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(2, 1, -255, 3) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, -255, 3)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForEqualProcecesses() { //test2 - sizeOfBlocks = new int[]{5, 12, 17, 10}; - sizeOfProcesses = new int[]{10, 10, 10, 10}; + sizeOfBlocks = new int[] { 5, 12, 17, 10 }; + sizeOfProcesses = new int[] { 10, 10, 10, 10 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(2, 1, 3, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 3, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForNoEmptyBlockCell() { //test3 - could suits best, bad use of memory allocation due to worstFit algorithm - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 12, 10, 7}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 12, 10, 7 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(2, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForSameInputDifferentQuery() { //test4 same example different series - same results - sizeOfBlocks = new int[]{5, 12, 17}; - sizeOfProcesses = new int[]{5, 7, 10, 12}; + sizeOfBlocks = new int[] { 5, 12, 17 }; + sizeOfProcesses = new int[] { 5, 7, 10, 12 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList(2, 1, 2, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitForMoreBlocksNoFit() { //test5 for more blocks than processes - sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; - sizeOfProcesses = new int [] {10, 11}; + sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; + sizeOfProcesses = new int[] { 10, 11 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList( -255, -255) - ); + testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); } + @Test void testFitBadCase() { //test6 for only two process fit - sizeOfBlocks = new int[] {7, 17, 7, 5, 6}; - sizeOfProcesses = new int [] {8, 10, 10, 8, 8, 8}; + sizeOfBlocks = new int[] { 7, 17, 7, 5, 6 }; + sizeOfProcesses = new int[] { 8, 10, 10, 8, 8, 8 }; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = new ArrayList<>( - Arrays.asList( 1, -255, -255, 1, -255, -255) - ); + testMemAllocation = + new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java index 66716af86fac..bbefadee8e56 100644 --- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java @@ -5,23 +5,23 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - public class HammingDistanceTest { HammingDistance hd; @BeforeEach - void initialize(){ + void initialize() { hd = new HammingDistance(); } @Test - public void checkForDifferentBits(){ - String senderBits = "000", receiverBits = "011"; + public void checkForDifferentBits() { + String senderBits = "000", receiverBits = "011"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(2); } -/* + + /* 1 0 1 0 1 1 1 1 1 0 @@ -31,46 +31,49 @@ public void checkForDifferentBits(){ */ @Test - public void checkForDifferentBitsLength(){ - String senderBits = "10101", receiverBits = "11110"; + public void checkForDifferentBitsLength() { + String senderBits = "10101", receiverBits = "11110"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(3); } - @Test - public void checkForSameBits(){ + public void checkForSameBits() { String senderBits = "111", receiverBits = "111"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(0); } @Test - public void checkForLongDataBits(){ - String senderBits = "10010101101010000100110100", receiverBits = "00110100001011001100110101"; + public void checkForLongDataBits() { + String senderBits = "10010101101010000100110100", receiverBits = + "00110100001011001100110101"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(7); } @Test - public void mismatchDataBits(){ + public void mismatchDataBits() { String senderBits = "100010", receiverBits = "00011"; - Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () ->{ - int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); - }); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows( + IllegalArgumentException.class, + () -> { + int answer = hd.getHammingDistanceBetweenBits( + senderBits, + receiverBits + ); + } + ); Assertions.assertThat(ex.getMessage()).contains("bits should be same"); - } @Test - public void checkForLongDataBitsSame(){ - String senderBits = "10010101101010000100110100", receiverBits = "10010101101010000100110100"; + public void checkForLongDataBitsSame() { + String senderBits = "10010101101010000100110100", receiverBits = + "10010101101010000100110100"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(0); } - - - } diff --git a/src/test/java/com/thealgorithms/others/countSetBitsTest.java b/src/test/java/com/thealgorithms/others/countSetBitsTest.java index b43c8d29e335..1429aac8daff 100644 --- a/src/test/java/com/thealgorithms/others/countSetBitsTest.java +++ b/src/test/java/com/thealgorithms/others/countSetBitsTest.java @@ -3,13 +3,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; + public class countSetBitsTest { + @Test - void testSetBits(){ - countSetBits csb= new countSetBits(); - assertEquals(1L,csb.countsetBits(16)); + void testSetBits() { + countSetBits csb = new countSetBits(); + assertEquals(1L, csb.countsetBits(16)); assertEquals(4, csb.countsetBits(15)); assertEquals(5, csb.countsetBits(10000)); assertEquals(5, csb.countsetBits(31)); } -} \ No newline at end of file +} diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index ff62c844e644..ace42b8e03a2 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -1,23 +1,20 @@ package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestMiddle() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 6; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {1,1}; + int[] expected = { 1, 1 }; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(1, ans[1]); @@ -26,13 +23,11 @@ public void BinarySearch2dArrayTestMiddle() { @Test // valid test case public void BinarySearch2dArrayTestMiddleSide() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 8; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {1,3}; + int[] expected = { 1, 3 }; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(3, ans[1]); @@ -41,13 +36,11 @@ public void BinarySearch2dArrayTestMiddleSide() { @Test // valid test case public void BinarySearch2dArrayTestUpper() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 2; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {0,1}; + int[] expected = { 0, 1 }; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(1, ans[1]); @@ -56,13 +49,11 @@ public void BinarySearch2dArrayTestUpper() { @Test // valid test case public void BinarySearch2dArrayTestUpperSide() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 1; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {0,0}; + int[] expected = { 0, 0 }; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(0, ans[1]); @@ -71,13 +62,11 @@ public void BinarySearch2dArrayTestUpperSide() { @Test // valid test case public void BinarySearch2dArrayTestLower() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 10; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {2,1}; + int[] expected = { 2, 1 }; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(1, ans[1]); @@ -86,13 +75,11 @@ public void BinarySearch2dArrayTestLower() { @Test // valid test case public void BinarySearch2dArrayTestLowerSide() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 11; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {2,2}; + int[] expected = { 2, 2 }; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(2, ans[1]); @@ -101,17 +88,13 @@ public void BinarySearch2dArrayTestLowerSide() { @Test // valid test case public void BinarySearch2dArrayTestNotFound() { - int[][] arr = { {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9,10,11,12}}; + int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int target = 101; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = {-1,-1}; + int[] expected = { -1, -1 }; System.out.println(Arrays.toString(ans)); assertEquals(-1, ans[0]); assertEquals(-1, ans[1]); } - } - diff --git a/src/test/java/com/thealgorithms/searches/KMPSearchTest.java b/src/test/java/com/thealgorithms/searches/KMPSearchTest.java index a5a396a9f611..a0250ba34f5a 100644 --- a/src/test/java/com/thealgorithms/searches/KMPSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/KMPSearchTest.java @@ -1,66 +1,63 @@ - package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class KMPSearchTest { - + @Test // valid test case public void KMPSearchTestLast() { - String txt = "ABABDABACDABABCABAB"; + String txt = "ABABDABACDABABCABAB"; String pat = "ABABCABAB"; KMPSearch kmpSearch = new KMPSearch(); int value = kmpSearch.KMPSearch(pat, txt); System.out.println(value); assertEquals(value, 10); - } - + @Test // valid test case public void KMPSearchTestFront() { - String txt = "AAAAABAAABA"; - String pat = "AAAA"; + String txt = "AAAAABAAABA"; + String pat = "AAAA"; KMPSearch kmpSearch = new KMPSearch(); int value = kmpSearch.KMPSearch(pat, txt); System.out.println(value); assertEquals(value, 0); - } - + @Test // valid test case public void KMPSearchTestMiddle() { - String txt = "AAACAAAAAC"; - String pat = "AAAA"; + String txt = "AAACAAAAAC"; + String pat = "AAAA"; KMPSearch kmpSearch = new KMPSearch(); int value = kmpSearch.KMPSearch(pat, txt); System.out.println(value); assertEquals(value, 4); - } + @Test // valid test case public void KMPSearchTestNotFound() { - String txt = "AAABAAAA"; - String pat = "AAAA"; + String txt = "AAABAAAA"; + String pat = "AAAA"; KMPSearch kmpSearch = new KMPSearch(); int value = kmpSearch.KMPSearch(pat, txt); System.out.println(value); assertEquals(value, 4); - } + @Test // not valid test case public void KMPSearchTest4() { - String txt = "AABAAA"; - String pat = "AAAA"; + String txt = "AABAAA"; + String pat = "AAAA"; KMPSearch kmpSearch = new KMPSearch(); int value = kmpSearch.KMPSearch(pat, txt); System.out.println(value); assertEquals(value, -1); - } } diff --git a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java index 588b20f54545..720a1250be7c 100644 --- a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java +++ b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java @@ -1,13 +1,13 @@ package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class QuickSelectTest { + @Test void quickSelectMinimumOfOneElement() { List elements = Collections.singletonList(42); @@ -181,8 +181,8 @@ void quickSelectMedianOfManyCharacters() { @Test void quickSelectNullList() { NullPointerException exception = assertThrows( - NullPointerException.class, - () -> QuickSelect.select(null, 0) + NullPointerException.class, + () -> QuickSelect.select(null, 0) ); String expectedMsg = "The list of elements must not be null."; assertEquals(expectedMsg, exception.getMessage()); @@ -192,8 +192,8 @@ void quickSelectNullList() { void quickSelectEmptyList() { List objects = Collections.emptyList(); IllegalArgumentException exception = assertThrows( - IllegalArgumentException.class, - () -> QuickSelect.select(objects, 0) + IllegalArgumentException.class, + () -> QuickSelect.select(objects, 0) ); String expectedMsg = "The list of elements must not be empty."; assertEquals(expectedMsg, exception.getMessage()); @@ -202,8 +202,8 @@ void quickSelectEmptyList() { @Test void quickSelectIndexOutOfLeftBound() { IndexOutOfBoundsException exception = assertThrows( - IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), -1) + IndexOutOfBoundsException.class, + () -> QuickSelect.select(Collections.singletonList(1), -1) ); String expectedMsg = "The index must not be negative."; assertEquals(expectedMsg, exception.getMessage()); @@ -212,10 +212,11 @@ void quickSelectIndexOutOfLeftBound() { @Test void quickSelectIndexOutOfRightBound() { IndexOutOfBoundsException exception = assertThrows( - IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), 1) + IndexOutOfBoundsException.class, + () -> QuickSelect.select(Collections.singletonList(1), 1) ); - String expectedMsg = "The index must be less than the number of elements."; + String expectedMsg = + "The index must be less than the number of elements."; assertEquals(expectedMsg, exception.getMessage()); } @@ -229,12 +230,15 @@ private static List generateRandomIntegers(int n) { } private static List generateRandomCharacters(int n) { - return RANDOM.ints(n, ASCII_A, ASCII_Z) - .mapToObj(i -> (char) i) - .collect(Collectors.toList()); + return RANDOM + .ints(n, ASCII_A, ASCII_Z) + .mapToObj(i -> (char) i) + .collect(Collectors.toList()); } - private static > List getSortedCopyOfList(List list) { + private static > List getSortedCopyOfList( + List list + ) { return list.stream().sorted().collect(Collectors.toList()); } } diff --git a/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java b/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java index 0bc0ab1f7b3b..6841fdac33f4 100644 --- a/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java @@ -1,14 +1,13 @@ package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class RabinKarpAlgorithmTest { - - RabinKarpAlgorithm RKA= new RabinKarpAlgorithm(); - int q= 101; + RabinKarpAlgorithm RKA = new RabinKarpAlgorithm(); + int q = 101; @Test // valid test case @@ -16,9 +15,9 @@ public void RabinKarpAlgorithmTestExample() { String txt = "This is an example for rabin karp algorithmn"; String pat = "algorithmn"; int value = RKA.search(pat, txt, q); - assertEquals(value,34); + assertEquals(value, 34); } - + @Test // valid test case public void RabinKarpAlgorithmTestFront() { @@ -54,5 +53,4 @@ public void RabinKarpAlgorithmTestNotFound() { int value = RKA.search(pat, txt, q); assertEquals(value, -1); } - } diff --git a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java index 70d0abadebed..656b499c6cfa 100644 --- a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java @@ -1,26 +1,27 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class BinaryInsertionSortTest { - BinaryInsertionSort BIS= new BinaryInsertionSort(); - + + BinaryInsertionSort BIS = new BinaryInsertionSort(); + @Test // valid test case public void BinaryInsertionSortTestNonDuplicate() { - int[] array = {1,0,2,5,3,4,9,8,10,6,7}; - int [] expResult= {0,1,2,3,4,5,6,7,8,9,10}; + int[] array = { 1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7 }; + int[] expResult = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int[] actResult = BIS.binaryInsertSort(array); - assertArrayEquals(expResult,actResult); + assertArrayEquals(expResult, actResult); } @Test public void BinaryInsertionSortTestDuplicate() { - int[] array = {1,1,1,5,9,8,7,2,6}; - int [] expResult= {1,1,1,2,5,6,7,8,9}; + int[] array = { 1, 1, 1, 5, 9, 8, 7, 2, 6 }; + int[] expResult = { 1, 1, 1, 2, 5, 6, 7, 8, 9 }; int[] actResult = BIS.binaryInsertSort(array); - assertArrayEquals(expResult,actResult); + assertArrayEquals(expResult, actResult); } } diff --git a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java index e1a2ca2f7ff8..1d8cdd31c5ab 100644 --- a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java @@ -9,6 +9,7 @@ * @see BubbleSort */ public class BubbleSortTest { + private BubbleSort bubbleSort = new BubbleSort(); @Test @@ -21,33 +22,73 @@ public void bubbleSortEmptyArray() { @Test public void bubbleSortSingleIntegerElementArray() { - Integer[] inputArray = {4}; + Integer[] inputArray = { 4 }; Integer[] outputArray = bubbleSort.sort(inputArray); - Integer[] expectedOutput = {4}; + Integer[] expectedOutput = { 4 }; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortSingleStringElementArray() { - String[] inputArray = {"s"}; + String[] inputArray = { "s" }; String[] outputArray = bubbleSort.sort(inputArray); - String[] expectedOutput = {"s"}; + String[] expectedOutput = { "s" }; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortIntegerArray() { - Integer[] inputArray = {4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12}; + Integer[] inputArray = { 4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12 }; Integer[] outputArray = bubbleSort.sort(inputArray); - Integer[] expectedOutput = {-231, -6, -6, 1, 4, 9, 12, 23, 23, 54, 78}; + Integer[] expectedOutput = { + -231, + -6, + -6, + 1, + 4, + 9, + 12, + 23, + 23, + 54, + 78, + }; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortStringArray() { - String[] inputArray = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"}; + String[] inputArray = { + "cbf", + "auk", + "ó", + "(b", + "a", + ")", + "au", + "á", + "cba", + "auk", + "(a", + "bhy", + "cba", + }; String[] outputArray = bubbleSort.sort(inputArray); - String[] expectedOutput = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"}; + String[] expectedOutput = { + "(a", + "(b", + ")", + "a", + "au", + "auk", + "auk", + "bhy", + "cba", + "cba", + "cbf", + "á", + "ó", + }; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java index 9e05f6cd94fc..0048c8437d80 100644 --- a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java @@ -1,17 +1,19 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class DutchNationalFlagSortTest { + @Test /* 1 will be used as intended middle. Partitions on the result array: [ smaller than 1 , equal 1, greater than 1] */ void DNFSTestOdd() { - Integer[] integers = {1, 3, 1, 4, 0}; - Integer[] integersResult = {0, 1, 1, 4, 3}; + Integer[] integers = { 1, 3, 1, 4, 0 }; + Integer[] integersResult = { 0, 1, 1, 4, 3 }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -23,8 +25,8 @@ void DNFSTestOdd() { Partitions on the result array: [ smaller than 3 , equal 3, greater than 3] */ void DNFSTestEven() { - Integer[] integers = {8, 1, 3, 1, 4, 0}; - Integer[] integersResult = {0, 1, 1, 3, 4, 8}; + Integer[] integers = { 8, 1, 3, 1, 4, 0 }; + Integer[] integersResult = { 0, 1, 1, 3, 4, 8 }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -36,8 +38,8 @@ void DNFSTestEven() { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestEvenStrings() { - String[] strings = {"a", "d", "b", "s", "e", "e"}; - String[] stringsResult = {"a", "b", "s", "e", "e", "d"}; + String[] strings = { "a", "d", "b", "s", "e", "e" }; + String[] stringsResult = { "a", "b", "s", "e", "e", "d" }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -49,8 +51,8 @@ void DNFSTestEvenStrings() { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestOddStrings() { - String[] strings = {"a", "d", "b", "s", "e"}; - String[] stringsResult = {"a", "b", "s", "e", "d"}; + String[] strings = { "a", "d", "b", "s", "e" }; + String[] stringsResult = { "a", "b", "s", "e", "d" }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -62,8 +64,8 @@ void DNFSTestOddStrings() { Partitions on the result array: [ smaller than 0 , equal 0, greater than 0] */ void DNFSTestOddMidGiven() { - Integer[] integers = {1, 3, 1, 4, 0}; - Integer[] integersResult = {0, 1, 4, 3, 1}; + Integer[] integers = { 1, 3, 1, 4, 0 }; + Integer[] integersResult = { 0, 1, 4, 3, 1 }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 0); assertArrayEquals(integers, integersResult); @@ -75,8 +77,8 @@ void DNFSTestOddMidGiven() { Partitions on the result array: [ smaller than 4 , equal 4, greater than 4] */ void DNFSTestEvenMidGiven() { - Integer[] integers = {8, 1, 3, 1, 4, 0}; - Integer[] integersResult = {0, 1, 3, 1, 4, 8}; + Integer[] integers = { 8, 1, 3, 1, 4, 0 }; + Integer[] integersResult = { 0, 1, 3, 1, 4, 8 }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 4); assertArrayEquals(integers, integersResult); @@ -88,8 +90,8 @@ void DNFSTestEvenMidGiven() { Partitions on the result array: [ smaller than s , equal s, greater than s] */ void DNFSTestEvenStringsMidGiven() { - String[] strings = {"a", "d", "b", "s", "e", "e"}; - String[] stringsResult = {"a", "d", "b", "e", "e", "s"}; + String[] strings = { "a", "d", "b", "s", "e", "e" }; + String[] stringsResult = { "a", "d", "b", "e", "e", "s" }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "s"); assertArrayEquals(strings, stringsResult); @@ -101,8 +103,8 @@ void DNFSTestEvenStringsMidGiven() { Partitions on the result array: [ smaller than e , equal e, greater than e] */ void DNFSTestOddStringsMidGiven() { - String[] strings = {"a", "d", "b", "s", "e"}; - String[] stringsResult = {"a", "d", "b", "e", "s"}; + String[] strings = { "a", "d", "b", "s", "e" }; + String[] stringsResult = { "a", "d", "b", "e", "s" }; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "e"); assertArrayEquals(strings, stringsResult); diff --git a/src/test/java/com/thealgorithms/sorts/QuickSortTest.java b/src/test/java/com/thealgorithms/sorts/QuickSortTest.java index 63d23b1002b4..6d66f51eaaa1 100644 --- a/src/test/java/com/thealgorithms/sorts/QuickSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/QuickSortTest.java @@ -9,61 +9,54 @@ * @see QuickSort */ class QuickSortTest { - - private QuickSort quickSort = new QuickSort(); - @Test - void quickSortEmptyArrayShouldPass() - { - Integer[] array = {}; - Integer[] sorted = quickSort.sort(array); - Integer[] expected = {}; - assertArrayEquals(expected, sorted); - } - - @Test - void quickSortSingleValueArrayShouldPass() - { - Integer[] array = {7}; - Integer[] sorted = quickSort.sort(array); - Integer[] expected = {7}; - assertArrayEquals(expected, sorted); - } - - @Test - void quickSortWithIntegerArrayShouldPass() - { - Integer[] array = {49,4,36,9,144,1}; - Integer[] sorted = quickSort.sort(array); - Integer[] expected = {1,4,9,36,49,144}; - assertArrayEquals(expected, sorted); - } - - @Test - void quickSortForArrayWithNegativeValuesShouldPass() - { - Integer[] array = {49,-36,-144,-49,1,9}; - Integer[] sorted = quickSort.sort(array); - Integer[] expected = {-144,-49,-36,1,9,49}; - assertArrayEquals(expected, sorted); - } - - @Test - void quickSortForArrayWithDuplicateValuesShouldPass() - { - Integer[] array = {36,1,49,1,4,9}; - Integer[] sorted = quickSort.sort(array); - Integer[] expected = {1,1,4,9,36,49}; - assertArrayEquals(expected, sorted); - } - - @Test - void quickSortWithStringArrayShouldPass() - { - String[] array = {"c", "a", "e", "b", "d"}; - String[] sorted = quickSort.sort(array); - String[] expected = {"a","b","c","d","e"}; - assertArrayEquals(expected, sorted); - } - + private QuickSort quickSort = new QuickSort(); + + @Test + void quickSortEmptyArrayShouldPass() { + Integer[] array = {}; + Integer[] sorted = quickSort.sort(array); + Integer[] expected = {}; + assertArrayEquals(expected, sorted); + } + + @Test + void quickSortSingleValueArrayShouldPass() { + Integer[] array = { 7 }; + Integer[] sorted = quickSort.sort(array); + Integer[] expected = { 7 }; + assertArrayEquals(expected, sorted); + } + + @Test + void quickSortWithIntegerArrayShouldPass() { + Integer[] array = { 49, 4, 36, 9, 144, 1 }; + Integer[] sorted = quickSort.sort(array); + Integer[] expected = { 1, 4, 9, 36, 49, 144 }; + assertArrayEquals(expected, sorted); + } + + @Test + void quickSortForArrayWithNegativeValuesShouldPass() { + Integer[] array = { 49, -36, -144, -49, 1, 9 }; + Integer[] sorted = quickSort.sort(array); + Integer[] expected = { -144, -49, -36, 1, 9, 49 }; + assertArrayEquals(expected, sorted); + } + + @Test + void quickSortForArrayWithDuplicateValuesShouldPass() { + Integer[] array = { 36, 1, 49, 1, 4, 9 }; + Integer[] sorted = quickSort.sort(array); + Integer[] expected = { 1, 1, 4, 9, 36, 49 }; + assertArrayEquals(expected, sorted); + } + + @Test + void quickSortWithStringArrayShouldPass() { + String[] array = { "c", "a", "e", "b", "d" }; + String[] sorted = quickSort.sort(array); + String[] expected = { "a", "b", "c", "d", "e" }; + assertArrayEquals(expected, sorted); + } } diff --git a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java index 56b8a3c47096..ebe153e68de1 100644 --- a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java @@ -1,35 +1,41 @@ -package com.thealgorithms.sorts; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class SelectionSortTest { - - @Test - // valid test case - void IntegerArrTest() { - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - SelectionSort selectionSort = new SelectionSort(); - - assertArrayEquals(new Integer[]{1, 4, 6, 9, 12, 23, 54, 78, 231}, selectionSort.sort(arr)); - } - - @Test - // valid test case - void StringArrTest() { - String[] arr = {"c", "a", "e", "b", "d"}; - SelectionSort selectionSort = new SelectionSort(); - - assertArrayEquals(new String[]{"a", "b", "c", "d", "e"}, selectionSort.sort(arr)); - } - - @Test - // invalid test case - void emptyArrTest() { - Integer[] arr = {}; - SelectionSort selectionSort = new SelectionSort(); - - assertArrayEquals(new Integer[]{}, selectionSort.sort(arr)); - } -} +package com.thealgorithms.sorts; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class SelectionSortTest { + + @Test + // valid test case + void IntegerArrTest() { + Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + SelectionSort selectionSort = new SelectionSort(); + + assertArrayEquals( + new Integer[] { 1, 4, 6, 9, 12, 23, 54, 78, 231 }, + selectionSort.sort(arr) + ); + } + + @Test + // valid test case + void StringArrTest() { + String[] arr = { "c", "a", "e", "b", "d" }; + SelectionSort selectionSort = new SelectionSort(); + + assertArrayEquals( + new String[] { "a", "b", "c", "d", "e" }, + selectionSort.sort(arr) + ); + } + + @Test + // invalid test case + void emptyArrTest() { + Integer[] arr = {}; + SelectionSort selectionSort = new SelectionSort(); + + assertArrayEquals(new Integer[] {}, selectionSort.sort(arr)); + } +} diff --git a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java index f24596e706c4..9e46c9cc266e 100644 --- a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java @@ -1,39 +1,38 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.LinkedList; - +import org.junit.jupiter.api.Test; class StrandSortTest { - @Test - // valid test case - public void StrandSortNonDuplicateTest() { - int[] expectedArray = { 1, 2, 3, 4, 5 }; - LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(3, 1, 2, 4, 5))); - int[] actualArray = new int[actualList.size()]; - for (int i = 0; i < actualList.size(); i++) { - actualArray[i] = actualList.get(i); - } - assertArrayEquals(expectedArray, actualArray); - - } - - @Test - // valid test case - public void StrandSortDuplicateTest() { - int[] expectedArray = { 2, 2, 2, 5, 7 }; - LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(7, 2, 2, 2, 5))); - int[] actualArray = new int[actualList.size()]; - for (int i = 0; i < actualList.size(); i++) { - actualArray[i] = actualList.get(i); - } - assertArrayEquals(expectedArray, actualArray); - - } + @Test + // valid test case + public void StrandSortNonDuplicateTest() { + int[] expectedArray = { 1, 2, 3, 4, 5 }; + LinkedList actualList = StrandSort.strandSort( + new LinkedList(Arrays.asList(3, 1, 2, 4, 5)) + ); + int[] actualArray = new int[actualList.size()]; + for (int i = 0; i < actualList.size(); i++) { + actualArray[i] = actualList.get(i); + } + assertArrayEquals(expectedArray, actualArray); + } + + @Test + // valid test case + public void StrandSortDuplicateTest() { + int[] expectedArray = { 2, 2, 2, 5, 7 }; + LinkedList actualList = StrandSort.strandSort( + new LinkedList(Arrays.asList(7, 2, 2, 2, 5)) + ); + int[] actualArray = new int[actualList.size()]; + for (int i = 0; i < actualList.size(); i++) { + actualArray[i] = actualList.get(i); + } + assertArrayEquals(expectedArray, actualArray); + } } - - diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java index 6bec2a1bbc01..fe678c00c1bb 100644 --- a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; -import com.thealgorithms.sorts.TopologicalSort.Graph; -import com.thealgorithms.sorts.TopologicalSort.BackEdgeException; +import com.thealgorithms.sorts.TopologicalSort.BackEdgeException; +import com.thealgorithms.sorts.TopologicalSort.Graph; import java.util.LinkedList; +import org.junit.jupiter.api.Test; class TopologicalSortTest { + @Test void successTest() { /* @@ -22,7 +23,7 @@ void successTest() { graph.addEdge("undershorts", "pants", "shoes"); graph.addEdge("shoes", ""); graph.addEdge("socks", "shoes"); - graph.addEdge("jacket",""); + graph.addEdge("jacket", ""); graph.addEdge("pants", "belt", "shoes"); LinkedList expected = new LinkedList<>(); expected.add("socks"); @@ -39,11 +40,10 @@ void successTest() { @Test public void failureTest() { - /* - * Graph example from Geeks For Geeks - * https://www.geeksforgeeks.org/tree-back-edge-and-cross-edges-in-dfs-of-graph/ - * */ + * Graph example from Geeks For Geeks + * https://www.geeksforgeeks.org/tree-back-edge-and-cross-edges-in-dfs-of-graph/ + * */ Graph graph = new Graph(); graph.addEdge("1", "2", "3", "8"); graph.addEdge("2", "4"); @@ -53,9 +53,13 @@ public void failureTest() { graph.addEdge("6", "2"); graph.addEdge("7", ""); graph.addEdge("8", ""); - Exception exception = assertThrows(BackEdgeException.class, () -> TopologicalSort.sort(graph)); - String expected = "This graph contains a cycle. No linear ordering is possible. " + - "Back edge: 6 -> 2"; + Exception exception = assertThrows( + BackEdgeException.class, + () -> TopologicalSort.sort(graph) + ); + String expected = + "This graph contains a cycle. No linear ordering is possible. " + + "Back edge: 6 -> 2"; assertEquals(exception.getMessage(), expected); } } diff --git a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java index 336170a33535..cddbb432db7d 100644 --- a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java @@ -1,74 +1,72 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import java.util.Arrays; +import org.junit.jupiter.api.Test; public class WiggleSortTest { + @Test - void WiggleTestNumbersEven(){ + void WiggleTestNumbersEven() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {1, 2, 3, 4}; - Integer[] result = {1, 4, 2, 3}; + Integer[] values = { 1, 2, 3, 4 }; + Integer[] result = { 1, 4, 2, 3 }; wiggleSort.sort(values); assertArrayEquals(values, result); } @Test - void WiggleTestNumbersOdd(){ + void WiggleTestNumbersOdd() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {1, 2, 3, 4, 5}; - Integer[] result = {3, 5, 1, 4, 2}; + Integer[] values = { 1, 2, 3, 4, 5 }; + Integer[] result = { 3, 5, 1, 4, 2 }; wiggleSort.sort(values); assertArrayEquals(values, result); - } @Test - void WiggleTestNumbersOddDuplicates(){ + void WiggleTestNumbersOddDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {7, 2, 2, 2, 5}; - Integer[] result = {2, 7, 2, 5, 2}; + Integer[] values = { 7, 2, 2, 2, 5 }; + Integer[] result = { 2, 7, 2, 5, 2 }; wiggleSort.sort(values); assertArrayEquals(values, result); } @Test - void WiggleTestNumbersOddMultipleDuplicates(){ + void WiggleTestNumbersOddMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {1, 1, 2, 2, 5}; - Integer[] result = {2, 5, 1, 2, 1}; + Integer[] values = { 1, 1, 2, 2, 5 }; + Integer[] result = { 2, 5, 1, 2, 1 }; wiggleSort.sort(values); assertArrayEquals(values, result); } @Test - void WiggleTestNumbersEvenMultipleDuplicates(){ + void WiggleTestNumbersEvenMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {1, 1, 2, 2, 2, 5}; - Integer[] result = {2, 5, 1, 2, 1, 2}; + Integer[] values = { 1, 1, 2, 2, 2, 5 }; + Integer[] result = { 2, 5, 1, 2, 1, 2 }; wiggleSort.sort(values); System.out.println(Arrays.toString(values)); assertArrayEquals(values, result); } @Test - void WiggleTestNumbersEvenDuplicates(){ + void WiggleTestNumbersEvenDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = {1, 2, 4, 4}; - Integer[] result = {1, 4, 2, 4}; + Integer[] values = { 1, 2, 4, 4 }; + Integer[] result = { 1, 4, 2, 4 }; wiggleSort.sort(values); assertArrayEquals(values, result); } @Test - void WiggleTestStrings(){ + void WiggleTestStrings() { WiggleSort wiggleSort = new WiggleSort(); - String[] values = {"a", "b", "d", "c"}; - String[] result = {"a", "d", "b", "c"}; + String[] values = { "a", "b", "d", "c" }; + String[] result = { "a", "d", "b", "c" }; wiggleSort.sort(values); assertArrayEquals(values, result); } diff --git a/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java b/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java index a7316b83f65b..3d240f2c2bed 100644 --- a/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java +++ b/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java @@ -1,11 +1,11 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class AlphabeticalTest { + @Test public void isAlphabetical() { // expected to be true @@ -26,5 +26,4 @@ public void isAlphabetical() { assertFalse(Alphabetical.isAlphabetical(input5)); assertFalse(Alphabetical.isAlphabetical(input6)); } - } diff --git a/src/test/java/com/thealgorithms/strings/AnagramsTest.java b/src/test/java/com/thealgorithms/strings/AnagramsTest.java index 36b337e5e9ba..4a0771eef875 100644 --- a/src/test/java/com/thealgorithms/strings/AnagramsTest.java +++ b/src/test/java/com/thealgorithms/strings/AnagramsTest.java @@ -1,10 +1,11 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class AnagramsTest { + @Test public void isAlphabetical() { String input1 = "late"; diff --git a/src/test/java/com/thealgorithms/strings/CharacterSameTest.java b/src/test/java/com/thealgorithms/strings/CharacterSameTest.java index 8df9e273ab61..e4faee25e84f 100644 --- a/src/test/java/com/thealgorithms/strings/CharacterSameTest.java +++ b/src/test/java/com/thealgorithms/strings/CharacterSameTest.java @@ -1,10 +1,11 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class CharacterSameTest { + @Test public void isAllCharactersSame() { String input1 = "aaa"; @@ -22,7 +23,5 @@ public void isAllCharactersSame() { assertTrue(CharactersSame.isAllCharactersSame(input5)); assertTrue(CharactersSame.isAllCharactersSame(input6)); assertFalse(CharactersSame.isAllCharactersSame(input7)); - } - } diff --git a/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java b/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java index 8afe864114fd..4e2854333a30 100644 --- a/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java +++ b/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java @@ -1,35 +1,35 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class CheckAnagramsTest { + @Test public void CheckAnagrams() { String testString1 = "STUDY"; String testString2 = "DUSTY"; - assertTrue(CheckAnagrams.isAnagrams(testString1,testString2)); + assertTrue(CheckAnagrams.isAnagrams(testString1, testString2)); } @Test public void CheckFalseAnagrams() { String testString1 = "STUDY"; String testString2 = "random"; - assertFalse(CheckAnagrams.isAnagrams(testString1,testString2)); + assertFalse(CheckAnagrams.isAnagrams(testString1, testString2)); } @Test public void CheckSameWordAnagrams() { String testString1 = "STUDY"; - assertTrue(CheckAnagrams.isAnagrams(testString1,testString1)); + assertTrue(CheckAnagrams.isAnagrams(testString1, testString1)); } @Test public void CheckDifferentCasesAnagram() { String testString1 = "STUDY"; String testString2 = "dusty"; - assertTrue(CheckAnagrams.isAnagrams(testString1,testString2)); + assertTrue(CheckAnagrams.isAnagrams(testString1, testString2)); } } diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java index d17744f1dc66..386ad125ca6d 100644 --- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java @@ -1,23 +1,39 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class HammingDistanceTest { + @Test void testHammingDistance() throws Exception { assertEquals(HammingDistance.calculateHammingDistance("", ""), 0); - assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0); - assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3); - assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4); - assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5); + assertEquals( + HammingDistance.calculateHammingDistance("java", "java"), + 0 + ); + assertEquals( + HammingDistance.calculateHammingDistance("karolin", "kathrin"), + 3 + ); + assertEquals( + HammingDistance.calculateHammingDistance("kathrin", "kerstin"), + 4 + ); + assertEquals( + HammingDistance.calculateHammingDistance("00000", "11111"), + 5 + ); } @Test void testNotEqualStringLengths() { - Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc")); + Exception exception = assertThrows( + Exception.class, + () -> HammingDistance.calculateHammingDistance("ab", "abc") + ); assertEquals("String lengths must be equal", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/strings/IsomorphicTest.java b/src/test/java/com/thealgorithms/strings/IsomorphicTest.java index 1a83e6075061..991b0cf51ee8 100644 --- a/src/test/java/com/thealgorithms/strings/IsomorphicTest.java +++ b/src/test/java/com/thealgorithms/strings/IsomorphicTest.java @@ -1,30 +1,31 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; + import java.util.*; +import org.junit.jupiter.api.Test; public class IsomorphicTest { @Test public static void main(String[] args) { + String str1 = "abbbbaac"; + String str2 = "kffffkkd"; - String str1 = "abbbbaac"; - String str2 = "kffffkkd"; - - String str3 = "xyxyxy"; - String str4 = "bnbnbn"; + String str3 = "xyxyxy"; + String str4 = "bnbnbn"; - String str5 = "ghjknnmm"; - String str6 = "wertpopo"; + String str5 = "ghjknnmm"; + String str6 = "wertpopo"; - String str7 = "aaammmnnn"; - String str8 = "ggghhhbbj"; + String str7 = "aaammmnnn"; + String str8 = "ggghhhbbj"; - Isomorphic isomorphic = new Isomorphic(); + Isomorphic isomorphic = new Isomorphic(); - assertTrue(isomorphic.checkStrings(str1, str2)); - assertTrue(isomorphic.checkStrings(str3, str4)); - assertFalse(isomorphic.checkStrings(str5, str6)); - assertFalse(isomorphic.checkStrings(str7, str8)); - } + assertTrue(isomorphic.checkStrings(str1, str2)); + assertTrue(isomorphic.checkStrings(str3, str4)); + assertFalse(isomorphic.checkStrings(str5, str6)); + assertFalse(isomorphic.checkStrings(str7, str8)); + } } diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java index 6ae1a9133714..c98ebc2ae985 100644 --- a/src/test/java/com/thealgorithms/strings/PalindromeTest.java +++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; public class PalindromeTest { + @Test public void palindrome() { String input1 = "kayak"; diff --git a/src/test/java/com/thealgorithms/strings/PangramTest.java b/src/test/java/com/thealgorithms/strings/PangramTest.java index c07f07b64672..599ed3d56cae 100644 --- a/src/test/java/com/thealgorithms/strings/PangramTest.java +++ b/src/test/java/com/thealgorithms/strings/PangramTest.java @@ -1,12 +1,12 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; import static com.thealgorithms.strings.Pangram.isPangram; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class PangramTest { + @Test public void testPangram() { assertTrue(isPangram("The quick brown fox jumps over the lazy dog")); diff --git a/src/test/java/com/thealgorithms/strings/UpperTest.java b/src/test/java/com/thealgorithms/strings/UpperTest.java index 542b175c94bf..5c030efdc740 100644 --- a/src/test/java/com/thealgorithms/strings/UpperTest.java +++ b/src/test/java/com/thealgorithms/strings/UpperTest.java @@ -1,10 +1,11 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class UpperTest { + @Test public void toUpperCase() { String input1 = "hello world"; diff --git a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java index f8bc63562487..dac3cc8513fb 100644 --- a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java +++ b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java @@ -4,11 +4,18 @@ import org.junit.jupiter.api.Test; public class longestNonRepeativeSubstringTest { + @Test public void palindrome() { String input1 = "HelloWorld"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input1 ) , 5 ) ; - Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input2 ) , 9 ) ; + Assertions.assertEquals( + longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), + 5 + ); + Assertions.assertEquals( + longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), + 9 + ); } } diff --git a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java index 6c0e0333b338..81d42af93983 100644 --- a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java +++ b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java @@ -4,11 +4,18 @@ import org.junit.jupiter.api.Test; public class zigZagPatternTest { + @Test public void palindrome() { String input1 = "HelloWorldFromJava"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( zigZagPattern.encode( input1 , 4 ) , "HooeWrrmalolFJvlda" ) ; - Assertions.assertEquals( zigZagPattern.encode( input2 , 4 ) , "jAaLgasPrmgaaevIrgmnnuaoig" ) ; + Assertions.assertEquals( + zigZagPattern.encode(input1, 4), + "HooeWrrmalolFJvlda" + ); + Assertions.assertEquals( + zigZagPattern.encode(input2, 4), + "jAaLgasPrmgaaevIrgmnnuaoig" + ); } }