diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index fbc095909541..5cd8b19346f7 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java @@ -2,7 +2,7 @@ /** * N-Order IIR Filter Assumes inputs are normalized to [-1, 1] - * + *

* Based on the difference equation from * Wikipedia link */ @@ -43,7 +43,7 @@ public IIRFilter(int order) throws IllegalArgumentException { * @param aCoeffs Denominator coefficients * @param bCoeffs Numerator coefficients * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is - * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 + * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 */ public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { if (aCoeffs.length != order) { diff --git a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java index 6569896bd1b7..a2aed159cdd7 100644 --- a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java +++ b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java @@ -33,10 +33,10 @@ public static List> combination(int n, int k) { * A helper method that uses backtracking to find combinations. * * @param combinations The list to store all valid combinations found. - * @param current The current combination being built. - * @param start The starting index for the current recursion. - * @param n The total number of elements (0 to n-1). - * @param k The desired length of each combination. + * @param current The current combination being built. + * @param start The starting index for the current recursion. + * @param n The total number of elements (0 to n-1). + * @param k The desired length of each combination. */ private static void combine(List> combinations, List current, int start, int n, int k) { // Base case: combination found diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index ecaf7428f986..8e05f28353ff 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -8,6 +8,7 @@ /** * Finds all permutations of given array + * * @author Alan Piao (git-Alan Piao) */ public final class Combination { @@ -16,8 +17,9 @@ private Combination() { /** * Find all combinations of given array using backtracking + * * @param arr the array. - * @param n length of combination + * @param n length of combination * @param the type of elements in the array. * @return a list of all combinations of length n. If n == 0, return null. */ @@ -39,12 +41,13 @@ public static List> combination(T[] arr, int n) { /** * Backtrack all possible combinations of a given array - * @param arr the array. - * @param n length of the combination - * @param index the starting index. + * + * @param arr the array. + * @param n length of the combination + * @param index the starting index. * @param currSet set that tracks current combination - * @param result the list contains all combination. - * @param the type of elements in the array. + * @param result the list contains all combination. + * @param the type of elements in the array. */ private static void backtracking(T[] arr, int n, int index, TreeSet currSet, List> result) { if (index + n - currSet.size() > arr.length) { diff --git a/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java index 6bfb026c7de9..1972d3dc2338 100644 --- a/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java +++ b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java @@ -8,19 +8,19 @@ * A class to solve a crossword puzzle using backtracking. * Example: * Input: - * puzzle = { - * {' ', ' ', ' '}, - * {' ', ' ', ' '}, - * {' ', ' ', ' '} - * } - * words = List.of("cat", "dog") - * + * puzzle = { + * {' ', ' ', ' '}, + * {' ', ' ', ' '}, + * {' ', ' ', ' '} + * } + * words = List.of("cat", "dog") + *

* Output: - * { - * {'c', 'a', 't'}, - * {' ', ' ', ' '}, - * {'d', 'o', 'g'} - * } + * { + * {'c', 'a', 't'}, + * {' ', ' ', ' '}, + * {'d', 'o', 'g'} + * } */ public final class CrosswordSolver { private CrosswordSolver() { diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java index c8219ca8ba7e..839cbae1f447 100644 --- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java +++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java @@ -2,6 +2,7 @@ /** * Java program for Flood fill algorithm. + * * @author Akshay Dubey (Git-Akshay Dubey) */ public final class FloodFill { @@ -12,8 +13,8 @@ private FloodFill() { * Get the color at the given coordinates of a 2D image * * @param image The image to be filled - * @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 + * @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(final int[][] image, final int x, final int y) { @@ -24,8 +25,8 @@ public static int getPixel(final int[][] image, final int x, final int y) { * Put the color at the given coordinates of a 2D image * * @param image The image to be filled - * @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 + * @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(final int[][] image, final int x, final int y, final int newColor) { image[x][y] = newColor; @@ -34,9 +35,9 @@ public static void putPixel(final int[][] image, final int x, final int y, final /** * Fill the 2D image with new color * - * @param image The image to be filled - * @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 + * @param image The image to be filled + * @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 * @param newColor The new color which to be filled in the image * @param oldColor The old color which is to be replaced in the image */ diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java index 2c2da659f3aa..8e481167f7be 100644 --- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java +++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java @@ -6,12 +6,12 @@ /** * The KnightsTour class solves the Knight's Tour problem using backtracking. - * + *

* Problem Statement: * Given an N*N board with a knight placed on the first block, the knight must * move according to chess rules and visit each square on the board exactly once. * The class outputs the sequence of moves for the knight. - * + *

* Example: * Input: N = 8 (8x8 chess board) * Output: The sequence of numbers representing the order in which the knight visits each square. @@ -61,7 +61,7 @@ public static void resetBoard() { /** * Recursive method to solve the Knight's Tour problem. * - * @param row The current row of the knight + * @param row The current row of the knight * @param column The current column of the knight * @param count The current move number * @return True if a solution is found, False otherwise @@ -96,10 +96,10 @@ static boolean solve(int row, int column, int count) { /** * Returns a list of valid neighboring cells where the knight can move. * - * @param row The current row of the knight + * @param row The current row of the knight * @param column The current column of the knight * @return A list of arrays representing valid moves, where each array contains: - * {nextRow, nextCol, numberOfPossibleNextMoves} + * {nextRow, nextCol, numberOfPossibleNextMoves} */ static List neighbors(int row, int column) { List neighbour = new ArrayList<>(); @@ -137,9 +137,9 @@ static int countNeighbors(int row, int column) { /** * Detects if moving to a given position will create an orphan (a position with no further valid moves). * - * @param count The current move number - * @param row The row of the current position - * @param column The column of the current position + * @param count The current move number + * @param row The row of the current position + * @param column The column of the current position * @return True if an orphan is detected, False otherwise */ static boolean orphanDetected(int count, int row, int column) { diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java index 8247172e7ee0..515b36d57562 100644 --- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java +++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java @@ -4,7 +4,7 @@ * This class contains methods to solve a maze using recursive backtracking. * The maze is represented as a 2D array where walls, paths, and visited/dead * ends are marked with different integers. - * + *

* The goal is to find a path from a starting position to the target position * (map[6][5]) while navigating through the maze. */ diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java index 1a8e453e34cb..b99e392dca79 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -8,21 +8,21 @@ * which N queens can be placed on the board such no two queens attack each * other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....", * "...Q..", ".....Q", "Q.....", "..Q...", "....Q." - * + *

* Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.." - * + *

* Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..." - * + *

* Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...." - * + *

* Solution: Brute Force approach: - * + *

* Generate all possible arrangement to place N queens on N*N board. Check each * board if queens are placed safely. If it is safe, include arrangement in * solution set. Otherwise, ignore it - * + *

* Optimized solution: This can be solved using backtracking in below steps - * + *

* Start with first column and place queen on first row Try placing queen in a * row on second column If placing second queen in second column attacks any of * the previous queens, change the row in second column otherwise move to next @@ -59,9 +59,9 @@ public static void placeQueens(final int queens) { /** * This is backtracking function which tries to place queen recursively * - * @param boardSize: size of chess board - * @param solutions: this holds all possible arrangements - * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param boardSize: size of chess board + * @param solutions: this holds all possible arrangements + * @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) { @@ -94,8 +94,8 @@ private static void getSolution(int boardSize, List> solutions, int * This function checks if queen can be placed at row = rowIndex in column = * columnIndex safely * - * @param columns: columns[i] = rowId where queen is placed in ith column. - * @param rowIndex: row in which queen has to be placed + * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param rowIndex: row in which queen has to be placed * @param columnIndex: column in which queen is being placed * @return true: if queen can be placed safely false: otherwise */ diff --git a/src/main/java/com/thealgorithms/backtracking/Permutation.java b/src/main/java/com/thealgorithms/backtracking/Permutation.java index 21d26e53980f..745aa9dd6e6b 100644 --- a/src/main/java/com/thealgorithms/backtracking/Permutation.java +++ b/src/main/java/com/thealgorithms/backtracking/Permutation.java @@ -5,6 +5,7 @@ /** * Finds all permutations of given array + * * @author Alan Piao (Git-Alan Piao) */ public final class Permutation { @@ -13,6 +14,7 @@ private Permutation() { /** * Find all permutations of given array using backtracking + * * @param arr the array. * @param the type of elements in the array. * @return a list of all permutations. @@ -26,10 +28,11 @@ public static List permutation(T[] arr) { /** * Backtrack all possible orders of a given array - * @param arr the array. - * @param index the starting index. + * + * @param arr the array. + * @param index the starting index. * @param result the list contains all permutations. - * @param the type of elements in the array. + * @param the type of elements in the array. */ private static void backtracking(T[] arr, int index, List result) { if (index == arr.length) { @@ -44,8 +47,9 @@ private static void backtracking(T[] arr, int index, List result) { /** * Swap two element for a given array - * @param a first index - * @param b second index + * + * @param a first index + * @param b second index * @param arr the array. * @param the type of elements in the array. */ diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java index b34ba660ebd7..10b98e5111e7 100644 --- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java +++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java @@ -6,7 +6,7 @@ * of unique, natural numbers. * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. * The only solution is 1^3 + 2^3 + 3^3 + 4^3. Therefore, the output will be 1. - * + *

* N is represented by the parameter 'targetSum' in the code. * X is represented by the parameter 'power' in the code. */ @@ -16,7 +16,7 @@ public class PowerSum { * Calculates the number of ways to express the target sum as a sum of Xth powers of unique natural numbers. * * @param targetSum The target sum to achieve (N in the problem statement) - * @param power The power to raise natural numbers to (X in the problem statement) + * @param power The power to raise natural numbers to (X in the problem statement) * @return The number of ways to express the target sum */ public int powSum(int targetSum, int power) { @@ -30,10 +30,10 @@ public int powSum(int targetSum, int power) { /** * Recursively calculates the number of ways to express the remaining sum as a sum of Xth powers. * - * @param remainingSum The remaining sum to achieve - * @param power The power to raise natural numbers to (X in the problem statement) + * @param remainingSum The remaining sum to achieve + * @param power The power to raise natural numbers to (X in the problem statement) * @param currentNumber The current natural number being considered - * @param currentSum The current sum of powered numbers + * @param currentSum The current sum of powered numbers * @return The number of valid combinations */ private int sumRecursive(int remainingSum, int power, int currentNumber, int currentSum) { diff --git a/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java b/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java index 4a159dbfe0b1..8f84c4f85d9d 100644 --- a/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java +++ b/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java @@ -14,7 +14,7 @@ private SubsequenceFinder() { * Find all subsequences of given list using backtracking * * @param sequence a list of items on the basis of which we need to generate all subsequences - * @param the type of elements in the array + * @param the type of elements in the array * @return a list of all subsequences */ public static List> generateAll(List sequence) { @@ -33,11 +33,11 @@ public static List> generateAll(List sequence) { * We know that each state has exactly two branching * It terminates when it reaches the end of the given sequence * - * @param sequence all elements + * @param sequence all elements * @param currentSubsequence current subsequence - * @param index current index - * @param allSubSequences contains all sequences - * @param the type of elements which we generate + * @param index current index + * @param allSubSequences contains all sequences + * @param the type of elements which we generate */ private static void backtrack(List sequence, List currentSubsequence, final int index, List> allSubSequences) { assert index <= sequence.size(); diff --git a/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java b/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java index 1854cab20a7f..d2240fdbe2ae 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java +++ b/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java @@ -5,16 +5,16 @@ /** * Class to determine if a pattern matches a string using backtracking. - * + *

* Example: * Pattern: "abab" * Input String: "JavaPythonJavaPython" * Output: true - * + *

* Pattern: "aaaa" * Input String: "JavaJavaJavaJava" * Output: true - * + *

* Pattern: "aabb" * Input String: "JavaPythonPythonJava" * Output: false @@ -26,7 +26,7 @@ private WordPatternMatcher() { /** * Determines if the given pattern matches the input string using backtracking. * - * @param pattern The pattern to match. + * @param pattern The pattern to match. * @param inputString The string to match against the pattern. * @return True if the pattern matches the string, False otherwise. */ @@ -39,12 +39,12 @@ public static boolean matchWordPattern(String pattern, String inputString) { /** * Backtracking helper function to check if the pattern matches the string. * - * @param pattern The pattern string. - * @param inputString The string to match against the pattern. + * @param pattern The pattern string. + * @param inputString The string to match against the pattern. * @param patternIndex Current index in the pattern. - * @param strIndex Current index in the input string. - * @param patternMap Map to store pattern characters to string mappings. - * @param strMap Map to store string to pattern character mappings. + * @param strIndex Current index in the input string. + * @param patternMap Map to store pattern characters to string mappings. + * @param strMap Map to store string to pattern character mappings. * @return True if the pattern matches, False otherwise. */ private static boolean backtrack(String pattern, String inputString, int patternIndex, int strIndex, Map patternMap, Map strMap) { diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java index 174ca90ccaab..049ee2b45227 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -2,37 +2,37 @@ /** * Word Search Problem - * + *

* This class solves the word search problem where given an m x n grid of characters (board) * and a target word, the task is to check if the word exists in the grid. * The word can be constructed from sequentially adjacent cells (horizontally or vertically), * and the same cell may not be used more than once in constructing the word. - * + *

* Example: * - For board = - * [ - * ['A','B','C','E'], - * ['S','F','C','S'], - * ['A','D','E','E'] - * ] - * and word = "ABCCED", -> returns true - * and word = "SEE", -> returns true - * and word = "ABCB", -> returns false - * + * [ + * ['A','B','C','E'], + * ['S','F','C','S'], + * ['A','D','E','E'] + * ] + * and word = "ABCCED", -> returns true + * and word = "SEE", -> returns true + * and word = "ABCB", -> returns false + *

* Solution: * - Depth First Search (DFS) with backtracking is used to explore possible paths from any cell - * matching the first letter of the word. DFS ensures that we search all valid paths, while - * backtracking helps in reverting decisions when a path fails to lead to a solution. - * + * matching the first letter of the word. DFS ensures that we search all valid paths, while + * backtracking helps in reverting decisions when a path fails to lead to a solution. + *

* Time Complexity: O(m * n * 3^L) - * - m = number of rows in the board - * - n = number of columns in the board - * - L = length of the word - * - For each cell, we look at 3 possible directions (since we exclude the previously visited direction), - * and we do this for L letters. - * + * - m = number of rows in the board + * - n = number of columns in the board + * - L = length of the word + * - For each cell, we look at 3 possible directions (since we exclude the previously visited direction), + * and we do this for L letters. + *

* Space Complexity: O(L) - * - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word). + * - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word). */ public class WordSearch { private final int[] dx = {0, 0, 1, -1}; diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java index e6bd35720d9f..d012a9691206 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java @@ -2,9 +2,9 @@ /** * This class provides methods to convert between BCD (Binary-Coded Decimal) and decimal numbers. - * + *

* BCD is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of binary digits, usually four or eight. - * + *

* For more information, refer to the * Binary-Coded Decimal Wikipedia page. * diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java b/src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java index 0d6fd140c720..26da840b0422 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java @@ -3,9 +3,9 @@ /** * This class contains a method to check if the binary representation of a number is a palindrome. *

- * A binary palindrome is a number whose binary representation is the same when read from left to right and right to left. - * For example, the number 9 has a binary representation of 1001, which is a palindrome. - * The number 10 has a binary representation of 1010, which is not a palindrome. + * A binary palindrome is a number whose binary representation is the same when read from left to right and right to left. + * For example, the number 9 has a binary representation of 1001, which is a palindrome. + * The number 10 has a binary representation of 1010, which is not a palindrome. *

* * @author Hardvan diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java b/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java index 40b3097b1276..8f53d88ac433 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java @@ -3,6 +3,7 @@ public final class BitSwap { private BitSwap() { } + /* * @brief Swaps the bits at the position posA and posB from data */ diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java index 3e9a4a21183f..9ecf1eda1e6d 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java @@ -3,7 +3,7 @@ /** * ClearLeftmostSetBit class contains a method to clear the leftmost set bit of a number. * The leftmost set bit is the leftmost bit that is set to 1 in the binary representation of a number. - * + *

* Example: * 26 (11010) -> 10 (01010) * 1 (1) -> 0 (0) diff --git a/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java b/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java index 242f35fc35f2..7e3d09e007cb 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java @@ -5,41 +5,41 @@ 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. - - The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This - works as the expression n-1 flips all the bits after the rightmost set bit of n, including the - rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. - - For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set. - - 1st iteration of the loop: n = 52 - - 00110100 & (n) - 00110011 (n-1) - ~~~~~~~~ - 00110000 - - - 2nd iteration of the loop: n = 48 - - 00110000 & (n) - 00101111 (n-1) - ~~~~~~~~ - 00100000 - - - 3rd iteration of the loop: n = 32 - - 00100000 & (n) - 00011111 (n-1) - ~~~~~~~~ - 00000000 (n = 0) - + * 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. + *

+ * The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This + * works as the expression n-1 flips all the bits after the rightmost set bit of n, including the + * rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. + *

+ * For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set. + *

+ * 1st iteration of the loop: n = 52 + *

+ * 00110100 & (n) + * 00110011 (n-1) + * ~~~~~~~~ + * 00110000 + *

+ *

+ * 2nd iteration of the loop: n = 48 + *

+ * 00110000 & (n) + * 00101111 (n-1) + * ~~~~~~~~ + * 00100000 + *

+ *

+ * 3rd iteration of the loop: n = 32 + *

+ * 00100000 & (n) + * 00011111 (n-1) + * ~~~~~~~~ + * 00000000 (n = 0) + * * @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) { @@ -51,9 +51,9 @@ public long countSetBits(long num) { /** * This approach takes O(1) running time to count the set bits, but requires a pre-processing. - * + *

* So, we divide our 32-bit input into 8-bit chunks, with four chunks. We have 8 bits in each chunk. - * + *

* Then the range is from 0-255 (0 to 2^7). * So, we may need to count set bits from 0 to 255 in individual chunks. * diff --git a/src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java b/src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java index 7a35fc3feebf..4d41339595f2 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java @@ -33,7 +33,7 @@ private FindNthBit() { * * @param num the integer number whose Nth bit is to be found * @param n the bit position (1-based) to retrieve - * @return the value of the Nth bit (0 or 1) + * @return the value of the Nth bit (0 or 1) * @throws IllegalArgumentException if the bit position is less than 1 */ public static int findNthBit(int num, int n) { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java index 9a761c572e2c..0f264a858f98 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java @@ -3,12 +3,12 @@ /** * This class provides a method to find the first differing bit * between two integers. - * + *

* Example: - * x = 10 (1010 in binary) - * y = 12 (1100 in binary) - * The first differing bit is at index 1 (0-based) - * So, the output will be 1 + * x = 10 (1010 in binary) + * y = 12 (1100 in binary) + * The first differing bit is at index 1 (0-based) + * So, the output will be 1 * * @author Hardvan */ diff --git a/src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java b/src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java index 0fb058b2b8a3..8b0c4b3a7d20 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java @@ -3,15 +3,15 @@ /** * HigherLowerPowerOfTwo class has two methods to find the next higher and lower power of two. *

- * nextHigherPowerOfTwo method finds the next higher power of two. - * nextLowerPowerOfTwo method finds the next lower power of two. - * Both methods take an integer as input and return the next higher or lower power of two. - * If the input is less than 1, the next higher power of two is 1. - * If the input is less than or equal to 1, the next lower power of two is 0. - * nextHigherPowerOfTwo method uses bitwise operations to find the next higher power of two. - * nextLowerPowerOfTwo method uses Integer.highestOneBit method to find the next lower power of two. - * The time complexity of both methods is O(1). - * The space complexity of both methods is O(1). + * nextHigherPowerOfTwo method finds the next higher power of two. + * nextLowerPowerOfTwo method finds the next lower power of two. + * Both methods take an integer as input and return the next higher or lower power of two. + * If the input is less than 1, the next higher power of two is 1. + * If the input is less than or equal to 1, the next lower power of two is 0. + * nextHigherPowerOfTwo method uses bitwise operations to find the next higher power of two. + * nextLowerPowerOfTwo method uses Integer.highestOneBit method to find the next lower power of two. + * The time complexity of both methods is O(1). + * The space complexity of both methods is O(1). *

* * @author Hardvan diff --git a/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java index 2398b8214371..a3e1966ef2a2 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java @@ -4,12 +4,12 @@ /** * Find Highest Set Bit - * + *

* This class provides a utility method to calculate the position of the highest * (most significant) bit that is set to 1 in a given non-negative integer. * It is often used in bit manipulation tasks to find the left-most set bit in binary * representation of a number. - * + *

* Example: * - For input 18 (binary 10010), the highest set bit is at position 4 (zero-based index). * @@ -25,13 +25,13 @@ private HighestSetBit() { /** * Finds the highest (most significant) set bit in the given integer. * The method returns the position (index) of the highest set bit as an {@link Optional}. - * + *

* - If the number is 0, no bits are set, and the method returns {@link Optional#empty()}. * - If the number is negative, the method throws {@link IllegalArgumentException}. * * @param num The input integer for which the highest set bit is to be found. It must be non-negative. * @return An {@link Optional} containing the index of the highest set bit (zero-based). - * Returns {@link Optional#empty()} if the number is 0. + * Returns {@link Optional#empty()} if the number is 0. * @throws IllegalArgumentException if the input number is negative. */ public static Optional findHighestSetBit(int num) { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java index 1b8962344ea7..d20d0ae59169 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java @@ -6,7 +6,7 @@ * Specifically, it includes a method to find the index of the rightmost set bit * in an integer. * This class is not meant to be instantiated. - * + *

* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public final class IndexOfRightMostSetBit { @@ -20,7 +20,7 @@ private IndexOfRightMostSetBit() { * * @param n the integer to check for the rightmost set bit * @return the index of the rightmost set bit; -1 if there are no set bits - * (i.e., the input integer is 0) + * (i.e., the input integer is 0) */ public static int indexOfRightMostSetBit(int n) { if (n == 0) { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java index 09d5383322ff..d87d7aea10c6 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java @@ -2,12 +2,14 @@ /** * Checks whether a number is even + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public final class IsEven { private IsEven() { } + public static boolean isEven(int number) { return (number & 1) == 0; } diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java index 4cdf3c6faa3e..8c5539ce7aee 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java @@ -13,7 +13,7 @@ private IsPowerTwo() { /** * Checks if the given integer is a power of two. - * + *

* A number is considered a power of two if it is greater than zero and * has exactly one '1' bit in its binary representation. This method * uses the property that for any power of two (n), the expression diff --git a/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java index 127b6fa2c0b1..c65db42f168a 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java @@ -2,6 +2,7 @@ /** * Lowest Set Bit + * * @author Prayas Kumar (https://github.com/prayas7102) */ @@ -9,6 +10,7 @@ public final class LowestSetBit { // Private constructor to hide the default public one private LowestSetBit() { } + /** * Isolates the lowest set bit of the given number. For example, if n = 18 * (binary: 10010), the result will be 2 (binary: 00010). @@ -20,6 +22,7 @@ public static int isolateLowestSetBit(int n) { // Isolate the lowest set bit using n & -n return n & -n; } + /** * Clears the lowest set bit of the given number. * For example, if n = 18 (binary: 10010), the result will be 16 (binary: 10000). diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java index 17e1a73ec062..607e1bda0c48 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java @@ -3,13 +3,13 @@ /** * A utility class to find the non-repeating number in an array where every other number repeats. * This class contains a method to identify the single unique number using bit manipulation. - * + *

* The solution leverages the properties of the XOR operation, which states that: * - x ^ x = 0 for any integer x (a number XORed with itself is zero) * - x ^ 0 = x for any integer x (a number XORed with zero is the number itself) - * + *

* Using these properties, we can find the non-repeating number in linear time with constant space. - * + *

* Example: * Given the input array [2, 3, 5, 2, 3], the output will be 5 since it does not repeat. * diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java index bd4868d4dbd5..1d14342c7c0b 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java @@ -4,15 +4,15 @@ * This class provides a method to find the element that appears an * odd number of times in an array. All other elements in the array * must appear an even number of times for the logic to work. - * + *

* The solution uses the XOR operation, which has the following properties: * - a ^ a = 0 (XOR-ing the same numbers cancels them out) * - a ^ 0 = a * - XOR is commutative and associative. - * + *

* Time Complexity: O(n), where n is the size of the array. * Space Complexity: O(1), as no extra space is used. - * + *

* Usage Example: * int result = NumberAppearingOddTimes.findOddOccurrence(new int[]{1, 2, 1, 2, 3}); * // result will be 3 diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java b/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java index a2da37aa81ee..4c78e2eb0bb0 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java @@ -3,11 +3,11 @@ /** * This class provides a method to determine whether two integers have * different signs. It utilizes the XOR operation on the two numbers: - * + *

* - If two numbers have different signs, their most significant bits - * (sign bits) will differ, resulting in a negative XOR result. + * (sign bits) will differ, resulting in a negative XOR result. * - If two numbers have the same sign, the XOR result will be non-negative. - * + *

* Time Complexity: O(1) - Constant time operation. * Space Complexity: O(1) - No extra space used. * diff --git a/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java b/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java index afec0188e299..3324cb1fef73 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java @@ -3,7 +3,7 @@ /** * This class provides a method to detect if two integers * differ by exactly one bit flip. - * + *

* Example: * 1 (0001) and 2 (0010) differ by exactly one bit flip. * 7 (0111) and 3 (0011) differ by exactly one bit flip. diff --git a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java index c5c068422113..fed35b650737 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java @@ -3,9 +3,9 @@ /** * @author - https://github.com/Monk-AbhinayVerma * @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement - * The class OnesComplement computes the complement of binary number - * and returns - * the complemented binary string. + * The class OnesComplement computes the complement of binary number + * and returns + * the complemented binary string. * @return the complimented binary string */ public final class OnesComplement { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java index e8f2930d3afe..0465cf6a4fe8 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java @@ -2,6 +2,7 @@ /** * Converts any Octal Number to a Binary Number + * * @author Bama Charan Chhandogi */ diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java index 624a4e2b858a..19de5b9ee7a2 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java @@ -4,18 +4,18 @@ * A utility class for performing single-bit operations on integers. * These operations include flipping, setting, clearing, and getting * individual bits at specified positions. - * + *

* Bit positions are zero-indexed (i.e., the least significant bit is at position 0). * These methods leverage bitwise operations for optimal performance. - * + *

* Examples: * - `flipBit(3, 1)` flips the bit at index 1 in binary `11` (result: `1`). * - `setBit(4, 0)` sets the bit at index 0 in `100` (result: `101` or 5). * - `clearBit(7, 1)` clears the bit at index 1 in `111` (result: `101` or 5). * - `getBit(6, 0)` checks if the least significant bit is set (result: `0`). - * + *

* Time Complexity: O(1) for all operations. - * + *

* Author: lukasb1b (https://github.com/lukasb1b) */ public final class SingleBitOperations { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java index 933dec5654a0..f99ee8b161fb 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java @@ -2,6 +2,7 @@ /** * Swap every pair of adjacent bits of a given number. + * * @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) */ diff --git a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java index 9b8cecd791a6..9e7b454a9a8b 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java @@ -9,11 +9,11 @@ * correct for all binary inputs, including edge cases like all zeroes and all ones. * *

For more information on Two's Complement: + * + * @author Abhinay Verma (https://github.com/Monk-AbhinayVerma) * @see Wikipedia - Two's Complement * *

Algorithm originally suggested by Jon von Neumann. - * - * @author Abhinay Verma (https://github.com/Monk-AbhinayVerma) */ public final class TwosComplement { private TwosComplement() { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java b/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java index b22abc0c04ff..2ac37dc25c2e 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java @@ -2,9 +2,9 @@ /** * This class provides methods to convert between XS-3 (Excess-3) and binary. - * + *

* Excess-3, also called XS-3, is a binary-coded decimal (BCD) code in which each decimal digit is represented by its corresponding 4-bit binary value plus 3. - * + *

* For more information, refer to the * Excess-3 Wikipedia page. * @@ -20,6 +20,7 @@ public final class Xs3Conversion { private Xs3Conversion() { } + /** * Converts an XS-3 (Excess-3) number to binary. * diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java index 5d614afbe584..01538d0f3c47 100644 --- a/src/main/java/com/thealgorithms/ciphers/AES.java +++ b/src/main/java/com/thealgorithms/ciphers/AES.java @@ -2685,7 +2685,7 @@ public static BigInteger mixColumnsDec(BigInteger ciphertext) { * Encrypts the plaintext with the key and returns the result * * @param plainText which we want to encrypt - * @param key the key for encrypt + * @param key the key for encrypt * @return EncryptedText */ public static BigInteger encrypt(BigInteger plainText, BigInteger key) { @@ -2746,34 +2746,34 @@ public static void main(String[] args) { switch (choice) { case 'E', 'e' -> { System.out.println( - "Choose a plaintext block (128-Bit Integer in base 16):" + "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):" + "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):" + "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):" + "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 **"); diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index 14582205442f..36c851f79d51 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -58,10 +58,10 @@ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException * Encrypts plainText in AES using the secret key * * @return byteCipherText (The encrypted text) - * @throws NoSuchPaddingException (from Cipher) - * @throws NoSuchAlgorithmException (from Cipher) - * @throws InvalidKeyException (from Cipher) - * @throws BadPaddingException (from Cipher) + * @throws NoSuchPaddingException (from Cipher) + * @throws NoSuchAlgorithmException (from Cipher) + * @throws InvalidKeyException (from Cipher) + * @throws BadPaddingException (from Cipher) * @throws IllegalBlockSizeException (from Cipher) */ public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java index 636323b63646..b0a3b72c6511 100644 --- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java @@ -3,10 +3,10 @@ /** * The AffineCipher class implements the Affine cipher, a type of monoalphabetic substitution cipher. * It encrypts and decrypts messages using a linear transformation defined by the formula: - * - * E(x) = (a * x + b) mod m - * D(y) = a^-1 * (y - b) mod m - * + *

+ * E(x) = (a * x + b) mod m + * D(y) = a^-1 * (y - b) mod m + *

* where: * - E(x) is the encrypted character, * - D(y) is the decrypted character, @@ -15,7 +15,7 @@ * - x is the index of the plaintext character, * - y is the index of the ciphertext character, * - m is the size of the alphabet (26 for the English alphabet). - * + *

* The class provides methods for encrypting and decrypting messages, as well as a main method to demonstrate its usage. */ final class AffineCipher { diff --git a/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java b/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java index 9169aa82bd75..8b9b48dad06d 100644 --- a/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java @@ -3,14 +3,14 @@ /** * The Atbash cipher is a classic substitution cipher that substitutes each letter * with its opposite letter in the alphabet. - * + *

* For example: * - 'A' becomes 'Z', 'B' becomes 'Y', 'C' becomes 'X', and so on. * - Similarly, 'a' becomes 'z', 'b' becomes 'y', and so on. - * + *

* The cipher works identically for both uppercase and lowercase letters. * Non-alphabetical characters remain unchanged in the output. - * + *

* This cipher is symmetric, meaning that applying the cipher twice will return * the original text. Therefore, the same function is used for both encryption and decryption. * diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index f6a0a3753e9b..7095bfa717a1 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -1099,7 +1099,7 @@ 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 + * parameter */ private String binToHex(String binary) { long num = Long.parseUnsignedLong(binary, 2); @@ -1117,7 +1117,7 @@ private String binToHex(String binary) { * * @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); @@ -1135,7 +1135,7 @@ private String xor(String a, String b) { * * @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 + * passed as parameters */ private String addBin(String a, String b) { String ans = ""; diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java index 61c444cf6463..4dc2da92efb1 100644 --- a/src/main/java/com/thealgorithms/ciphers/Caesar.java +++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java @@ -83,7 +83,7 @@ private static boolean isSmallLatinLetter(char c) { } /** - * @return string array which contains all the possible decoded combination. + * @return string array which contains all the possible decoded combination. */ public String[] bruteforce(String encryptedMessage) { String[] listOfAllTheAnswers = new String[27]; diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java index b6b889b079ca..e68aef054231 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -22,7 +22,7 @@ private ColumnarTranspositionCipher() { /** * Encrypts a certain String with the Columnar Transposition Cipher Rule * - * @param word Word being encrypted + * @param word Word being encrypted * @param keyword String with keyword being used * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule @@ -44,10 +44,10 @@ public static String encrypt(final String word, final String keyword) { /** * Encrypts a certain String with the Columnar Transposition Cipher Rule * - * @param word Word being encrypted - * @param keyword String with keyword being used + * @param word Word being encrypted + * @param keyword String with keyword being used * @param abecedarium String with the abecedarium being used. null for - * default one + * default one * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ diff --git a/src/main/java/com/thealgorithms/ciphers/ECC.java b/src/main/java/com/thealgorithms/ciphers/ECC.java index 7b1e37f0e1e1..e6225c345bd6 100644 --- a/src/main/java/com/thealgorithms/ciphers/ECC.java +++ b/src/main/java/com/thealgorithms/ciphers/ECC.java @@ -9,7 +9,7 @@ * elliptic curves over finite fields. ECC provides a higher level of security with smaller key sizes compared * to other public-key methods like RSA, making it particularly suitable for environments where computational * resources are limited, such as mobile devices and embedded systems. - * + *

* This class implements elliptic curve cryptography, providing encryption and decryption * functionalities based on public and private key pairs. * diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index 28af1a62032a..1fd5a42778fb 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -7,11 +7,11 @@ * RSA is an asymmetric cryptographic algorithm used for secure data encryption and decryption. * It relies on a pair of keys: a public key (used for encryption) and a private key * (used for decryption). The algorithm is based on the difficulty of factoring large prime numbers. - * + *

* This implementation includes key generation, encryption, and decryption methods that can handle both * text-based messages and BigInteger inputs. For more details on RSA: * RSA Cryptosystem - Wikipedia. - * + *

* Example Usage: *

  * RSA rsa = new RSA(1024);
@@ -19,7 +19,7 @@
  * String decryptedMessage = rsa.decrypt(encryptedMessage);
  * System.out.println(decryptedMessage);  // Output: Hello RSA!
  * 
- * + *

* Note: The key size directly affects the security and performance of the RSA algorithm. * Larger keys are more secure but slower to compute. * @@ -45,8 +45,8 @@ public RSA(int bits) { * Encrypts a text message using the RSA public key. * * @param message The plaintext message to be encrypted. - * @throws IllegalArgumentException If the message is empty. * @return The encrypted message represented as a String. + * @throws IllegalArgumentException If the message is empty. */ public synchronized String encrypt(String message) { if (message.isEmpty()) { @@ -69,8 +69,8 @@ public synchronized BigInteger encrypt(BigInteger message) { * Decrypts an encrypted message (as String) using the RSA private key. * * @param encryptedMessage The encrypted message to be decrypted, represented as a String. - * @throws IllegalArgumentException If the message is empty. * @return The decrypted plaintext message as a String. + * @throws IllegalArgumentException If the message is empty. */ public synchronized String decrypt(String encryptedMessage) { if (encryptedMessage.isEmpty()) { diff --git a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java index f81252980468..141223870caf 100644 --- a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java @@ -6,6 +6,7 @@ * The rail fence cipher (also called a zigzag cipher) is a classical type of transposition cipher. * It derives its name from the manner in which encryption is performed, in analogy to a fence built with horizontal rails. * https://en.wikipedia.org/wiki/Rail_fence_cipher + * * @author https://github.com/Krounosity */ @@ -69,6 +70,7 @@ else if (row == rails - 1) { } return encryptedString.toString(); } + // Decrypts the input string using the rail fence cipher method with the given number of rails. public String decrypt(String str, int rails) { diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java index 0f117853bb85..5eec12335f17 100644 --- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java +++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java @@ -2,24 +2,24 @@ /** * A Java implementation of the Vigenère Cipher. - * + *

* The Vigenère Cipher is a polyalphabetic substitution cipher that uses a * keyword to shift letters in the plaintext by different amounts, depending * on the corresponding character in the keyword. It wraps around the alphabet, * ensuring the shifts are within 'A'-'Z' or 'a'-'z'. - * + *

* Non-alphabetic characters (like spaces, punctuation) are kept unchanged. - * + *

* Encryption Example: * - Plaintext: "Hello World!" * - Key: "suchsecret" * - Encrypted Text: "Zynsg Yfvev!" - * + *

* Decryption Example: * - Ciphertext: "Zynsg Yfvev!" * - Key: "suchsecret" * - Decrypted Text: "Hello World!" - * + *

* Wikipedia Reference: * Vigenère Cipher - Wikipedia * @@ -39,9 +39,9 @@ public class Vigenere { * 6. Return the encrypted message. * * @param message The plaintext message to encrypt. - * @param key The keyword used for encryption. - * @throws IllegalArgumentException if the key is empty. + * @param key The keyword used for encryption. * @return The encrypted message. + * @throws IllegalArgumentException if the key is empty. */ public String encrypt(final String message, final String key) { if (key.isEmpty()) { @@ -77,9 +77,9 @@ public String encrypt(final String message, final String key) { * 6. Return the decrypted message. * * @param message The encrypted message to decrypt. - * @param key The keyword used for decryption. - * @throws IllegalArgumentException if the key is empty. + * @param key The keyword used for decryption. * @return The decrypted plaintext message. + * @throws IllegalArgumentException if the key is empty. */ public String decrypt(final String message, final String key) { if (key.isEmpty()) { diff --git a/src/main/java/com/thealgorithms/ciphers/XORCipher.java b/src/main/java/com/thealgorithms/ciphers/XORCipher.java index a612ccfbcdef..4e780841293c 100644 --- a/src/main/java/com/thealgorithms/ciphers/XORCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/XORCipher.java @@ -9,22 +9,22 @@ * using a given key. This cipher works by applying the XOR bitwise operation between * the bytes of the input text and the corresponding bytes of the key (repeating the key * if necessary). - * + *

* Usage: * - Encryption: Converts plaintext into a hexadecimal-encoded ciphertext. * - Decryption: Converts the hexadecimal ciphertext back into plaintext. - * + *

* Characteristics: * - Symmetric: The same key is used for both encryption and decryption. * - Simple but vulnerable: XOR encryption is insecure for real-world cryptography, - * especially when the same key is reused. - * + * especially when the same key is reused. + *

* Example: * Plaintext: "Hello!" * Key: "key" * Encrypted: "27090c03120b" * Decrypted: "Hello!" - * + *

* Reference: XOR Cipher - Wikipedia * * @author lcsjunior @@ -42,7 +42,7 @@ private XORCipher() { * If the key is shorter than the input, it wraps around (cyclically). * * @param inputBytes The input byte array (plaintext or ciphertext). - * @param keyBytes The key byte array used for XOR operation. + * @param keyBytes The key byte array used for XOR operation. * @return A new byte array containing the XOR result. */ public static byte[] xor(final byte[] inputBytes, final byte[] keyBytes) { @@ -58,9 +58,9 @@ public static byte[] xor(final byte[] inputBytes, final byte[] keyBytes) { * The result is a hexadecimal-encoded string representing the ciphertext. * * @param plainText The input plaintext to encrypt. - * @param key The encryption key. - * @throws IllegalArgumentException if the key is empty. + * @param key The encryption key. * @return A hexadecimal string representing the encrypted text. + * @throws IllegalArgumentException if the key is empty. */ public static String encrypt(final String plainText, final String key) { if (key.isEmpty()) { @@ -78,9 +78,9 @@ public static String encrypt(final String plainText, final String key) { * with the specified key. The result is the original plaintext. * * @param cipherText The hexadecimal string representing the encrypted text. - * @param key The decryption key (must be the same as the encryption key). - * @throws IllegalArgumentException if the key is empty. + * @param key The decryption key (must be the same as the encryption key). * @return The decrypted plaintext. + * @throws IllegalArgumentException if the key is empty. */ public static String decrypt(final String cipherText, final String key) { if (key.isEmpty()) { diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index cc2e9105229a..c46ac3dbd4a1 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java @@ -5,7 +5,7 @@ /** * The A5Cipher class implements the A5/1 stream cipher, which is a widely used * encryption algorithm, particularly in mobile communications. - * + *

* This implementation uses a key stream generator to produce a stream of bits * that are XORed with the plaintext bits to produce the ciphertext. * @@ -22,7 +22,7 @@ public class A5Cipher { /** * Constructs an A5Cipher instance with the specified session key and frame counter. * - * @param sessionKey a BitSet representing the session key used for encryption. + * @param sessionKey a BitSet representing the session key used for encryption. * @param frameCounter a BitSet representing the frame counter that helps in key stream generation. */ public A5Cipher(BitSet sessionKey, BitSet frameCounter) { @@ -32,7 +32,7 @@ public A5Cipher(BitSet sessionKey, BitSet frameCounter) { /** * Encrypts the given plaintext bits using the A5/1 cipher algorithm. - * + *

* This method generates a key stream and XORs it with the provided plaintext * bits to produce the ciphertext. * @@ -52,7 +52,7 @@ public BitSet encrypt(BitSet plainTextBits) { /** * Resets the internal counter of the key stream generator. - * + *

* This method can be called to re-initialize the state of the key stream * generator, allowing for new key streams to be generated for subsequent * encryptions. diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java index ee837ef4241a..f755f2e4bc14 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -32,7 +32,7 @@ public class A5KeyStreamGenerator extends CompositeLFSR { * configurations and initializes them. *

* - * @param sessionKey a BitSet representing the session key used for key stream generation. + * @param sessionKey a BitSet representing the session key used for key stream generation. * @param frameCounter a BitSet representing the frame counter that influences the key stream. */ @Override diff --git a/src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java index 18ad913784dc..4ae6c7910416 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java @@ -4,7 +4,9 @@ public interface BaseLFSR { void initialize(BitSet sessionKey, BitSet frameCounter); + boolean clock(); + int SESSION_KEY_LENGTH = 64; int FRAME_COUNTER_LENGTH = 22; } diff --git a/src/main/java/com/thealgorithms/conversions/AffineConverter.java b/src/main/java/com/thealgorithms/conversions/AffineConverter.java index 199a6dd517d5..548369e6641b 100644 --- a/src/main/java/com/thealgorithms/conversions/AffineConverter.java +++ b/src/main/java/com/thealgorithms/conversions/AffineConverter.java @@ -3,7 +3,7 @@ /** * A utility class to perform affine transformations of the form: * y = slope * x + intercept. - * + *

* This class supports inversion and composition of affine transformations. * It is immutable, meaning each instance represents a fixed transformation. */ @@ -14,7 +14,7 @@ public final class AffineConverter { /** * Constructs an AffineConverter with the given slope and intercept. * - * @param inSlope The slope of the affine transformation. + * @param inSlope The slope of the affine transformation. * @param inIntercept The intercept (constant term) of the affine transformation. * @throws IllegalArgumentException if either parameter is NaN. */ diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java index 4bd9c74a1751..4d69095484b5 100644 --- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java @@ -124,7 +124,7 @@ public static boolean validForBase(String n, int base) { * Method to convert any integer from base b1 to base b2. Works by * converting from b1 to decimal, then decimal to b2. * - * @param n The integer to be converted. + * @param n The integer to be converted. * @param b1 Beginning base. * @param b2 End base. * @return n in base b2. diff --git a/src/main/java/com/thealgorithms/conversions/AnytoAny.java b/src/main/java/com/thealgorithms/conversions/AnytoAny.java index e7bdbc2b79c4..d5ecb18e3535 100644 --- a/src/main/java/com/thealgorithms/conversions/AnytoAny.java +++ b/src/main/java/com/thealgorithms/conversions/AnytoAny.java @@ -2,7 +2,7 @@ /** * A utility class for converting numbers from any base to any other base. - * + *

* This class provides a method to convert a source number from a given base * to a destination number in another base. Valid bases range from 2 to 10. */ @@ -14,10 +14,10 @@ private AnytoAny() { * Converts a number from a source base to a destination base. * * @param sourceNumber The number in the source base (as an integer). - * @param sourceBase The base of the source number (between 2 and 10). - * @param destBase The base to which the number should be converted (between 2 and 10). - * @throws IllegalArgumentException if the bases are not between 2 and 10. + * @param sourceBase The base of the source number (between 2 and 10). + * @param destBase The base to which the number should be converted (between 2 and 10). * @return The converted number in the destination base (as an integer). + * @throws IllegalArgumentException if the bases are not between 2 and 10. */ public static int convertBase(int sourceNumber, int sourceBase, int destBase) { if (sourceBase < 2 || sourceBase > 10 || destBase < 2 || destBase > 10) { @@ -32,7 +32,7 @@ public static int convertBase(int sourceNumber, int sourceBase, int destBase) { * Converts a number from a given base to its decimal representation (base 10). * * @param number The number in the original base. - * @param base The base of the given number. + * @param base The base of the given number. * @return The decimal representation of the number. */ private static int toDecimal(int number, int base) { @@ -51,7 +51,7 @@ private static int toDecimal(int number, int base) { * Converts a decimal (base 10) number to a specified base. * * @param decimal The decimal number to convert. - * @param base The destination base for conversion. + * @param base The destination base for conversion. * @return The number in the specified base. */ private static int fromDecimal(int decimal, int base) { diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java index a5615dc002f5..a6a738328dc8 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java @@ -4,8 +4,8 @@ import java.util.List; /** - * Class that provides methods to convert a decimal number to a string representation - * in any specified base between 2 and 36. + * Class that provides methods to convert a decimal number to a string representation + * in any specified base between 2 and 36. * * @author Varun Upadhyay (...) */ diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java index e8d033e0093c..6b3cfd37c01d 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java @@ -12,6 +12,7 @@ private DecimalToBinary() { /** * Converts a decimal number to a binary number using a conventional algorithm. + * * @param decimalNumber the decimal number to convert * @return the binary representation of the decimal number */ @@ -31,6 +32,7 @@ public static int convertUsingConventionalAlgorithm(int decimalNumber) { /** * Converts a decimal number to a binary number using a bitwise algorithm. + * * @param decimalNumber the decimal number to convert * @return the binary representation of the decimal number */ diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java b/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java index 47a1e36b27e3..86d384c6e786 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java @@ -14,6 +14,7 @@ private DecimalToHexadecimal() { /** * Converts a decimal number to a hexadecimal string. + * * @param decimal the decimal number to convert * @return the hexadecimal representation of the decimal number */ diff --git a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java index 07acefc9fb14..eb91fa1afb81 100644 --- a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java @@ -34,8 +34,8 @@ public class HexaDecimalToBinary { * * * @param numHex the hexadecimal string (e.g., "A1", "7F") - * @throws NumberFormatException if the input string is not a valid hexadecimal number * @return the binary string representation, padded to 8 bits (e.g., "10100001") + * @throws NumberFormatException if the input string is not a valid hexadecimal number */ public String convert(String numHex) { int conHex = Integer.parseInt(numHex, 16); diff --git a/src/main/java/com/thealgorithms/conversions/IPConverter.java b/src/main/java/com/thealgorithms/conversions/IPConverter.java index 765cb0201dd5..8ff65d6beabb 100644 --- a/src/main/java/com/thealgorithms/conversions/IPConverter.java +++ b/src/main/java/com/thealgorithms/conversions/IPConverter.java @@ -4,7 +4,7 @@ * Converts an IPv4 address to its binary equivalent and vice-versa. * IP to Binary: Converts an IPv4 address to its binary equivalent. * Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101 - * + *

* Binary to IP: Converts a binary equivalent to an IPv4 address. * Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5 * @@ -16,6 +16,7 @@ private IPConverter() { /** * Converts an IPv4 address to its binary equivalent. + * * @param ip The IPv4 address to convert. * @return The binary equivalent of the IPv4 address. */ @@ -29,6 +30,7 @@ public static String ipToBinary(String ip) { /** * Converts a single octet to its 8-bit binary representation. + * * @param octet The octet to convert (0-255). * @return The 8-bit binary representation as a String. */ @@ -45,6 +47,7 @@ private static String octetToBinary(int octet) { /** * Converts a binary equivalent to an IPv4 address. + * * @param binary The binary equivalent to convert. * @return The IPv4 address of the binary equivalent. */ diff --git a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java index d42ffd027514..e16b0ca3ef34 100644 --- a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java +++ b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java @@ -6,7 +6,7 @@ /** * A utility class for converting between IPv6 and IPv4 addresses. - * + *

* - Converts IPv4 to IPv6-mapped IPv6 address. * - Extracts IPv4 address from IPv6-mapped IPv6. * - Handles exceptions for invalid inputs. @@ -23,7 +23,7 @@ private IPv6Converter() { * * @param ipv4Address The IPv4 address in string format. * @return The corresponding IPv6-mapped IPv6 address. - * @throws UnknownHostException If the IPv4 address is invalid. + * @throws UnknownHostException If the IPv4 address is invalid. * @throws IllegalArgumentException If the IPv6 address is not a mapped IPv4 address. */ public static String ipv4ToIpv6(String ipv4Address) throws UnknownHostException { diff --git a/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java b/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java index fec437668fe6..40d6cfa531c2 100644 --- a/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java +++ b/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java @@ -49,7 +49,7 @@ private IntegerToRoman() { * * @param num the integer value to convert (must be greater than 0) * @return the Roman numeral representation of the input integer - * or an empty string if the input is non-positive + * or an empty string if the input is non-positive */ public static String integerToRoman(int num) { if (num <= 0) { diff --git a/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java index a3973da0c586..383ffe334bef 100644 --- a/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java +++ b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java @@ -7,10 +7,10 @@ * Converts text to Morse code and vice-versa. * Text to Morse code: Each letter is separated by a space and each word is separated by a pipe (|). * Example: "HELLO WORLD" -> ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." - * + *

* Morse code to text: Each letter is separated by a space and each word is separated by a pipe (|). * Example: ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." -> "HELLO WORLD" - * + *

* Applications: Used in radio communications and algorithmic challenges. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java index d91ce6eb3634..2357a2353c1a 100644 --- a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java +++ b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java @@ -2,7 +2,6 @@ /** * Class for converting an octal number to a decimal number. Octal numbers are based on 8, using digits from 0 to 7. - * */ public final class OctalToDecimal { private static final int OCTAL_BASE = 8; diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java index 84cbff09db6b..2bf5ba88b396 100644 --- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java +++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java @@ -50,9 +50,9 @@ public static void main(String[] args) { /** * Conversion from the HSV-representation to the RGB-representation. * - * @param hue Hue of the color. + * @param hue Hue of the color. * @param saturation Saturation of the color. - * @param value Brightness-value of the color. + * @param value Brightness-value of the color. * @return The tuple of RGB-components. */ public static int[] hsvToRgb(double hue, double saturation, double value) { @@ -79,9 +79,9 @@ public static int[] hsvToRgb(double hue, double saturation, double value) { /** * Conversion from the RGB-representation to the HSV-representation. * - * @param red Red-component of the color. + * @param red Red-component of the color. * @param green Green-component of the color. - * @param blue Blue-component of the color. + * @param blue Blue-component of the color. * @return The tuple of HSV-components. */ public static double[] rgbToHsv(int red, int green, int blue) { diff --git a/src/main/java/com/thealgorithms/conversions/RomanToInteger.java b/src/main/java/com/thealgorithms/conversions/RomanToInteger.java index a634c720326f..2f212cb40fac 100644 --- a/src/main/java/com/thealgorithms/conversions/RomanToInteger.java +++ b/src/main/java/com/thealgorithms/conversions/RomanToInteger.java @@ -66,7 +66,7 @@ private static int romanSymbolToInt(final char symbol) { * @param roman the Roman numeral string * @return the integer value of the Roman numeral * @throws IllegalArgumentException if the input contains invalid Roman characters - * @throws NullPointerException if the input is {@code null} + * @throws NullPointerException if the input is {@code null} */ public static int romanToInt(String roman) { if (roman == null) { diff --git a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java index 00690b2c0f9b..9da99230742b 100644 --- a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java +++ b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java @@ -121,12 +121,12 @@ public UnitsConverter(final Map, AffineConverter> basicConv /** * Converts a value from one unit to another. * - * @param inputUnit the unit of the input value. + * @param inputUnit the unit of the input value. * @param outputUnit the unit to convert the value into. - * @param value the value to convert. + * @param value the value to convert. * @return the converted value in the target unit. * @throws IllegalArgumentException if inputUnit equals outputUnit. - * @throws NoSuchElementException if no conversion exists between the units. + * @throws NoSuchElementException if no conversion exists between the units. */ public double convert(final String inputUnit, final String outputUnit, final double value) { if (inputUnit.equals(outputUnit)) { diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java index b709e16fd1f6..819746802d4c 100644 --- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java +++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java @@ -73,8 +73,8 @@ public Item get() { * If the buffer is full, this operation will overwrite the oldest data. * * @param item The item to be added. - * @throws IllegalArgumentException if the item is null. * @return {@code true} if the item was successfully added, {@code false} if the buffer was full and the item overwrote existing data. + * @throws IllegalArgumentException if the item is null. */ public boolean put(Item item) { if (item == null) { @@ -110,7 +110,7 @@ private static class CircularPointer { * Constructor to initialize the circular pointer. * * @param pointer The initial position of the pointer. - * @param max The maximum size (capacity) of the circular buffer. + * @param max The maximum size (capacity) of the circular buffer. */ CircularPointer(int pointer, int max) { this.pointer = pointer; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java index f0d8ea8f7ff3..bbc8be658a0b 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java @@ -20,7 +20,6 @@ * * @param The type of keys maintained by this cache. * @param The type of mapped values. - * * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ public class LFUCache { @@ -40,8 +39,8 @@ private class Node { /** * Constructs a new {@code Node} with the specified key, value, and frequency. * - * @param key The key associated with this node. - * @param value The value stored in this node. + * @param key The key associated with this node. + * @param value The value stored in this node. * @param frequency The frequency of usage of this node. */ Node(K key, V value, int frequency) { @@ -102,7 +101,7 @@ public V get(K key) { * If the key already exists, the value is updated and its frequency is incremented. * If the cache is full, the least frequently used item is removed before inserting the new item. * - * @param key The key associated with the value to be inserted or updated. + * @param key The key associated with the value to be inserted or updated. * @param value The value to be inserted or updated. */ public void put(K key, V value) { diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java index ec39d2a6ed28..2f56e0104e6b 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java @@ -142,7 +142,7 @@ private void moveNodeToLast(Entry entry) { /** * Associates the specified value with the specified key in this cache. * - * @param key the key with which the specified value is to be associated + * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key */ public void put(K key, V value) { diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java index 93b13e6ad654..b91c391e9a91 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java @@ -9,7 +9,7 @@ * In contrast to the Least Recently Used (LRU) strategy, the MRU caching policy * evicts the most recently accessed items first. This class provides methods to * store key-value pairs and manage cache eviction based on this policy. - * + *

* For more information, refer to: * MRU on Wikipedia. * diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java index 741caa59c5b5..30db15e983f7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java @@ -103,9 +103,9 @@ static void initializeGraph(Graph graph, List data) { /** * Implements the A* pathfinding algorithm to find the shortest path from a start node to a destination node. * - * @param from the starting node - * @param to the destination node - * @param graph the graph representation of the problem + * @param from the starting node + * @param to the destination node + * @param graph the graph representation of the problem * @param heuristic the heuristic estimates for each node * @return a PathAndDistance object containing the shortest 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 47c5f0d0b98e..627047d876c0 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -82,7 +82,7 @@ public void go() { arr[i] = new Edge(u, ve, w); } int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance - // between source + // between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { @@ -128,15 +128,15 @@ public void go() { */ 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 + // method // Just shows results of computation, if graph is passed to it. The + // graph should int i; int j; int v = vertex; int e = edge; int neg = 0; double[] dist = new double[v]; // Distance array for holding the finalized shortest path - // distance between source + // distance between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java index 15ae5225533c..d3c86f81017b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java @@ -7,25 +7,25 @@ * This class provides a method to check if a given undirected graph is bipartite using Depth-First Search (DFS). * A bipartite graph is a graph whose vertices can be divided into two disjoint sets such that no two vertices * within the same set are adjacent. In other words, all edges must go between the two sets. - * + *

* The implementation leverages DFS to attempt to color the graph using two colors. If we can color the graph such * that no two adjacent vertices have the same color, the graph is bipartite. - * + *

* Example: * Input (Adjacency Matrix): * {{0, 1, 0, 1}, - * {1, 0, 1, 0}, - * {0, 1, 0, 1}, - * {1, 0, 1, 0}} - * + * {1, 0, 1, 0}, + * {0, 1, 0, 1}, + * {1, 0, 1, 0}} + *

* Output: YES (This graph is bipartite) - * + *

* Input (Adjacency Matrix): * {{0, 1, 1, 0}, - * {1, 0, 1, 0}, - * {1, 1, 0, 1}, - * {0, 0, 1, 0}} - * + * {1, 0, 1, 0}, + * {1, 1, 0, 1}, + * {0, 0, 1, 0}} + *

* Output: NO (This graph is not bipartite) */ public final class BipartiteGraphDFS { @@ -34,7 +34,7 @@ private BipartiteGraphDFS() { /** * Helper method to perform DFS and check if the graph is bipartite. - * + *

* During DFS traversal, this method attempts to color each vertex in such a way * that no two adjacent vertices share the same color. * @@ -42,7 +42,7 @@ private BipartiteGraphDFS() { * @param adj Adjacency list of the graph where each index i contains a list of adjacent vertices * @param color Array to store the color assigned to each vertex (-1 indicates uncolored) * @param node Current vertex being processed - * @return True if the graph (or component of the graph) is bipartite, otherwise false + * @return True if the graph (or component of the graph) is bipartite, otherwise false */ private static boolean bipartite(int v, ArrayList> adj, int[] color, int node) { if (color[node] == -1) { @@ -66,7 +66,7 @@ private static boolean bipartite(int v, ArrayList> adj, int[] * * @param v Number of vertices in the graph * @param adj Adjacency list of the graph - * @return True if the graph is bipartite, otherwise false + * @return True if the graph is bipartite, otherwise false */ public static boolean isBipartite(int v, ArrayList> adj) { int[] color = new int[v + 1]; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java index 520a1681774a..30091859d0bd 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java @@ -44,7 +44,7 @@ class Edge { * will be added to it. * * @param startNode the starting Node from the edge - * @param endNode the ending Node from the edge + * @param endNode the ending Node from the edge */ public void addEdge(E startNode, E endNode) { Node start = null; @@ -93,7 +93,7 @@ public int countGraphs() { /** * Implementation of depth first search. * - * @param n the actual visiting node + * @param n the actual visiting node * @param visited A list of already visited nodes in the depth first search * @return returns a set of visited nodes */ diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java index 70699a9461f7..5acf8b5f0b79 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java @@ -20,11 +20,11 @@ public DijkstraAlgorithm(int vertexCount) { /** * Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices. - * + *

* The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i} * to vertex {@code j}. A value of 0 indicates no edge exists between the vertices. * - * @param graph The graph represented as an adjacency matrix. + * @param graph The graph represented as an adjacency matrix. * @param source The source vertex. * @return An array where the value at each index {@code i} represents the shortest distance from the source vertex to vertex {@code i}. * @throws IllegalArgumentException if the source vertex is out of range. diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java index db716580d689..8c742ee3b467 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java @@ -11,7 +11,7 @@ * to find the maximum matching in a general graph. The algorithm efficiently * handles cases where the graph contains odd-length cycles by contracting * "blossoms" and finding augmenting paths. - *

+ *

* Documentation of Algorithm (Stanford University) *

* Wikipedia Documentation @@ -26,7 +26,7 @@ private EdmondsBlossomAlgorithm() { /** * Finds the maximum matching in a general graph (Edmonds Blossom Algorithm). * - * @param edges A list of edges in the graph. + * @param edges A list of edges in the graph. * @param vertexCount The number of vertices in the graph. * @return A list of matched pairs of vertices. */ @@ -127,9 +127,9 @@ public static List maximumMatching(Iterable edges, int vertexCount /** * Updates the matching along the augmenting path found. * - * @param match The matching array. + * @param match The matching array. * @param parent The parent array used during the BFS. - * @param u The starting node of the augmenting path. + * @param u The starting node of the augmenting path. */ private static void updateMatching(int[] match, int[] parent, int u) { while (u != UNMATCHED) { @@ -144,10 +144,10 @@ private static void updateMatching(int[] match, int[] parent, int u) { /** * Finds the base of a node in the blossom. * - * @param base The base array. + * @param base The base array. * @param parent The parent array. - * @param u One end of the edge. - * @param v The other end of the edge. + * @param u One end of the edge. + * @param v The other end of the edge. * @return The base of the node or UNMATCHED. */ private static int findBase(int[] base, int[] parent, int u, int v) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index 66dc6782a8be..bd954022a58b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -11,7 +11,7 @@ * The distance matrix is updated iteratively to find the shortest distance between any two vertices * by considering each vertex as an intermediate step. *

- * + *

* Reference: Floyd-Warshall Algorithm */ public class FloydWarshall { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java index b0970f36ddc5..78266e3e1535 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java @@ -48,7 +48,7 @@ public boolean removeAdjacentVertex(E to) { * vertices * * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to + * @param to the data of the vertex the edge is going to * @return returns false if the edge doesn't exist, returns true if the edge * exists and is removed */ @@ -70,7 +70,7 @@ public boolean removeEdge(E from, E to) { * this method adds an edge to the graph between two specified vertices * * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to + * @param to the data of the vertex the edge is going to * @return returns true if the edge did not exist, return false if it * already did */ diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java index 5c95850c4971..10ff8d7650c7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java @@ -10,7 +10,7 @@ *

For more details, see the * Wikipedia article. * - * @author Akshay Dubey + * @author Akshay Dubey */ public class HamiltonianCycle { @@ -25,7 +25,7 @@ public class HamiltonianCycle { * @param graph Adjacency matrix representing the graph G(V, E), where V is * the set of vertices and E is the set of edges. * @return An array representing the Hamiltonian cycle if found, otherwise an - * array filled with -1 indicating no Hamiltonian cycle exists. + * array filled with -1 indicating no Hamiltonian cycle exists. */ public int[] findHamiltonianCycle(int[][] graph) { // Single vertex graph diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java index 351bd5b009e8..aa2df55a82df 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java @@ -7,16 +7,16 @@ /** * This class implements Johnson's algorithm for finding all-pairs shortest paths in a weighted, * directed graph that may contain negative edge weights. - * + *

* Johnson's algorithm works by using the Bellman-Ford algorithm to compute a transformation of the * input graph that removes all negative weights, allowing Dijkstra's algorithm to be used for * efficient shortest path computations. - * + *

* Time Complexity: O(V^2 * log(V) + V*E) * Space Complexity: O(V^2) - * + *

* Where V is the number of vertices and E is the number of edges in the graph. - * + *

* For more information, please visit {@link https://en.wikipedia.org/wiki/Johnson%27s_algorithm} */ public final class JohnsonsAlgorithm { @@ -79,7 +79,7 @@ public static double[][] convertToEdgeList(double[][] graph) { * Implements the Bellman-Ford algorithm to compute the shortest paths from a new vertex * to all other vertices. This is used to calculate the weight function h(v) for reweighting. * - * @param edges The edge list of the graph. + * @param edges The edge list of the graph. * @param numVertices The number of vertices in the original graph. * @return An array of modified weights for each vertex. */ @@ -122,7 +122,7 @@ private static double[] bellmanFord(double[][] edges, int numVertices) { /** * Reweights the graph using the modified weights computed by Bellman-Ford. * - * @param graph The original graph. + * @param graph The original graph. * @param modifiedWeights The modified weights from Bellman-Ford. * @return The reweighted graph. */ @@ -146,7 +146,7 @@ public static double[][] reweightGraph(double[][] graph, double[] modifiedWeight * Implements Dijkstra's algorithm for finding shortest paths from a source vertex. * * @param reweightedGraph The reweighted graph to run Dijkstra's on. - * @param source The source vertex. + * @param source The source vertex. * @param modifiedWeights The modified weights from Bellman-Ford. * @return An array of shortest distances from the source to all other vertices. */ @@ -182,7 +182,7 @@ public static double[] dijkstra(double[][] reweightedGraph, int source, double[] * Finds the vertex with the minimum distance value from the set of vertices * not yet included in the shortest path tree. * - * @param dist Array of distances. + * @param dist Array of distances. * @param visited Array of visited vertices. * @return The index of the vertex with minimum distance. */ diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java index 9a97bc3f4808..5b3acbd188ee 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java @@ -13,7 +13,7 @@ * maintains a mapping of vertices to their adjacent vertices. * * @param the type of vertices, extending Comparable to ensure that vertices - * can be compared + * can be compared */ class AdjacencyList> { @@ -67,7 +67,7 @@ Set getVertices() { * A class that performs topological sorting on a directed graph using Kahn's algorithm. * * @param the type of vertices, extending Comparable to ensure that vertices - * can be compared + * can be compared */ class TopologicalSort> { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java index 78a184f042b5..70ff9b404b0b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java @@ -52,7 +52,7 @@ * | v | v v * 1 5 <--- 6 * - * + *

* The SCCs of this transpose graph are the same as the original graph. */ public class Kosaraju { @@ -74,7 +74,7 @@ public class Kosaraju { * 3. Find SCCs by performing DFS on the transpose graph * 4. Return the list of SCCs * - * @param v the number of vertices in the graph + * @param v the number of vertices in the graph * @param list the adjacency list representing the directed graph * @return a list of SCCs where each SCC is a list of vertices */ @@ -87,7 +87,8 @@ public List> kosaraju(int v, List> list) { /** * Performs DFS on the original graph to sort nodes by their finishing times. - * @param v the number of vertices in the graph + * + * @param v the number of vertices in the graph * @param list the adjacency list representing the original graph */ private void sortEdgesByLowestFinishTime(int v, List> list) { @@ -101,7 +102,8 @@ private void sortEdgesByLowestFinishTime(int v, List> list) { /** * Creates the transpose (reverse) of the original graph. - * @param v the number of vertices in the graph + * + * @param v the number of vertices in the graph * @param list the adjacency list representing the original graph * @return the adjacency list representing the transposed graph */ @@ -120,7 +122,8 @@ private List> createTransposeMatrix(int v, List> lis /** * Finds the strongly connected components (SCCs) by performing DFS on the transposed graph. - * @param v the number of vertices in the graph + * + * @param v the number of vertices in the graph * @param transposeGraph the adjacency list representing the transposed graph */ public void findStronglyConnectedComponents(int v, List> transposeGraph) { @@ -137,8 +140,9 @@ public void findStronglyConnectedComponents(int v, List> transpose /** * Performs DFS on the original graph and pushes nodes onto the stack in order of their finish time. + * * @param node the current node being visited - * @param vis array to keep track of visited nodes + * @param vis array to keep track of visited nodes * @param list the adjacency list of the graph */ private void dfs(int node, int[] vis, List> list) { @@ -153,8 +157,9 @@ private void dfs(int node, int[] vis, List> list) { /** * Performs DFS on the transposed graph to find the strongly connected components. + * * @param node the current node being visited - * @param vis array to keep track of visited nodes + * @param vis array to keep track of visited nodes * @param list the adjacency list of the transposed graph */ private void dfs2(int node, int[] vis, List> list) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index 25c4548daa7a..d65fa9c0527c 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -40,9 +40,9 @@ static class Edge { /** * Adds an edge to the graph. * - * @param graph the adjacency list representing the graph - * @param from the source vertex of the edge - * @param to the destination vertex of the edge + * @param graph the adjacency list representing the graph + * @param from the source vertex of the edge + * @param to the destination vertex of the edge * @param weight the weight of the edge */ static void addEdge(HashSet[] graph, int from, int to, int weight) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java index c1d47df457da..902fd2fb5df7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java @@ -103,7 +103,6 @@ public int numberOfVertices() { * Updates the number of edges in the graph * * @param newNumberOfEdges the new number of edges - * */ private void setNumberOfEdges(int newNumberOfEdges) { this.edgeCount = newNumberOfEdges; @@ -140,7 +139,7 @@ private int[][] adjacency() { * Checks if two vertices are connected by an edge * * @param from the parent vertex to check for adjacency - * @param to the child vertex to check for adjacency + * @param to the child vertex to check for adjacency * @return whether or not the vertices are adjancent */ private boolean adjacencyOfEdgeDoesExist(int from, int to) { @@ -161,7 +160,7 @@ public boolean vertexDoesExist(int aVertex) { * Checks if two vertices are connected by an edge * * @param from the parent vertex to check for adjacency - * @param to the child vertex to check for adjacency + * @param to the child vertex to check for adjacency * @return whether or not the vertices are adjancent */ public boolean edgeDoesExist(int from, int to) { @@ -176,7 +175,7 @@ public boolean edgeDoesExist(int from, int to) { * This method adds an edge to the graph between two specified vertices * * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to + * @param to the data of the vertex the edge is going to * @return returns true if the edge did not exist, return false if it * already did */ @@ -197,7 +196,7 @@ public boolean addEdge(int from, int to) { * this method removes an edge from the graph between two specified vertices * * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to + * @param to the data of the vertex the edge is going to * @return returns false if the edge doesn't exist, returns true if the edge * exists and is removed */ @@ -243,9 +242,9 @@ public List depthFirstOrder(int startVertex) { * first traversal recursively on the graph * * @param currentVertex the currently exploring vertex - * @param visited the array of values denoting whether or not that vertex - * has been visited - * @param orderList the list to add vertices to as they are visited + * @param visited the array of values denoting whether or not that vertex + * has been visited + * @param orderList the list to add vertices to as they are visited */ private void depthFirstOrder(int currentVertex, boolean[] visited, List orderList) { // If this vertex has already been visited, do nothing and return @@ -261,7 +260,7 @@ private void depthFirstOrder(int currentVertex, boolean[] visited, List // Get the adjacency array for this vertex int[] adjacent = adjMatrix[currentVertex]; 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 + // currentVertex and the vertex if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) { depthFirstOrder(i, visited, orderList); } @@ -311,7 +310,7 @@ public List breadthFirstOrder(int startVertex) { // check each node int[] adjacent = adjMatrix[currentVertex]; 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 + // 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/README.md b/src/main/java/com/thealgorithms/datastructures/graphs/README.md index 4798e372667b..eaeb76971a02 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/README.md +++ b/src/main/java/com/thealgorithms/datastructures/graphs/README.md @@ -1,5 +1,7 @@ ## Graphs -Graph is a useful data structure for representing most of the real-world problems involving a set of users/candidates/nodes and their relations. A graph consists of two parameters: + +Graph is a useful data structure for representing most of the real-world problems involving a set of +users/candidates/nodes and their relations. A graph consists of two parameters: ``` V = a set of vertices @@ -8,33 +10,52 @@ E = a set of edges Each edge in `E` connects any two vertices from `V`. Based on the type of edge, graphs can be of two types: -1. **Directed**: The edges are directed in nature, which means that when there is an edge from node `A` to `B`, it does not imply that there is an edge from `B` to `A`. An example of a directed edge graph is the **follow** feature of social media. If you follow a celebrity, it doesn't imply that they follow you. +1. **Directed**: The edges are directed in nature, which means that when there is an edge from node `A` to `B`, it does + not imply that there is an edge from `B` to `A`. An example of a directed edge graph is the **follow** feature of + social media. If you follow a celebrity, it doesn't imply that they follow you. -2. **Undirected**: The edges don't have any direction. So if `A` and `B` are connected, we can assume that there is an edge from both `A` to `B` and `B` to `A`. For example, in a social media graph, if two persons are friends, it implies that both are friends with each other. +2. **Undirected**: The edges don't have any direction. So if `A` and `B` are connected, we can assume that there is an + edge from both `A` to `B` and `B` to `A`. For example, in a social media graph, if two persons are friends, it + implies that both are friends with each other. ### Components of a Graph -**Vertices:** Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled. +**Vertices:** Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. +Every node/vertex can be labeled or unlabelled. -**Edges:** Edges are used to connect two nodes of the graph. They can be an ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labeled/unlabeled. +**Edges:** Edges are used to connect two nodes of the graph. They can be an ordered pair of nodes in a directed graph. +Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every +edge can be labeled/unlabeled. -Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths in a city, telephone network, or circuit network. Graphs are also used in social networks like LinkedIn, Facebook. For example, on Facebook, each person is represented with a vertex (or node). Each node is a structure and contains information like person id, name, gender, locale, etc. +Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths +in a city, telephone network, or circuit network. Graphs are also used in social networks like LinkedIn, Facebook. For +example, on Facebook, each person is represented with a vertex (or node). Each node is a structure and contains +information like person id, name, gender, locale, etc. ### Graph Representation Graph can be represented in the following ways: -**Set Representation:** Set representation of a graph involves two sets: Set of vertices V = {V1, V2, V3, V4} and set of edges E = {{V1, V2}, {V2, V3}, {V3, V4}, {V4, V1}}. This representation is efficient for memory but does not allow parallel edges. +**Set Representation:** Set representation of a graph involves two sets: Set of vertices V = {V1, V2, V3, V4} and set of +edges E = {{V1, V2}, {V2, V3}, {V3, V4}, {V4, V1}}. This representation is efficient for memory but does not allow +parallel edges. -**Sequential Representation:** This representation of a graph can be represented by means of matrices: Adjacency Matrix, Incidence matrix, and Path matrix. +**Sequential Representation:** This representation of a graph can be represented by means of matrices: Adjacency Matrix, +Incidence matrix, and Path matrix. -**Adjacency Matrix:** This matrix includes information about the adjacent nodes. Here, aij = 1 if there is an edge from Vi to Vj; otherwise, it's 0. It is a matrix of order V×V. +**Adjacency Matrix:** This matrix includes information about the adjacent nodes. Here, aij = 1 if there is an edge from +Vi to Vj; otherwise, it's 0. It is a matrix of order V×V. -**Incidence Matrix:** This matrix includes information about the incidence of edges on the nodes. Here, aij = 1 if the jth edge Ej is incident on the ith vertex Vi; otherwise, it's 0. It is a matrix of order V×E. +**Incidence Matrix:** This matrix includes information about the incidence of edges on the nodes. Here, aij = 1 if the +jth edge Ej is incident on the ith vertex Vi; otherwise, it's 0. It is a matrix of order V×E. -**Path Matrix:** This matrix includes information about the simple path between two vertices. Here, Pij = 1 if there is a path from Vi to Vj; otherwise, it's 0. It is also called the reachability matrix of graph G. +**Path Matrix:** This matrix includes information about the simple path between two vertices. Here, Pij = 1 if there is +a path from Vi to Vj; otherwise, it's 0. It is also called the reachability matrix of graph G. -**Linked Representation:** This representation gives information about the nodes to which a specific node is connected, i.e., adjacency lists. This representation gives the adjacency lists of the vertices with the help of arrays and linked lists. In the adjacency lists, the vertices connected to the specific vertex are arranged in the form of lists that are connected to that vertex. +**Linked Representation:** This representation gives information about the nodes to which a specific node is connected, +i.e., adjacency lists. This representation gives the adjacency lists of the vertices with the help of arrays and linked +lists. In the adjacency lists, the vertices connected to the specific vertex are arranged in the form of lists that are +connected to that vertex. ### Real-Time Applications of Graph @@ -48,7 +69,8 @@ In transportation, graphs are used to find the shortest path. In circuits, graphs can be used to represent circuit points as nodes and wires as edges. Graphs are used in solving puzzles with only one solution, such as mazes. Graphs are used in computer networks for Peer to Peer (P2P) applications. -Graphs, basically in the form of DAG (Directed Acyclic Graph), are used as an alternative to blockchain for cryptocurrency. For example, cryptocurrencies like IOTA and Nano are mainly based on DAG. +Graphs, basically in the form of DAG (Directed Acyclic Graph), are used as an alternative to blockchain for +cryptocurrency. For example, cryptocurrencies like IOTA and Nano are mainly based on DAG. ### Advantages of Graph @@ -62,11 +84,14 @@ Because of their non-linear structure, graphs help in understanding complex prob Graphs use lots of pointers, which can be complex to handle. They can have large memory complexity. -If the graph is represented with an adjacency matrix, then it does not allow parallel edges, and multiplication of the graph is also difficult. +If the graph is represented with an adjacency matrix, then it does not allow parallel edges, and multiplication of the +graph is also difficult. ### Representation -1. **Adjacency Lists**: Each node is represented as an entry, and all the edges are represented as a list emerging from the corresponding node. So, if vertex 1 has edges to 2, 3, and 6, the list corresponding to 1 will have 2, 3, and 6 as entries. Consider the following graph: +1. **Adjacency Lists**: Each node is represented as an entry, and all the edges are represented as a list emerging from + the corresponding node. So, if vertex 1 has edges to 2, 3, and 6, the list corresponding to 1 will have 2, 3, and 6 + as entries. Consider the following graph: ``` 0: 1-->2-->3 @@ -78,7 +103,8 @@ If the graph is represented with an adjacency matrix, then it does not allow par It means there are edges from 0 to 1, 2, and 3; from 1 to 0 and 2, and so on. -2. **Adjacency Matrix**: The graph is represented as a matrix of size |V| x |V|, and an entry 1 in cell (i, j) implies that there is an edge from i to j. 0 represents no edge. The matrix for the above graph: +2. **Adjacency Matrix**: The graph is represented as a matrix of size |V| x |V|, and an entry 1 in cell (i, j) implies + that there is an edge from i to j. 0 represents no edge. The matrix for the above graph: ``` 0 1 2 3 4 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java index 91974ba13319..51035049c896 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java @@ -66,7 +66,7 @@ public class TarjansAlgorithm { /** * Finds and returns the strongly connected components (SCCs) of the directed graph. * - * @param v the number of vertices in the graph + * @param v the number of vertices in the graph * @param graph the adjacency list representation of the graph * @return a list of lists, where each inner list represents a strongly connected component */ @@ -97,12 +97,12 @@ public List> stronglyConnectedComponents(int v, List /** * A utility function to perform DFS and find SCCs. * - * @param u the current vertex being visited - * @param lowTime array to keep track of the low-link values + * @param u the current vertex being visited + * @param lowTime array to keep track of the low-link values * @param insertionTime array to keep track of the insertion times - * @param isInStack boolean array indicating if a vertex is in the stack - * @param st the stack used for DFS - * @param graph the adjacency list representation of the graph + * @param isInStack boolean array indicating if a vertex is in the stack + * @param st the stack used for DFS + * @param graph the adjacency list representation of the graph */ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack st, List> graph) { // Set insertion time and low-link value diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 26ca97736fe9..4f8084290ab1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -102,7 +102,7 @@ int getNumVertices() { * Creates a graph with the specified number of vertices and edges. * * @param numberOfVertices the total number of vertices - * @param listOfEdges a 2D array representing edges where each inner array contains two vertex indices + * @param listOfEdges a 2D array representing edges where each inner array contains two vertex indices * @return a Graph object representing the created graph * @throws IllegalArgumentException if the edge array is invalid or vertices are out of bounds */ @@ -154,7 +154,7 @@ private static boolean isBlank(int color) { /** * Checks if a vertex has adjacent colored vertices * - * @param graph the input graph + * @param graph the input graph * @param vertex the vertex to check * @param colors the array of colors assigned to the vertices * @return {@code true} if the vertex has adjacent colored vertices, {@code false} otherwise @@ -188,7 +188,7 @@ private static Integer[] getSortedNodes(final Graph graph) { /** * Computes the colors already used by the adjacent vertices * - * @param graph the input graph + * @param graph the input graph * @param vertex the vertex to check * @param colors the array of colors assigned to the vertices * @return an array of booleans representing the colors used by the adjacent vertices diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/Readme.md b/src/main/java/com/thealgorithms/datastructures/hashmap/Readme.md index 252b06ea59b0..ca58e2aa538b 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/Readme.md +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/Readme.md @@ -3,16 +3,22 @@ A hash map organizes data so you can quickly look up values for a given key. ## Strengths: + - **Fast lookups**: Lookups take O(1) time on average. - **Flexible keys**: Most data types can be used for keys, as long as they're hashable. ## Weaknesses: + - **Slow worst-case**: Lookups take O(n) time in the worst case. -- **Unordered**: Keys aren't stored in a special order. If you're looking for the smallest key, the largest key, or all the keys in a range, you'll need to look through every key to find it. -- **Single-directional lookups**: While you can look up the value for a given key in O(1) time, looking up the keys for a given value requires looping through the whole dataset—O(n) time. -- **Not cache-friendly**: Many hash table implementations use linked lists, which don't put data next to each other in memory. +- **Unordered**: Keys aren't stored in a special order. If you're looking for the smallest key, the largest key, or all + the keys in a range, you'll need to look through every key to find it. +- **Single-directional lookups**: While you can look up the value for a given key in O(1) time, looking up the keys for + a given value requires looping through the whole dataset—O(n) time. +- **Not cache-friendly**: Many hash table implementations use linked lists, which don't put data next to each other in + memory. ## Time Complexity + | | AVERAGE | WORST | |--------|---------|-------| | Space | O(n) | O(n) | @@ -21,7 +27,9 @@ A hash map organizes data so you can quickly look up values for a given key. | Delete | O(1) | O(n) | ## Internal Structure of HashMap + Internally HashMap contains an array of Node and a node is represented as a class that contains 4 fields: + - int hash - K key - V value @@ -30,20 +38,29 @@ Internally HashMap contains an array of Node and a node is represented as a clas It can be seen that the node contains a reference to its object. So it’s a linked list. ## Performance of HashMap + The performance of HashMap depends on 2 parameters which are named as follows: + - Initial Capacity - Load Factor +**Initial Capacity**: It is the capacity of HashMap at the time of its creation (It is the number of buckets a HashMap +can hold when the HashMap is instantiated). In Java, it is 2^4=16 initially, meaning it can hold 16 key-value pairs. -**Initial Capacity**: It is the capacity of HashMap at the time of its creation (It is the number of buckets a HashMap can hold when the HashMap is instantiated). In Java, it is 2^4=16 initially, meaning it can hold 16 key-value pairs. - -**Load Factor**: It is the percent value of the capacity after which the capacity of Hashmap is to be increased (It is the percentage fill of buckets after which Rehashing takes place). In Java, it is 0.75f by default, meaning the rehashing takes place after filling 75% of the capacity. +**Load Factor**: It is the percent value of the capacity after which the capacity of Hashmap is to be increased (It is +the percentage fill of buckets after which Rehashing takes place). In Java, it is 0.75f by default, meaning the +rehashing takes place after filling 75% of the capacity. -**Threshold**: It is the product of Load Factor and Initial Capacity. In Java, by default, it is (16 * 0.75 = 12). That is, Rehashing takes place after inserting 12 key-value pairs into the HashMap. +**Threshold**: It is the product of Load Factor and Initial Capacity. In Java, by default, it is (16 * 0.75 = 12). That +is, Rehashing takes place after inserting 12 key-value pairs into the HashMap. -**Rehashing** : It is the process of doubling the capacity of the HashMap after it reaches its Threshold. In Java, HashMap continues to rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, …. so on. +**Rehashing** : It is the process of doubling the capacity of the HashMap after it reaches its Threshold. In Java, +HashMap continues to rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, …. so on. -If the initial capacity is kept higher then rehashing will never be done. But keeping it higher increases the time complexity of iteration. So it should be chosen very cleverly to increase performance. The expected number of values should be taken into account to set the initial capacity. The most generally preferred load factor value is 0.75 which provides a good deal between time and space costs. The load factor’s value varies between 0 and 1. +If the initial capacity is kept higher then rehashing will never be done. But keeping it higher increases the time +complexity of iteration. So it should be chosen very cleverly to increase performance. The expected number of values +should be taken into account to set the initial capacity. The most generally preferred load factor value is 0.75 which +provides a good deal between time and space costs. The load factor’s value varies between 0 and 1. ``` Note: From Java 8 onward, Java has started using Self Balancing BST instead of a linked list for chaining. @@ -59,7 +76,12 @@ While both classes use keys to look up values, there are some important differen ## When Hash Map operations cost O(n) time? -**Hash collisions**: If all our keys caused hash collisions, we'd be at risk of having to walk through all of our values for a single lookup (in the example above, we'd have one big linked list). This is unlikely, but it could happen. That's the worst case. +**Hash collisions**: If all our keys caused hash collisions, we'd be at risk of having to walk through all of our values +for a single lookup (in the example above, we'd have one big linked list). This is unlikely, but it could happen. That's +the worst case. -**Dynamic array resizing**: Suppose we keep adding more items to our hash map. As the number of keys and values in our hash map exceeds the number of indices in the underlying array, hash collisions become inevitable. To mitigate this, we could expand our underlying array whenever things start to get crowded. That requires allocating a larger array and rehashing all of our existing keys to figure out their new position—O(n) time. +**Dynamic array resizing**: Suppose we keep adding more items to our hash map. As the number of keys and values in our +hash map exceeds the number of indices in the underlying array, hash collisions become inevitable. To mitigate this, we +could expand our underlying array whenever things start to get crowded. That requires allocating a larger array and +rehashing all of our existing keys to figure out their new position—O(n) time. 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 89e25f4eb0f7..916b9a0f0716 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java @@ -43,7 +43,7 @@ public GenericHashMapUsingArrayList() { * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old value is replaced. * - * @param key the key with which the specified value is to be associated + * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key */ public void put(K key, V value) { 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 8bcf00730acb..1f80416acadd 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -7,7 +7,7 @@ * Cuckoo hashing is a type of open-addressing hash table that resolves collisions * by relocating existing keys. It utilizes two hash functions to minimize collisions * and automatically resizes the table when the load factor exceeds 0.7. - * + *

* For more information on cuckoo hashing, refer to * this Wikipedia page. */ diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java index 10d5dc7decae..d5f2536e8cf6 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java @@ -29,10 +29,9 @@ * ensuring efficient space utilization. *

* - * @see Linear Probing Hash Table - * - * @param the type of keys maintained by this map + * @param the type of keys maintained by this map * @param the type of mapped values + * @see Linear Probing Hash Table */ public class LinearProbingHashMap, Value> extends Map { private int hsize; // size of the hash table diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java index 8cb93edf78f3..2fe46646d1a4 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java @@ -38,7 +38,7 @@ public interface Heap { * Delete an element in the heap. * * @param elementIndex int containing the position in the heap of the - * element to be deleted. + * element to be deleted. */ void deleteElement(int elementIndex) throws EmptyHeapException; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index 57cc9e37122d..ba1a62978be2 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -28,6 +28,7 @@ public class HeapElement { private final Object additionalInfo; // Constructors + /** * Creates a HeapElement with the specified key and additional information. * @@ -113,6 +114,7 @@ public HeapElement(Double key) { } // Getters + /** * Returns the object containing the additional information provided by the user. * @@ -132,6 +134,7 @@ public double getKey() { } // Overridden object methods + /** * Returns a string representation of the heap element. * diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java index 7ad92e8ba3c1..172265ef7f18 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java @@ -17,12 +17,12 @@ private KthElementFinder() { /** * Finds the Kth largest element in the given array. * Uses a min-heap of size K to track the largest K elements. - * + *

* Time Complexity: O(n * log(k)), where n is the size of the input array. * Space Complexity: O(k), as we maintain a heap of size K. * * @param nums the input array of integers - * @param k the desired Kth position (1-indexed, i.e., 1 means the largest element) + * @param k the desired Kth position (1-indexed, i.e., 1 means the largest element) * @return the Kth largest element in the array */ public static int findKthLargest(int[] nums, int k) { @@ -39,12 +39,12 @@ public static int findKthLargest(int[] nums, int k) { /** * Finds the Kth smallest element in the given array. * Uses a max-heap of size K to track the smallest K elements. - * + *

* Time Complexity: O(n * log(k)), where n is the size of the input array. * Space Complexity: O(k), as we maintain a heap of size K. * * @param nums the input array of integers - * @param k the desired Kth position (1-indexed, i.e., 1 means the smallest element) + * @param k the desired Kth position (1-indexed, i.e., 1 means the smallest element) * @return the Kth smallest element in the array */ public static int findKthSmallest(int[] nums, int k) { diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java index 1c91d24f0fb5..619f8e0ec4e2 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java @@ -150,7 +150,7 @@ public ArrayList inOrder() { /** * Auxiliary function for in-order traversal * - * @param n the current node + * @param n the current node * @param lst the list to store the elements in in-order */ private void inOrderAux(Node n, ArrayList lst) { diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java index 4e74aaec4a10..57dd8f609179 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java @@ -7,11 +7,11 @@ * two heaps: a max-heap and a min-heap. The max-heap stores the smaller half * of the numbers, and the min-heap stores the larger half. * This data structure ensures that retrieving the median is efficient. - * + *

* Time Complexity: * - Adding a number: O(log n) due to heap insertion. * - Finding the median: O(1). - * + *

* Space Complexity: O(n), where n is the total number of elements added. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java b/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java index e41711f05914..3415407d1d56 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java @@ -6,10 +6,10 @@ /** * This class provides a method to merge multiple sorted arrays into a single sorted array. * It utilizes a min-heap to efficiently retrieve the smallest elements from each array. - * + *

* Time Complexity: O(n * log k), where n is the total number of elements across all arrays * and k is the number of arrays. - * + *

* Space Complexity: O(k) for the heap, where k is the number of arrays. * * @author Hardvan @@ -24,10 +24,10 @@ private MergeKSortedArrays() { * 1. Create a min-heap to store elements in the format: {value, array index, element index} * 2. Add the first element from each array to the heap * 3. While the heap is not empty, remove the smallest element from the heap - * and add it to the result array. If there are more elements in the same array, - * add the next element to the heap. - * Continue until all elements have been processed. - * The result array will contain all elements in sorted order. + * and add it to the result array. If there are more elements in the same array, + * add the next element to the heap. + * Continue until all elements have been processed. + * The result array will contain all elements in sorted order. * 4. Return the result array. * * @param arrays a 2D array, where each subarray is sorted in non-decreasing order diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index 3a4822142b5f..459e6c2c2ca9 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -7,17 +7,17 @@ * A Min Heap implementation where each node's key is lower than or equal to its children's keys. * This data structure provides O(log n) time complexity for insertion and deletion operations, * and O(1) for retrieving the minimum element. - * + *

* Properties: * 1. Complete Binary Tree * 2. Parent node's key ≤ Children nodes' keys * 3. Root contains the minimum element - * + *

* Example usage: * ```java * List elements = Arrays.asList( - * new HeapElement(5, "Five"), - * new HeapElement(2, "Two") + * new HeapElement(5, "Five"), + * new HeapElement(2, "Two") * ); * MinHeap heap = new MinHeap(elements); * heap.insertElement(new HeapElement(1, "One")); diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/Readme.md b/src/main/java/com/thealgorithms/datastructures/heaps/Readme.md index 5e77c68dee8c..de8d86a5f6af 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/Readme.md +++ b/src/main/java/com/thealgorithms/datastructures/heaps/Readme.md @@ -2,10 +2,10 @@

A Heap is a special Tree-based data structure in which the tree is a complete binary tree. ##

Complete Binary Tree

+

A complete binary tree is a binary tree in which all the levels except the last level, i.e., leaf node should be completely filled, and all the nodes should be left-justified.

- ``` 10 / \ @@ -16,8 +16,8 @@ in which all the levels except the last level, i.e., leaf node should be complet COMPLETE BINARY TREE ``` - ##

Types of Heap

+

Generally, Heaps can be of two types:
Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. @@ -25,8 +25,6 @@ in which all the levels except the last level, i.e., leaf node should be complet Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.

- - ``` 10 / \ @@ -48,6 +46,7 @@ in which all the levels except the last level, i.e., leaf node should be complet ``` ##

Min Heap Construction Algorithm

+ ``` Step 1 − Create a new node at the end of heap. Step 2 − Assign new value to the node. @@ -69,6 +68,7 @@ Add 15 ``` ##

Min Heap Deletion Algorithm

+ ``` Step 1 − Remove root node. Step 2 − Move the last element of last level to root. @@ -90,6 +90,7 @@ Delete 10 ``` ##

Time Complexity (Min Heap)

+ @@ -122,7 +123,11 @@ Delete 10

Heapsort: Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. -Priority Queues: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also in O(logn) time which is a O(n) operation in Binary Heap. Heap Implemented priority queues are used in Graph algorithms like Prim’s Algorithm and Dijkstra’s algorithm. +Priority Queues: Priority queues can be efficiently implemented using Binary Heap because it supports +insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are +variations of Binary Heap. These variations perform union also in O(logn) time which is a O(n) operation in Binary Heap. +Heap Implemented priority queues are used in Graph algorithms like Prim’s Algorithm and Dijkstra’s algorithm. -Order statistics: The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an array. +Order statistics: The Heap data structure can be used to efficiently find the kth smallest (or largest) +element in an array.

diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java index 3902d08bfd14..4305f2a52fce 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java @@ -35,7 +35,7 @@ static final class Node { * destination position (position1). If either position is invalid, no loop * will be created. * - * @param head the head node of the linked list + * @param head the head node of the linked list * @param position1 the position in the list where the loop should end * @param position2 the position in the list where the loop should start */ @@ -74,7 +74,7 @@ static void createLoop(Node head, int position1, int position2) { * @param head the head node of the linked list * @return true if a loop is detected, false otherwise * @see - * Floyd's Cycle Detection Algorithm + * Floyd's Cycle Detection Algorithm */ static boolean detectLoop(Node head) { Node sptr = head; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 58898ddc0fcf..bc89777b78a4 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -224,7 +224,7 @@ public void insertTail(int x, DoublyLinkedList doublyLinkedList) { /** * Insert an element at the index * - * @param x Element to be inserted + * @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) { @@ -265,7 +265,7 @@ public Link deleteHead() { tail = null; } else { head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so - // will be removed + // will be removed } --size; return temp; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/README.md b/src/main/java/com/thealgorithms/datastructures/lists/README.md index 6aefa4c98e6d..84e067614417 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/README.md +++ b/src/main/java/com/thealgorithms/datastructures/lists/README.md @@ -1,7 +1,9 @@ ## Linked List + ### Description -LinkedList is a data structure in which data is stored in a linear manner. It usually contains a data field and a link to the memory location of the next node. +LinkedList is a data structure in which data is stored in a linear manner. It usually contains a data field and a link +to the memory location of the next node. ### Structure @@ -12,12 +14,15 @@ class LinkedList{ } ``` -The `next` variable points to the next node in the data structure and value stores the data. Any number of nodes can be linked in this manner. The structure will be: - +The `next` variable points to the next node in the data structure and value stores the data. Any number of nodes can be +linked in this manner. The structure will be: ### Properties -1. Linked list does not provide indexing like an array. For accessing a node at position `p` , θ(p) nodes need to be accessed. -2. Main advantage of linked list is addition and removal of nodes near the end and beginning of lists. It can be done just by updating the link (O(1) time) + +1. Linked list does not provide indexing like an array. For accessing a node at position `p` , θ(p) nodes need to + be accessed. +2. Main advantage of linked list is addition and removal of nodes near the end and beginning of lists. It can be done + just by updating the link (O(1) time) 3. Unlike an array, its size is not predefined. So any number of nodes can be appended. ### File descriptions: @@ -26,7 +31,10 @@ The `next` variable points to the next node in the data structure and value stor 2. `SinglyLinkedList.java` : The classic case of single links. 3. `CountSinglyLinkedListRecursion.java`: Recursively counts the size of a list. 4. `CreateAndDetectLoop.java` : Create and detect a loop in a linked list. -5. `DoublyLinkedList.java` : A modification of singly linked list which has a `prev` pointer to point to the previous node. -6. `MergeKSortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list). +5. `DoublyLinkedList.java` : A modification of singly linked list which has a `prev` pointer to point to the previous + node. +6. `MergeKSortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient + sorting algorithm for linked list). 7. `RandomNode.java` : Selects a random node from given linked list and diplays it. -8. `SkipList.java` : Data Structure used for storing a sorted list of elements with help of a Linked list hierarchy that connects to subsequences of elements. +8. `SkipList.java` : Data Structure used for storing a sorted list of elements with help of a Linked list hierarchy that + connects to subsequences of elements. diff --git a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java index 3c4b9331266c..949609f3c6b2 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java @@ -15,6 +15,7 @@ public int length(Node head) { } return count; } + // reverse function public Node reverse(Node head, int count, int k) { if (count < k) { @@ -37,6 +38,7 @@ public Node reverse(Node head, int count, int k) { } return prev; } + public Node reverseKGroup(Node head, int k) { int count = length(head); Node ans = reverse(head, count, k); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java b/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java index 7676cc343653..c11d5ee44795 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java @@ -26,7 +26,7 @@ *
  • Space Complexity: O(1), as we only use a constant amount of additional space.
  • * *

    - * + *

    * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public class RotateSinglyLinkedLists { @@ -35,7 +35,7 @@ public class RotateSinglyLinkedLists { * Rotates a singly linked list to the right by `k` positions. * * @param head The head node of the singly linked list. - * @param k The number of positions to rotate the list to the right. + * @param k The number of positions to rotate the list to the right. * @return The head of the rotated linked list. */ public Node rotateRight(Node head, int k) { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java index a40e9b2a1a66..bcfca27d8125 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java @@ -27,7 +27,7 @@ public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { * Recursively searches for a given value in the linked list. * * @param node the head node to start the search. - * @param key the integer value to be searched for. + * @param key the integer value to be searched for. * @return {@code true} if the value `key` is present in the list; otherwise, {@code false}. */ private boolean searchRecursion(Node node, int key) { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java index d5d3f31f4b66..7599d9f5c221 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java @@ -41,7 +41,6 @@ public SinglyLinkedList(Node head, int size) { /** * Detects if there is a loop in the singly linked list using floy'd turtle * and hare algorithm. - * */ public boolean detectLoop() { Node currentNodeFast = head; @@ -59,6 +58,7 @@ public boolean detectLoop() { /** * Return the node in the middle of the list * If the length of the list is even then return item number length/2 + * * @return middle node of the list */ public Node middle() { @@ -76,7 +76,6 @@ public Node middle() { /** * Swaps nodes of two given values a and b. - * */ public void swapNodes(int valueFirst, int valueSecond) { if (valueFirst == valueSecond) { @@ -124,7 +123,6 @@ public void swapNodes(int valueFirst, int valueSecond) { /** * Reverse a singly linked list[Iterative] from a given node till the end - * */ public Node reverseListIter(Node node) { Node prev = null; @@ -145,9 +143,9 @@ public Node reverseListIter(Node node) { // the reversed linkedlist return prev; } + /** * Reverse a singly linked list[Recursive] from a given node till the end - * */ public Node reverseListRec(Node head) { if (head == null || head.next == null) { @@ -204,7 +202,6 @@ public Node getHead() { /** * Set head of the list. - * */ public void setHead(Node head) { this.head = head; @@ -305,7 +302,7 @@ public void insert(int data) { /** * Inserts a new node at a specified position of the list * - * @param data data to be stored in a new node + * @param data data to be stored in a new node * @param position position at which a new node is to be inserted */ public void insertNth(int data, int position) { @@ -385,10 +382,10 @@ public int getNth(int index) { /** * @param position to check position - * @param low low index - * @param high high index + * @param low low index + * @param high high index * @throws IndexOutOfBoundsException if {@code position} not in range - * {@code low} to {@code high} + * {@code low} to {@code high} */ public void checkBounds(int position, int low, int high) { if (position > high || position < low) { @@ -507,7 +504,7 @@ class Node { * Constructor * * @param value Value to be put in the node - * @param next Reference to the next node + * @param next Reference to the next node */ Node(int value, Node next) { this.value = value; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java index 3309ab24917d..764e395ef285 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java @@ -44,6 +44,7 @@ public class SkipList> { /** * Function for determining height of new nodes. + * * @see HeightStrategy */ private final HeightStrategy heightStrategy; @@ -217,6 +218,7 @@ public String toString() { * Value container. * Each node have pointers to the closest nodes left and right from current * on each layer of nodes height. + * * @param type of elements */ private static class Node { @@ -268,10 +270,12 @@ private void checkLayer(int layer) { /** * Height strategy is a way of calculating maximum height for skip list * and height for each node. + * * @see BernoulliHeightStrategy */ public interface HeightStrategy { int height(int expectedSize); + int nodeHeight(int heightCap); } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java index a5ca48670f2c..e1e4d25a0481 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -128,7 +128,7 @@ public int remove() { throw new RuntimeException("Queue is Empty"); } else { int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is - // the greatest + // the greatest // Swap max and last element int temp = queueArray[1]; diff --git a/src/main/java/com/thealgorithms/datastructures/queues/Queue.java b/src/main/java/com/thealgorithms/datastructures/queues/Queue.java index 046b79a020ed..0ab41d497a67 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/Queue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/Queue.java @@ -4,7 +4,7 @@ * This class implements a Queue data structure using an array. * A queue is a first-in-first-out (FIFO) data structure where elements are * added to the rear and removed from the front. - * + *

    * Note: This implementation is not thread-safe. */ public final class Queue { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/README.md b/src/main/java/com/thealgorithms/datastructures/queues/README.md index ef1b89b5c9a4..c4e22649fabe 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/README.md +++ b/src/main/java/com/thealgorithms/datastructures/queues/README.md @@ -1,79 +1,94 @@ # Queue + - The Queue interface is present in the `java.util` package. - It is an ordered list of objects that follows the **FIFO** (First-In-First-Out) principle. ## Characteristics of a Queue + - The Queue is used to insert elements at the end of the queue and removes elements from the beginning of the queue. - It supports all methods of Collection interface including insertion, deletion etc. - LinkedList, ArrayBlockingQueue and PriorityQueue are the most commonly used implementations. - ## Types Of Queue:- -- **FIFO Queue (First-In-First-Out):** This is the most common type of queue where the first item added is the first one to be removed. It follows a strict order of insertion and removal. +- **FIFO Queue (First-In-First-Out):** This is the most common type of queue where the first item added is the first one + to be removed. It follows a strict order of insertion and removal. -- **Priority Queue:** Elements in this queue are assigned priorities, and the item with the highest priority is dequeued first. It doesn't strictly follow the FIFO order. +- **Priority Queue:** Elements in this queue are assigned priorities, and the item with the highest priority is dequeued + first. It doesn't strictly follow the FIFO order. -- **Double-ended Queue (Deque):** A queue that allows elements to be added and removed from both ends. It can function as both a FIFO queue and a LIFO stack. +- **Double-ended Queue (Deque):** A queue that allows elements to be added and removed from both ends. It can function + as both a FIFO queue and a LIFO stack. -- **Circular Queue:** In this type, the last element is connected to the first element, forming a circular structure. It's often used for tasks like managing memory buffers. +- **Circular Queue:** In this type, the last element is connected to the first element, forming a circular structure. + It's often used for tasks like managing memory buffers. -- **Blocking Queue:** Designed for multithreaded applications, it provides thread-safety and blocking operations. Threads can wait until an element is available or space is free. +- **Blocking Queue:** Designed for multithreaded applications, it provides thread-safety and blocking operations. + Threads can wait until an element is available or space is free. -- **Priority Blocking Queue:** Similar to a priority queue but thread-safe, it allows multiple threads to access and modify the queue concurrently while maintaining priority. +- **Priority Blocking Queue:** Similar to a priority queue but thread-safe, it allows multiple threads to access and + modify the queue concurrently while maintaining priority. -- **Delay Queue:** Used for scheduling tasks to run after a specific delay or at a certain time. Elements are removed from the queue when their delay expires. +- **Delay Queue:** Used for scheduling tasks to run after a specific delay or at a certain time. Elements are removed + from the queue when their delay expires. ## Declaration + `Queue queue = new PriorityQueue();` ## Important operations -| Operations | Description |Time Complexity -| ----------- | ----------- |----------- -|Enqueue|Adds an item to the queue|O(1) -|Dequeue|Removes an item from the queue|O(1) -|Front|Gets the front item from the queue|O(1) -|Rear|Gets the last item from the queue|O(n) +| Operations | Description | Time Complexity +|------------|------------------------------------|----------------- +| Enqueue | Adds an item to the queue | O(1) +| Dequeue | Removes an item from the queue | O(1) +| Front | Gets the front item from the queue | O(1) +| Rear | Gets the last item from the queue | O(n) ## Enqueue - It adds an item to the rear of the queue. - For example: If we have `1, 2, 3, 4, 5` in queue, and if we call Enqueue(8), +It adds an item to the rear of the queue. + +For example: If we have `1, 2, 3, 4, 5` in queue, and if we call Enqueue(8), `8` will be added to last index of queue -> `1, 2, 3, 4, 5, 8`. + ## Dequeue - - It removes an item to the front of the queue. - - For example: If we have `1, 2, 3, 4, 5` in queue, and we call Dequeue(), + +It removes an item to the front of the queue. + +For example: If we have `1, 2, 3, 4, 5` in queue, and we call Dequeue(), `1` will be removed from front of queue and returned -> `2, 3, 4, 5`. -## Front - It returns an item to the front of the queue. +## Front + +It returns an item to the front of the queue. For example: If we have `1, 2, 3, 5` in queue, and we call Front(), `1` will be returned (without removing it from the queue). ## Rear - It returns an item to the rear of the queue. - - For example: If we have `1, 2, 3, 5` in queue, and we call Rear(), + +It returns an item to the rear of the queue. + +For example: If we have `1, 2, 3, 5` in queue, and we call Rear(), `5` will be returned (without removing it from the queue). # Real Life Applications + `Task Scheduling in Operating Systems:` -Processes in a multitasking system are often scheduled using queues. For example, the ready queue contains processes ready to be executed. +Processes in a multitasking system are often scheduled using queues. For example, the ready queue contains processes +ready to be executed. `Multi-threaded Programming:` diff --git a/src/main/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximum.java b/src/main/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximum.java index d6720dd01e29..93b4b8da495c 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximum.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximum.java @@ -27,7 +27,7 @@ private SlidingWindowMaximum() { * * * @param nums the input array of integers - * @param k the size of the sliding window + * @param k the size of the sliding window * @return an array containing the maximum element for each sliding window */ public static int[] maxSlidingWindow(int[] nums, int k) { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java b/src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java index 999c963fab93..c2a9ee4467be 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java @@ -7,7 +7,7 @@ * This class is used to control the rate of requests in a distributed system. * It allows a certain number of requests (tokens) to be processed in a time frame, * based on the defined refill rate. - * + *

    * Applications: Computer networks, API rate limiting, distributed systems, etc. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/README.md b/src/main/java/com/thealgorithms/datastructures/stacks/README.md index 55c3ffd7de64..3715e1c113ad 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/README.md +++ b/src/main/java/com/thealgorithms/datastructures/stacks/README.md @@ -1,13 +1,17 @@ # STACK -- Stack is an ADT (abstract data type) that is a collection of elements where items are added and removed from the end, known as the "top" of the stack. +- Stack is an ADT (abstract data type) that is a collection of elements where items are added and removed from the end, + known as the "top" of the stack. -- Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the first item to be removed. +- Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the + first item to be removed. ## Declaration - `Stack stack=new Stack();` + +`Stack stack=new Stack();` # Functionalities + Stack is based on two functions (methods)- ## push(element) @@ -34,12 +38,15 @@ For example: If we have `1, 3, 5 , 9` in stack, and we call pop(), the function will return `9` and the stack will change to `1, 3, 5`. -# Real Life Applications - - `Undo mechanisms:` - Many software applications use stacks to implement an "undo" feature. +# Real Life Applications + +- `Undo mechanisms:` + Many software applications use stacks to implement an "undo" feature. - - `Browser history:` - The "back" button in a web browser is implemented using a stack, allowing users to navigate through previously visited pages. +- `Browser history:` + The "back" button in a web browser is implemented using a stack, allowing users to navigate through previously visited + pages. - - `Function calls and recursion:` - The computer's call stack keeps track of function calls, allowing programs to remember where to return after a function finishes execution. +- `Function calls and recursion:` + The computer's call stack keeps track of function calls, allowing programs to remember where to return after a + function finishes execution. diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index e9de14b53302..855479026d87 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -51,14 +51,14 @@ public static void reverseStack(Stack stack) { * Inserts the specified element at the bottom of the stack. * *

    This method is a helper for {@link #reverseStack(Stack)}. - * + *

    * Steps: * 1. If the stack is empty, push the element and return. * 2. Remove the top element from the stack. * 3. Recursively insert the new element at the bottom of the stack. * 4. Push the removed element back onto the stack. * - * @param stack the stack in which to insert the element; should not be null + * @param stack the stack in which to insert the element; should not be null * @param element the element to insert at the bottom of the stack */ private static void insertAtBottom(Stack stack, int element) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java index 1962eaa0a106..bb508dd2cfc7 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java @@ -4,7 +4,7 @@ /** * Given a sorted array. Create a balanced binary search tree from it. - * + *

    * Steps: 1. Find the middle element of array. This will act as root 2. Use the * left half recursively to create left subtree 3. Use the right half * recursively to create right subtree @@ -12,6 +12,7 @@ public final class BSTFromSortedArray { private BSTFromSortedArray() { } + public static Node createBST(int[] array) { if (array == null || array.length == 0) { return null; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java index 97c2667002b6..8d284145325c 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java @@ -3,8 +3,6 @@ import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** - * - * *

    Binary Search Tree (Iterative)

    * *

    diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java index 6c1f4f672ff0..dab708d33dc1 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java @@ -3,10 +3,8 @@ import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** - * - * *

    Binary Search Tree (Recursive)

    - * + *

    * An implementation of BST recursively. In recursive implementation the checks * are down the tree First root is checked if not found then its children are * checked Binary Search Tree is a binary tree which satisfies three properties: @@ -79,7 +77,7 @@ private Node delete(Node node, int data) { * Recursive insertion of value in BST. * * @param node to check if the data can be inserted in current node or its - * subtree + * subtree * @param data the value to be inserted * @return the modified value of the root parameter after insertion */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java index 5c1334ffa0e8..79863adac3f8 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java @@ -8,7 +8,7 @@ * *

    * A recursive implementation of generic type BST. - * + *

    * Reference: Wiki links for BST *

    * @@ -129,7 +129,7 @@ private Node delete(Node node, T data) { * Recursive insertion of value in BST. * * @param node to check if the data can be inserted in current node or its - * subtree + * subtree * @param data the value to be inserted * @return the modified value of the root parameter after insertion */ @@ -202,7 +202,7 @@ private void inOrder(Node node) { * Recursively traverse the tree using inorder traversal and keep adding * elements to argument list. * - * @param node the root node + * @param node the root node * @param sortedList the list to add the srted elements into */ private void inOrderSort(Node node, List sortedList) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java index cf0de4a92030..840f8a2a82eb 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java @@ -3,50 +3,14 @@ import java.util.LinkedList; import java.util.Queue; -/* - * This entire class is used to build a Binary Tree data structure. There is the - * Node Class and the Tree Class, both explained below. - */ -/** - * A binary tree is a data structure in which an element has two - * successors(children). The left child is usually smaller than the parent, and - * the right child is usually bigger. - * - * @author Unknown - */ public class BinaryTree { - /** - * This class implements the nodes that will go on the Binary Tree. They - * consist of the data in them, the node to the left, the node to the right, - * and the parent from which they came from. - * - * @author Unknown - */ static class Node { - - /** - * Data for the node - */ public int data; - /** - * The Node to the left of this one - */ public Node left; - /** - * The Node to the right of this one - */ public Node right; - /** - * The parent of this node - */ public Node parent; - /** - * Constructor of Node - * - * @param value Value to put in the node - */ Node(int value) { data = value; left = null; @@ -55,65 +19,20 @@ static class Node { } } - /** - * The root of the Binary Tree - */ private Node root; + private int size; // Keep track of the number of nodes - /** - * Constructor - */ public BinaryTree() { root = null; + size = 0; // Initialize size } - /** - * Parameterized Constructor - */ - public BinaryTree(Node root) { - this.root = root; - } - - /** - * Method to find a Node with a certain value - * - * @param key Value being looked for - * @return The node if it finds it, otherwise returns the parent - */ - public Node find(int key) { - Node current = root; - while (current != null) { - if (key < current.data) { - if (current.left == null) { - return current; // The key isn't exist, returns the parent - } - current = current.left; - } else if (key > current.data) { - if (current.right == null) { - return current; - } - current = current.right; - } else { // If you find the value return it - return current; - } - } - return null; - } - - /** - * Inserts certain value into the Binary Tree - * - * @param value Value to be inserted - */ public void put(int value) { Node newNode = new Node(value); if (root == null) { root = newNode; } else { - // This will return the soon to be parent of the value you're inserting Node parent = find(value); - - // This if/else assigns the new node to be either the left or right child of the parent if (value < parent.data) { parent.left = newNode; parent.left.parent = parent; @@ -122,209 +41,148 @@ public void put(int value) { parent.right.parent = parent; } } + size++; // Increment size on insertion } - /** - * Deletes a given value from the Binary Tree - * - * @param value Value to be deleted - * @return If the value was deleted - */ public boolean remove(int value) { - // temp is the node to be deleted Node temp = find(value); - - // If the value doesn't exist - if (temp.data != value) { + if (temp == null || temp.data != value) { return false; } // No children - if (temp.right == null && temp.left == null) { + if (temp.left == null && temp.right == null) { if (temp == root) { root = null; - } // This if/else assigns the new node to be either the left or right child of the - // parent - else if (temp.parent.data < temp.data) { + } else if (temp.parent.data < temp.data) { temp.parent.right = null; } else { temp.parent.left = null; } - return true; - } // Two children + } + // Two children else if (temp.left != null && temp.right != null) { Node successor = findSuccessor(temp); - - // The left tree of temp is made the left tree of the successor - successor.left = temp.left; - successor.left.parent = successor; - - // If the successor has a right child, the child's grandparent is it's new parent - if (successor.parent != temp) { + temp.data = successor.data; // Replace temp's data with successor's data + if (successor == successor.parent.left) { + successor.parent.left = successor.right; + if (successor.right != null) { + successor.right.parent = successor.parent; + } + } else { + successor.parent.right = successor.right; if (successor.right != null) { successor.right.parent = successor.parent; - successor.parent.left = successor.right; - } else { - successor.parent.left = null; } - successor.right = temp.right; - successor.right.parent = successor; } - + } + // One child + else { + Node child = (temp.left != null) ? temp.left : temp.right; if (temp == root) { - successor.parent = null; - root = successor; - } // If you're not deleting the root - else { - successor.parent = temp.parent; - - // This if/else assigns the new node to be either the left or right child of the - // parent + root = child; + if (child != null) { + child.parent = null; // Update parent reference + } + } else { + child.parent = temp.parent; if (temp.parent.data < temp.data) { - temp.parent.right = successor; + temp.parent.right = child; } else { - temp.parent.left = successor; + temp.parent.left = child; } } - return true; - } // One child - else { - // If it has a right child - if (temp.right != null) { - if (temp == root) { - root = temp.right; - return true; - } + } - temp.right.parent = temp.parent; + // Decrement size after successful removal + size--; + return true; + } - // Assigns temp to left or right child - if (temp.data < temp.parent.data) { - temp.parent.left = temp.right; - } else { - temp.parent.right = temp.right; - } - } // If it has a left child - else { - if (temp == root) { - root = temp.left; - return true; + public Node find(int key) { + Node current = root; + while (current != null) { + if (key < current.data) { + if (current.left == null) { + return current; // Return parent } - - temp.left.parent = temp.parent; - - // Assigns temp to left or right side - if (temp.data < temp.parent.data) { - temp.parent.left = temp.left; - } else { - temp.parent.right = temp.left; + current = current.left; + } else if (key > current.data) { + if (current.right == null) { + return current; // Return parent } + current = current.right; + } else { + return current; // Found node } - return true; } + return null; + } + + public Node getRoot() { + return root; + } + + public int size() { + return size; // Getter for size } - /** - * This method finds the Successor to the Node given. Move right once and go - * left down the tree as far as you can - * - * @param n Node that you want to find the Successor of - * @return The Successor of the node - */ public Node findSuccessor(Node n) { if (n.right == null) { return n; } Node current = n.right; - Node parent = n.right; - while (current != null) { - parent = current; + while (current.left != null) { current = current.left; } - return parent; - } - - /** - * Returns the root of the Binary Tree - * - * @return the root of the Binary Tree - */ - public Node getRoot() { - return root; + return current; } - /** - * Prints leftChild - root - rightChild This is the equivalent of a depth - * first search - * - * @param localRoot The local root of the binary tree - */ - public void inOrder(Node localRoot) { - if (localRoot != null) { - inOrder(localRoot.left); - System.out.print(localRoot.data + " "); - inOrder(localRoot.right); + // Breadth-First Search (Level Order Traversal) + public void bfs() { + if (root == null) { + return; } - } + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + Node current = queue.poll(); + System.out.print(current.data + " "); - /** - * Prints root - leftChild - rightChild - * - * @param localRoot The local root of the binary tree - */ - public void preOrder(Node localRoot) { - if (localRoot != null) { - System.out.print(localRoot.data + " "); - preOrder(localRoot.left); - preOrder(localRoot.right); + if (current.left != null) { + queue.add(current.left); + } + if (current.right != null) { + queue.add(current.right); + } } } - /** - * Prints leftChild - rightChild - root - * - * @param localRoot The local root of the binary tree - */ - public void postOrder(Node localRoot) { - if (localRoot != null) { - postOrder(localRoot.left); - postOrder(localRoot.right); - System.out.print(localRoot.data + " "); + // In-order Traversal + public void inOrder(Node node) { + if (node != null) { + inOrder(node.left); + System.out.print(node.data + " "); + inOrder(node.right); } } - /** - * Prints the tree in a breadth first search order This is similar to - * pre-order traversal, but instead of being implemented with a stack (or - * recursion), it is implemented with a queue - * - * @param localRoot The local root of the binary tree - */ - public void bfs(Node localRoot) { - // Create a queue for the order of the nodes - Queue queue = new LinkedList<>(); - - // If the give root is null, then we don't add to the queue - // and won't do anything - if (localRoot != null) { - queue.add(localRoot); + // Pre-order Traversal + public void preOrder(Node node) { + if (node != null) { + System.out.print(node.data + " "); + preOrder(node.left); + preOrder(node.right); } + } - // Continue until the queue is empty - while (!queue.isEmpty()) { - // Get the next node on the queue to visit - localRoot = queue.remove(); - - // Print the data from the node we are visiting - System.out.print(localRoot.data + " "); - - // Add the children to the queue if not null - if (localRoot.right != null) { - queue.add(localRoot.right); - } - if (localRoot.left != null) { - queue.add(localRoot.left); - } + // Post-order Traversal + public void postOrder(Node node) { + if (node != null) { + postOrder(node.left); + postOrder(node.right); + System.out.print(node.data + " "); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java index 214e111b9f1a..adcc7898e3a4 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java @@ -5,20 +5,20 @@ /** * Problem Statement Ceil value for any number x in a collection is a number y * which is either equal to x or the least greater number than x. - * + *

    * Problem: Given a binary search tree containing positive integer values. Find * ceil value for a given key in O(lg(n)) time. In case if it is not present * return -1. - * + *

    * Ex.1. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 10. Answer: 20 - * + *

    * Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 22 Answer: 25 - * + *

    * Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 52 Answer: -1 - * + *

    * Solution 1: Brute Force Solution: Do an inorder traversal and save result * into an array. Iterate over the array to get an element equal to or greater * than current key. Time Complexity: O(n) Space Complexity: O(n) for auxillary diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java index 0c2b44d78d74..cba288ef8e25 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java @@ -5,12 +5,13 @@ * Trees with only distinct values are supported. * Key points: * 1. According to the definition of a BST, each node in a tree must be in range [min, max], - * where 'min' and 'max' values represent the child nodes (left, right). + * where 'min' and 'max' values represent the child nodes (left, right). * 2. The smallest possible node value is Integer.MIN_VALUE, the biggest - Integer.MAX_VALUE. */ public final class CheckBinaryTreeIsValidBST { private CheckBinaryTreeIsValidBST() { } + public static boolean isBST(BinaryTree.Node root) { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java index 9aa4d5a1fef2..52adc3d97f98 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java @@ -17,6 +17,7 @@ public final class CheckIfBinaryTreeBalanced { private CheckIfBinaryTreeBalanced() { } + /** * Recursive is BT balanced implementation * diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java index 17d84bf11d54..30868a154122 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java @@ -6,18 +6,18 @@ * Check if a binary tree is symmetric or not. * A binary tree is a symmetric tree if the left and right subtree of root are mirror image. * Below is a symmetric tree - * 1 - * / \ - * 2 2 - * / \ / \ - * 3 4 4 3 - * + * 1 + * / \ + * 2 2 + * / \ / \ + * 3 4 4 3 + *

    * Below is not symmetric because values is different in last level - * 1 - * / \ - * 2 2 - * / \ / \ - * 3 5 4 3 + * 1 + * / \ + * 2 2 + * / \ / \ + * 3 5 4 3 *

    * Approach: * Recursively check for left and right subtree of root diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java index 04caa0b9e9d2..1041e2a6ca04 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java @@ -20,6 +20,7 @@ public final class CreateBinaryTreeFromInorderPreorder { private CreateBinaryTreeFromInorderPreorder() { } + public static Node createTree(final Integer[] preorder, final Integer[] inorder) { if (preorder == null || inorder == null) { return null; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java index a2e36f33dd4b..51468dd64d50 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java @@ -23,6 +23,7 @@ private static final class Node { } private final Node root; + public GenericTree() { // Constructor Scanner scn = new Scanner(System.in); root = createTreeG(null, 0, scn); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java index 5a001ff9ab9f..62a8bd38a955 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java @@ -8,26 +8,27 @@ /** * Given tree is traversed in an 'inorder' way: LEFT -> ROOT -> RIGHT. * Below are given the recursive and iterative implementations. - * + *

    * Complexities: * Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree. - * + *

    * Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 - * \ - * 6 - * \ - * 7 - * \ - * 8 + * \ + * 6 + * \ + * 7 + * \ + * 8 * * @author Albina Gimaletdinova on 21/02/2023 */ public final class InorderTraversal { private InorderTraversal() { } + public static List recursiveInorder(BinaryTree.Node root) { List result = new ArrayList<>(); recursiveInorder(root, result); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index 5190e82f74ef..b27fabab5248 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -50,7 +50,6 @@ public class KDTree { * Builds the KDTree from the specified coordinates of the points * * @param pointsCoordinates Array of initial points coordinates - * */ KDTree(int[][] pointsCoordinates) { if (pointsCoordinates.length == 0) { @@ -105,7 +104,6 @@ public String toString() { * * @param p1 First point * @param p2 Second point - * * @return The comparable distance between the two points */ public static int comparableDistance(Point p1, Point p2) { @@ -120,10 +118,9 @@ public static int comparableDistance(Point p1, Point p2) { /** * Find the comparable distance between two points with ignoring specified axis * - * @param p1 First point - * @param p2 Second point + * @param p1 First point + * @param p2 Second point * @param axis The axis to ignore - * * @return The distance between the two points */ public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { @@ -172,7 +169,6 @@ public int getAxis() { * Get the nearest child according to the specified point * * @param point The point to find the nearest child to - * * @return The nearest child Node */ public Node getNearChild(Point point) { @@ -187,7 +183,6 @@ public Node getNearChild(Point point) { * Get the farthest child according to the specified point * * @param point The point to find the farthest child to - * * @return The farthest child Node */ public Node getFarChild(Point point) { @@ -216,8 +211,7 @@ public Node getRoot() { * Builds the KDTree from the specified points * * @param points Array of initial points - * @param depth The current depth of the tree - * + * @param depth The current depth of the tree * @return The root of the KDTree */ private Node build(Point[] points, int depth) { @@ -240,7 +234,6 @@ private Node build(Point[] points, int depth) { * Insert a point into the KDTree * * @param point The point to insert - * */ public void insert(Point point) { if (point.getDimension() != k) { @@ -252,10 +245,9 @@ public void insert(Point point) { /** * Insert a point into a subtree * - * @param root The root of the subtree + * @param root The root of the subtree * @param point The point to insert * @param depth The current depth of the tree - * * @return The root of the KDTree */ private Node insert(Node root, Point point, int depth) { @@ -276,7 +268,6 @@ private Node insert(Node root, Point point, int depth) { * Search for Node corresponding to the specified point in the KDTree * * @param point The point to search for - * * @return The Node corresponding to the specified point */ public Optional search(Point point) { @@ -289,9 +280,8 @@ public Optional search(Point point) { /** * Search for Node corresponding to the specified point in a subtree * - * @param root The root of the subtree to search in + * @param root The root of the subtree to search in * @param point The point to search for - * * @return The Node corresponding to the specified point */ public Optional search(Node root, Point point) { @@ -308,7 +298,6 @@ public Optional search(Node root, Point point) { * Find a point with minimum value in specified axis in the KDTree * * @param axis The axis to find the minimum value in - * * @return The point with minimum value in the specified axis */ public Point findMin(int axis) { @@ -320,7 +309,6 @@ public Point findMin(int axis) { * * @param root The root of the subtree to search in * @param axis The axis to find the minimum value in - * * @return The Node with minimum value in the specified axis of the point */ public Node findMin(Node root, int axis) { @@ -344,7 +332,6 @@ public Node findMin(Node root, int axis) { * Find a point with maximum value in specified axis in the KDTree * * @param axis The axis to find the maximum value in - * * @return The point with maximum value in the specified axis */ public Point findMax(int axis) { @@ -356,7 +343,6 @@ public Point findMax(int axis) { * * @param root The root of the subtree to search in * @param axis The axis to find the maximum value in - * * @return The Node with maximum value in the specified axis of the point */ public Node findMax(Node root, int axis) { @@ -380,7 +366,7 @@ public Node findMax(Node root, int axis) { * Delete the node with the given point. * * @param point the point to delete - * */ + */ public void delete(Point point) { Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found")); root = delete(root, node); @@ -391,7 +377,6 @@ public void delete(Point point) { * * @param root The root of the subtree to delete from * @param node The node to delete - * * @return The new root of the subtree */ private Node delete(Node root, Node node) { @@ -423,7 +408,7 @@ private Node delete(Node root, Node node) { * Finds the nearest point in the tree to the given point. * * @param point The point to find the nearest neighbor to. - * */ + */ public Point findNearest(Point point) { return findNearest(root, point, root).point; } @@ -431,10 +416,10 @@ public Point findNearest(Point point) { /** * Finds the nearest point in a subtree to the given point. * - * @param root The root of the subtree to search in. - * @param point The point to find the nearest neighbor to. + * @param root The root of the subtree to search in. + * @param point The point to find the nearest neighbor to. * @param nearest The nearest neighbor found so far. - * */ + */ private Node findNearest(Node root, Point point, Node nearest) { if (root == null) { 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 95a289493007..1209e5c585ae 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java @@ -52,11 +52,11 @@ public static void main(String[] args) { /** * Depth first search to calculate parent and depth of every vertex * - * @param adj The adjacency list representation of the tree - * @param s The source vertex - * @param p Parent of source + * @param adj The adjacency list representation of the tree + * @param s The source vertex + * @param p Parent of source * @param parent An array to store parents of all vertices - * @param depth An array to store depth 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) { for (int adjacent : adj.get(s)) { @@ -71,9 +71,9 @@ private static void dfs(ArrayList> adj, int s, int p, int[] p /** * Method to calculate Lowest Common Ancestor * - * @param v1 The first vertex - * @param v2 The second vertex - * @param depth An array with depths of all vertices + * @param v1 The first vertex + * @param v2 The second vertex + * @param depth An array with depths of all vertices * @param parent An array with parents of all vertices * @return Returns a vertex that is LCA of v1 and v2 */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java index e7a8e23d6610..ac3b9ef4ac6e 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java @@ -5,8 +5,7 @@ public class LazySegmentTree { /** * Lazy Segment Tree * - * @see - * + * @see */ static class Node { @@ -59,7 +58,7 @@ public void shift() { /** * Create a new node that is the sum of this node and the given node. * - * @param left The left Node of merging + * @param left The left Node of merging * @param right The right Node of merging * @return The new Node. */ @@ -105,7 +104,7 @@ public LazySegmentTree(int[] array) { * * @param array The array to build the LazySegmentTree from. * @param start The start index of the current node. - * @param end The end index of the current node. + * @param end The end index of the current node. * @return The root of the new LazySegmentTree. */ private Node buildTree(int[] array, int start, int end) { @@ -121,10 +120,10 @@ private Node buildTree(int[] array, int start, int end) { /** * Update the value of given range with the given value diff in O(log n) time. * - * @param left The left index of the range to update. + * @param left The left index of the range to update. * @param right The right index of the range to update. - * @param diff The value to add to every index of the range. - * @param curr The current node. + * @param diff The value to add to every index of the range. + * @param curr The current node. */ private void updateRange(int left, int right, int diff, Node curr) { if (left <= curr.start && curr.end <= right) { @@ -144,7 +143,7 @@ private void updateRange(int left, int right, int diff, Node curr) { /** * Get Node of given range in O(log n) time. * - * @param left The left index of the range to update. + * @param left The left index of the range to update. * @param right The right index of the range to update. * @return The Node representing the sum of the given range. */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java index 50dc88381a24..97e28cecd3d4 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java @@ -17,18 +17,19 @@ * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 - * \ - * 6 - * \ - * 7 - * \ - * 8 + * \ + * 6 + * \ + * 7 + * \ + * 8 * * @author Albina Gimaletdinova on 21/02/2023 */ public final class PostOrderTraversal { private PostOrderTraversal() { } + public static List recursivePostOrder(BinaryTree.Node root) { List result = new ArrayList<>(); recursivePostOrder(root, result); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java index 3aceac4d1852..9ea5feea765a 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java @@ -8,26 +8,27 @@ /** * Given tree is traversed in a 'pre-order' way: ROOT -> LEFT -> RIGHT. * Below are given the recursive and iterative implementations. - * + *

    * Complexities: * Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree. - * + *

    * Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 - * \ - * 6 - * \ - * 7 - * \ - * 8 + * \ + * 6 + * \ + * 7 + * \ + * 8 * * @author Albina Gimaletdinova on 17/02/2023 */ public final class PreOrderTraversal { private PreOrderTraversal() { } + public static List recursivePreOrder(BinaryTree.Node root) { List result = new ArrayList<>(); recursivePreOrder(root, result); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java index e0d255b1e784..fe55f010013d 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java @@ -6,8 +6,8 @@ /** * Point is a simple class that represents a point in 2D space. * - * @see Point * @author Sailok Chinta + * @see Point */ class Point { public double x; @@ -22,8 +22,8 @@ class Point { /** * BoundingBox is a simple class that represents a bounding box in 2D space. * - * @see Bounding Box * @author Sailok Chinta + * @see Bounding Box */ class BoundingBox { public Point center; @@ -59,11 +59,11 @@ public boolean intersectsBoundingBox(BoundingBox otherBoundingBox) { /** * QuadTree is a tree data structure that is used to store spatial information * in an efficient way. - * + *

    * This implementation is specific to Point QuadTrees * - * @see Quad Tree * @author Sailok Chinta + * @see Quad Tree */ public class QuadTree { private final BoundingBox boundary; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/README.md b/src/main/java/com/thealgorithms/datastructures/trees/README.md index 89eeb35c5917..4fa121d66494 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/README.md +++ b/src/main/java/com/thealgorithms/datastructures/trees/README.md @@ -1,7 +1,10 @@ ## Tree + ### Description -Tree is a data structure where the data is organized in a hierarchial structure. There should be one root node (which does not have any parent) and all subsequent nodes are represented as children of the root node and its children. If a node has at least one child, it is called `internal` node and nodes with no children are called `leaf` nodes. +Tree is a data structure where the data is organized in a hierarchial structure. There should be one root node (which +does not have any parent) and all subsequent nodes are represented as children of the root node and its children. If a +node has at least one child, it is called `internal` node and nodes with no children are called `leaf` nodes. ### Basic Structure @@ -13,18 +16,24 @@ class Tree{ } ``` -This basic structure is for a binary tree where each internal tree has at least one and at most two children. `left` and `right` represent the two children and `value` is the placeholder for data. - +This basic structure is for a binary tree where each internal tree has at least one and at most two children. `left` +and `right` represent the two children and `value` is the placeholder for data. ### Properties + 1. Tree data structure gives the facility to organize data in a hierarchial structure -2. Tree nodes can be inserted in a sorted order which can be used for searching and inserting data in O(logN) time where N is the number of nodes. +2. Tree nodes can be inserted in a sorted order which can be used for searching and inserting data in O(logN) time where + N is the number of nodes. ### Types of Trees -1. **Binary Search Tree:** A binary tree where the elements are inserted in asorted order. Here the searching can be done in O(logN) time in (depending on the structure) -2. **AVL Tree and Red-Black Tree:** Binary search trees where the height is balanced. Here, searching is guaranteed to be in O(logN) time. + +1. **Binary Search Tree:** A binary tree where the elements are inserted in asorted order. Here the searching can be + done in O(logN) time in (depending on the structure) +2. **AVL Tree and Red-Black Tree:** Binary search trees where the height is balanced. Here, searching is guaranteed to + be in O(logN) time. 3. **Traversal algorithms:**
    -a. **BFS:** Breadth-first-search where all the children at each level are traversed at once.
    -b. **DFS:** Depth-first-search where the first discovered child is traversed first. + a. **BFS:** Breadth-first-search where all the children at each level are traversed at once.
    + b. **DFS:** Depth-first-search where the first discovered child is traversed first. 4. **MultiWay Search Tree:** Tree in sorted order, but more than two children in each internal node. -5. **Trie:** A character based multiway search tree where words can be retrieved based on their prefix. Useful for implementing prefix based search algorithm. \ No newline at end of file +5. **Trie:** A character based multiway search tree where words can be retrieved based on their prefix. Useful for + implementing prefix based search algorithm. \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java index cff27c12f1ca..5eceb2d857ff 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java @@ -8,17 +8,17 @@ * This code checks whether they are the same (structurally identical and have the same values) or * not.

    Example: * 1. Binary trees: - * 1 1 - * / \ / \ - * 2 3 2 3 - * /\ /\ /\ /\ - * 4 5 6 7 4 5 6 7 + * 1 1 + * / \ / \ + * 2 3 2 3 + * /\ /\ /\ /\ + * 4 5 6 7 4 5 6 7 * These trees are the same, so the code returns 'true'. *

    * 2. Binary trees: - * 1 1 - * / \ - * 2 2 + * 1 1 + * / \ + * 2 2 * These trees are NOT the same (the structure differs), so the code returns 'false'. *

    * This solution implements the breadth-first search (BFS) algorithm. @@ -35,6 +35,7 @@ public final class SameTreesCheck { private SameTreesCheck() { } + public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { if (p == null && q == null) { return true; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java index 2668b609aedc..7818747783c6 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java @@ -5,21 +5,21 @@ /** * Implementation of a Splay Tree data structure. - * + *

    * A splay tree is a self-adjusting binary search tree with the additional * property * that recently accessed elements are quick to access again. It performs basic * operations such as insertion, deletion, and searching in O(log n) amortized * time, * where n is the number of elements in the tree. - * + *

    * The key feature of splay trees is the splay operation, which moves a node * closer * to the root of the tree when it is accessed. This operation helps to maintain * good balance and improves the overall performance of the tree. After * performing * a splay operation, the accessed node becomes the new root of the tree. - * + *

    * Splay trees have applications in various areas, including caching, network * routing, * and dynamic optimality analysis. diff --git a/src/main/java/com/thealgorithms/datastructures/trees/Treap.java b/src/main/java/com/thealgorithms/datastructures/trees/Treap.java index 1e5d551cc40b..664c92a9c418 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/Treap.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/Treap.java @@ -6,8 +6,7 @@ * Treap -> Tree + Heap * Also called as cartesian tree * - * @see - * + * @see */ public class Treap { @@ -15,16 +14,16 @@ public class Treap { public static class TreapNode { /** * TreapNode class defines the individual nodes in the Treap - * + *

    * value -> holds the value of the node. * Binary Search Tree is built based on value. - * + *

    * priority -> holds the priority of the node. * Heaps are maintained based on priority. * It is randomly assigned - * + *

    * size -> holds the size of the subtree with current node as root - * + *

    * left -> holds the left subtree * right -> holds the right subtree */ @@ -65,7 +64,7 @@ private void updateSize() { /** * Constructors - * + *

    * Treap() -> create an empty Treap * Treap(int[] nodeValues) -> add the elements given in the array to the Treap */ @@ -76,7 +75,7 @@ public Treap() { /** * merges two Treaps left and right into a single Treap * - * @param left left Treap + * @param left left Treap * @param right right Treap * @return root of merged Treap */ @@ -103,7 +102,7 @@ private TreapNode merge(TreapNode left, TreapNode right) { * split the Treap into two Treaps where left Treap has nodes <= key and right Treap has nodes > key * * @param node root node to be split - * @param key key to compare the nodes + * @param key key to compare the nodes * @return TreapNode array of size 2. * TreapNode[0] contains the root of left Treap after split * TreapNode[1] contains the root of right Treap after split diff --git a/src/main/java/com/thealgorithms/datastructures/trees/Trie.java b/src/main/java/com/thealgorithms/datastructures/trees/Trie.java index 02f28d4d83ad..8d20d69663e9 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/Trie.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/Trie.java @@ -132,7 +132,7 @@ public boolean delete(String word) { /** * Counts the number of words in the trie - *

    + *

    * The method traverses the Trie and counts the number of words. * * @return count of words diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java index 84fe0eb2c42a..cf56113cb3d8 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java @@ -10,23 +10,23 @@ * Given a binary tree. * This code returns the zigzag level order traversal of its nodes' values. * Binary tree: - * 7 - * / \ - * 6 3 - * / \ / \ - * 2 4 10 19 + * 7 + * / \ + * 6 3 + * / \ / \ + * 2 4 10 19 * Zigzag traversal: * [[7], [3, 6], [2, 4, 10, 19]] *

    * This solution implements the breadth-first search (BFS) algorithm using a queue. * 1. The algorithm starts with a root node. This node is added to a queue. * 2. While the queue is not empty: - * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes + * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes * at the current level. - * - we traverse all the level nodes in 2 ways: from left to right OR from right to left - * (this state is stored on `prevLevelFromLeftToRight` variable) - * - if the current node has children we add them to a queue - * - add level with nodes to a result. + * - we traverse all the level nodes in 2 ways: from left to right OR from right to left + * (this state is stored on `prevLevelFromLeftToRight` variable) + * - if the current node has children we add them to a queue + * - add level with nodes to a result. *

    * Complexities: * O(N) - time, where N is the number of nodes in a binary tree @@ -37,6 +37,7 @@ public final class ZigzagTraversal { private ZigzagTraversal() { } + public static List> traverse(BinaryTree.Node root) { if (root == null) { return List.of(); diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index 95d53ecb1f7a..84889f2b7c5d 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -7,7 +7,6 @@ * child Nodes. * * @param The type of the data held in the Node. - * * @author aitorfi */ public class LargeTreeNode extends TreeNode { @@ -37,7 +36,7 @@ public LargeTreeNode(E data) { /** * Initializes the Nodes' data and parent node reference. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @see TreeNode#TreeNode(Object, Node) */ @@ -48,7 +47,7 @@ public LargeTreeNode(E data, LargeTreeNode parentNode) { /** * Initializes the Nodes' data and parent and child nodes references. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @param childNodes {@link Collection} of child Nodes. * @see TreeNode#TreeNode(Object, Node) diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java index a10817830962..d8a1cd8dcd5d 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java @@ -3,11 +3,10 @@ /** * Base class for any node implementation which contains a generic type * variable. - * + *

    * All known subclasses: {@link TreeNode}, {@link SimpleNode}. * * @param The type of the data held in the Node. - * * @author aitorfi */ public abstract class Node { diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java index 769ffc2a9a96..9a4fe6fb3685 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java @@ -4,7 +4,6 @@ * Simple Node implementation that holds a reference to the next Node. * * @param The type of the data held in the Node. - * * @author aitorfi */ public class SimpleNode extends Node { @@ -34,7 +33,7 @@ public SimpleNode(E data) { /** * Initializes the Nodes' data and next node reference. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param nextNode Value to which the next node reference will be set. */ public SimpleNode(E data, SimpleNode nextNode) { diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index 215f01a6ef59..e6291c12dff4 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -5,7 +5,6 @@ * right). * * @param The type of the data held in the Node. - * * @author aitorfi */ public class SimpleTreeNode extends TreeNode { @@ -39,7 +38,7 @@ public SimpleTreeNode(E data) { /** * Initializes the Nodes' data and parent node reference. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @see TreeNode#TreeNode(Object, Node) */ @@ -50,12 +49,12 @@ public SimpleTreeNode(E data, SimpleTreeNode parentNode) { /** * Initializes the Nodes' data and parent and child nodes references. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. - * @param leftNode Value to which the nodes' left child reference will be - * set. - * @param rightNode Value to which the nodes' right child reference will be - * set. + * @param leftNode Value to which the nodes' left child reference will be + * set. + * @param rightNode Value to which the nodes' right child reference will be + * set. */ public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode, SimpleTreeNode rightNode) { super(data, parentNode); diff --git a/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java index 13c9212306c1..281bcfb9a3bf 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java @@ -2,11 +2,10 @@ /** * Base class for any tree node which holds a reference to the parent node. - * + *

    * All known subclasses: {@link SimpleTreeNode}, {@link LargeTreeNode}. * * @param The type of the data held in the Node. - * * @author aitorfi */ public abstract class TreeNode extends Node { @@ -42,7 +41,7 @@ public TreeNode(E data) { /** * Initializes the Nodes' data and parent node reference. * - * @param data Value to which data will be initialized. + * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. */ public TreeNode(E data, TreeNode parentNode) { diff --git a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java index 36587a21c863..a530987c26b2 100644 --- a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java +++ b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java @@ -7,9 +7,9 @@ */ public interface MatrixSearchAlgorithm { /** - * @param key is an element which should be found + * @param key is an element which should be found * @param matrix is a matrix where the element should be found - * @param Comparable type + * @param Comparable type * @return array containing the first found coordinates of the element */ > int[] find(T[][] matrix, T key); diff --git a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java index eb5b42756958..64cd5d5abd1a 100644 --- a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java +++ b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java @@ -7,9 +7,9 @@ */ public interface SearchAlgorithm { /** - * @param key is an element which should be found + * @param key is an element which should be found * @param array is an array where the element should be found - * @param Comparable type + * @param Comparable type * @return first found index of the element */ > int find(T[] array, T key); diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java index cd26f9213651..a48cfd5b5e5e 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java +++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java @@ -77,9 +77,9 @@ public Location buildLocation(double x, double y) { /** * xPartition function: arrange x-axis. * - * @param a (IN Parameter) array of points
    + * @param a (IN Parameter) array of points
    * @param first (IN Parameter) first point
    - * @param last (IN Parameter) last point
    + * @param last (IN Parameter) last point
    * @return pivot index */ public int xPartition(final Location[] a, final int first, final int last) { @@ -104,9 +104,9 @@ public int xPartition(final Location[] a, final int first, final int last) { /** * yPartition function: arrange y-axis. * - * @param a (IN Parameter) array of points
    + * @param a (IN Parameter) array of points
    * @param first (IN Parameter) first point
    - * @param last (IN Parameter) last point
    + * @param last (IN Parameter) last point
    * @return pivot index */ public int yPartition(final Location[] a, final int first, final int last) { @@ -131,9 +131,9 @@ public int yPartition(final Location[] a, final int first, final int last) { /** * xQuickSort function: //x-axis Quick Sorting. * - * @param a (IN Parameter) array of points
    + * @param a (IN Parameter) array of points
    * @param first (IN Parameter) first point
    - * @param last (IN Parameter) last point
    + * @param last (IN Parameter) last point
    */ public void xQuickSort(final Location[] a, final int first, final int last) { if (first < last) { @@ -146,9 +146,9 @@ public void xQuickSort(final Location[] a, final int first, final int last) { /** * yQuickSort function: //y-axis Quick Sorting. * - * @param a (IN Parameter) array of points
    + * @param a (IN Parameter) array of points
    * @param first (IN Parameter) first point
    - * @param last (IN Parameter) last point
    + * @param last (IN Parameter) last point
    */ public void yQuickSort(final Location[] a, final int first, final int last) { if (first < last) { @@ -161,7 +161,7 @@ public void yQuickSort(final Location[] a, final int first, final int last) { /** * closestPair function: find closest pair. * - * @param a (IN Parameter) array stored before divide
    + * @param a (IN Parameter) array stored before divide
    * @param indexNum (IN Parameter) number coordinates divideArray
    * @return minimum distance
    */ diff --git a/src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java b/src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java index 15c8bc33b58f..b383c65ca90d 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java +++ b/src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java @@ -38,8 +38,8 @@ public static int countInversions(int[] arr) { * Recursively divides the array into two halves, sorts them, and counts * the number of inversions. Uses a modified merge sort approach. * - * @param arr The input array. - * @param left The starting index of the current segment. + * @param arr The input array. + * @param left The starting index of the current segment. * @param right The ending index of the current segment. * @return The number of inversions within the segment [left, right]. */ @@ -62,9 +62,9 @@ private static int mergeSortAndCount(int[] arr, int left, int right) { * A cross-inversion occurs when an element from the right subarray is * smaller than an element from the left subarray. * - * @param arr The input array. - * @param left The starting index of the first subarray. - * @param mid The ending index of the first subarray and midpoint of the segment. + * @param arr The input array. + * @param left The starting index of the first subarray. + * @param mid The ending index of the first subarray and midpoint of the segment. * @param right The ending index of the second subarray. * @return The number of cross-inversions between the two subarrays. */ diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java index 610b1b78a36a..dd7623082583 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java +++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java @@ -88,7 +88,7 @@ public ArrayList produceSubSkyLines(ArrayList list) { * "cleaned" first half's and second half's skylines, are combined, * producing the final skyline, which is returned. * - * @param left the skyline of the left part of points + * @param left the skyline of the left part of points * @param right the skyline of the right part of points * @return left the final skyline */ diff --git a/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java b/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java index ff2e1678ab48..7a5af427db74 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java +++ b/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java @@ -31,7 +31,7 @@ private TilingProblem() { /** * Solves the tiling problem for a 2^n x 2^n board with one missing square. * - * @param size The size of the board (must be a power of 2). + * @param size The size of the board (must be a power of 2). * @param missingRow The row index of the missing square. * @param missingCol The column index of the missing square. * @return A 2D array representing the tiled board with L-shaped tiles. @@ -50,9 +50,9 @@ public static int[][] solveTiling(int size, int missingRow, int missingCol) { * to cover three of the four quadrants. The process is then repeated for * each quadrant until the entire board is filled. * - * @param size The current size of the sub-board. - * @param row The starting row index of the current sub-board. - * @param col The starting column index of the current sub-board. + * @param size The current size of the sub-board. + * @param row The starting row index of the current sub-board. + * @param col The starting column index of the current sub-board. * @param missingRow The row index of the missing square within the board. * @param missingCol The column index of the missing square within the board. */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java b/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java index 60c0fd0a3cde..9a8c5521d516 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java @@ -2,12 +2,12 @@ /** * A class that provides a solution to the abbreviation problem. - * + *

    * Problem: Given two strings, `a` and `b`, determine if string `a` can be * transformed into string `b` by performing the following operations: * 1. Capitalize zero or more of `a`'s lowercase letters (i.e., convert them to uppercase). * 2. Delete any of the remaining lowercase letters from `a`. - * + *

    * The task is to determine whether it is possible to make string `a` equal to string `b`. * * @author Hardvan @@ -23,8 +23,8 @@ private Abbreviation() { * @param a The input string which may contain both uppercase and lowercase letters. * @param b The target string containing only uppercase letters. * @return {@code true} if string `a` can be transformed into string `b`, - * {@code false} otherwise. - * + * {@code false} otherwise. + *

    * Time Complexity: O(n * m) where n = length of string `a` and m = length of string `b`. * Space Complexity: O(n * m) due to the dynamic programming table. */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java b/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java index e7712b13a2b7..f802d10bb005 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java @@ -5,7 +5,7 @@ /** * This class provides a solution to the "All Construct" problem. - * + *

    * The problem is to determine all the ways a target string can be constructed * from a given list of substrings. Each substring in the word bank can be used * multiple times, and the order of substrings matters. @@ -21,13 +21,13 @@ private AllConstruct() { * from the given word bank. * Time Complexity: O(n * m * k), where n = length of the target, * m = number of words in wordBank, and k = average length of a word. - * + *

    * Space Complexity: O(n * m) due to the size of the table storing combinations. * * @param target The target string to construct. * @param wordBank An iterable collection of substrings that can be used to construct the target. * @return A list of lists, where each inner list represents one possible - * way of constructing the target string using the given word bank. + * way of constructing the target string using the given word bank. */ public static List> allConstruct(String target, Iterable wordBank) { List>> table = new ArrayList<>(target.length() + 1); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java b/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java index 5a894ca004b7..bb5bbc0dd5b0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java @@ -22,7 +22,7 @@ public final class AssignmentUsingBitmask { * Constructor for the AssignmentUsingBitmask class. * * @param taskPerformed a list of lists, where each inner list contains the tasks that a person can perform. - * @param total the total number of tasks. + * @param total the total number of tasks. */ public AssignmentUsingBitmask(List> taskPerformed, int total) { this.totalTasks = total; @@ -50,8 +50,8 @@ public AssignmentUsingBitmask(List> taskPerformed, int total) { /** * Counts the ways to assign tasks until the given task number with the specified mask. * - * @param mask the bitmask representing the current state of assignments. - * @param taskNo the current task number being processed. + * @param mask the bitmask representing the current state of assignments. + * @param taskNo the current task number being processed. * @return the number of ways to assign tasks. */ private int countWaysUntil(int mask, int taskNo) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index 8494492f293f..05f235b17e36 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -2,6 +2,7 @@ /** * Java program for Boundary fill algorithm. + * * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ public final class BoundaryFill { @@ -11,7 +12,7 @@ private BoundaryFill() { /** * Get the color at the given co-odrinates of a 2D image * - * @param image The image to be filled + * @param image The image to be filled * @param xCoordinate The x co-ordinate of which color is to be obtained * @param yCoordinate The y co-ordinate of which color is to be obtained */ @@ -22,7 +23,7 @@ public static int getPixel(int[][] image, int xCoordinate, int yCoordinate) { /** * Put the color at the given co-odrinates of a 2D image * - * @param image The image to be filed + * @param image The image to be filed * @param xCoordinate The x co-ordinate at which color is to be filled * @param yCoordinate The y co-ordinate at which color is to be filled */ @@ -33,10 +34,10 @@ public static void putPixel(int[][] image, int xCoordinate, int yCoordinate, int /** * Fill the 2D image with new color * - * @param image The image to be filed - * @param xCoordinate The x co-ordinate at which color is to be filled - * @param yCoordinate The y co-ordinate at which color is to be filled - * @param newColor The new color which to be filled in the image + * @param image The image to be filed + * @param xCoordinate The x co-ordinate at which color is to be filled + * @param yCoordinate The y co-ordinate at which color is to be filled + * @param newColor The new color which to be filled in the image * @param boundaryColor The old color which is to be replaced in the image */ public static void boundaryFill(int[][] image, int xCoordinate, int yCoordinate, int newColor, int boundaryColor) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java index 3c1851a8c46c..625022b9482c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java @@ -30,7 +30,7 @@ private BruteForceKnapsack() { * @param wt an array where wt[i] represents the weight of the i-th item * @param val an array where val[i] represents the value of the i-th item * @param n the number of items available for selection - * @return the maximum value that can be obtained with the given capacity + * @return the maximum value that can be obtained with the given capacity * *

    The function uses recursion to explore all possible subsets of items. * For each item, it has two choices: either include it in the knapsack diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java index d01066f611bd..e77606c51ae3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java @@ -1,10 +1,11 @@ package com.thealgorithms.dynamicprogramming; import java.util.Scanner; + /** * This file contains an implementation of finding the nth CATALAN NUMBER using * dynamic programming : Wikipedia - * + *

    * Time Complexity: O(n^2) Space Complexity: O(n) * * @author AMRITESH ANAND @@ -17,9 +18,8 @@ private CatalanNumber() { * This method finds the nth Catalan number * * @param n input n which determines the nth Catalan number n should be less - * than equal to 50 as 50th Catalan number is 6,533,841,209,031,609,592 for - * n > 50, BigInteger class should be used instead long - * + * than equal to 50 as 50th Catalan number is 6,533,841,209,031,609,592 for + * n > 50, BigInteger class should be used instead long * @return catalanArray[n] the nth Catalan number */ static long findNthCatalan(int n) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java index 0f0f5375ba82..653f06e09d01 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java @@ -27,9 +27,9 @@ private ClimbingStairs() { * * @param n the no. of steps in the staircase (non-negative integer) * @return the no. of distinct ways to climb to the top - * - Returns 0 if n is 0 (no steps to climb). - * - Returns 1 if n is 1 (only one way to climb). - * - For n > 1, it returns the total no. of ways to climb. + * - Returns 0 if n is 0 (no steps to climb). + * - Returns 1 if n is 1 (only one way to climb). + * - For n > 1, it returns the total no. of ways to climb. */ public static int numberOfWays(int n) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index 7edc9603dc8b..caf7093c4c63 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -11,9 +11,9 @@ private CoinChange() { * This method finds the number of combinations of getting change for a * given amount and change coins * - * @param coins The list of coins + * @param coins The list of coins * @param amount The amount for which we need to find the change Finds the - * number of combinations of change + * number of combinations of change */ public static int change(int[] coins, int amount) { int[] combinations = new int[amount + 1]; @@ -31,9 +31,9 @@ public static int change(int[] coins, int amount) { /** * This method finds the minimum number of coins needed for a given amount. * - * @param coins The list of coins + * @param coins The list of coins * @param amount The amount for which we need to find the minimum number of - * coins. Finds the minimum number of coins that make a given value. + * coins. Finds the minimum number of coins that make a given value. */ public static int minimumCoins(int[] coins, int amount) { // minimumCoins[i] will store the minimum coins needed for amount i diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java index e731524d4958..299f9ec97eaa 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java @@ -2,10 +2,10 @@ /** * @author Siddhant Swarup Mallick - + *

    * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal * to number of times n appears in the sequence. - + * * Wikipedia * Program description - To find the Golomb sequence upto n */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index 0d6aff2bbef3..4c4a52e5f79f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -16,7 +16,7 @@ private Fibonacci() { * This method finds the nth fibonacci number using memoization technique * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number + * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibMemo(int n) { @@ -42,7 +42,7 @@ public static int fibMemo(int n) { * This method finds the nth fibonacci number using bottom up * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number + * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibBotUp(int n) { @@ -68,13 +68,13 @@ public static int fibBotUp(int n) { * This method finds the nth fibonacci number using bottom up * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number - *

    - * This is optimized version of Fibonacci Program. Without using Hashmap and - * recursion. It saves both memory and time. Space Complexity will be O(1) - * Time Complexity will be O(n) - *

    - * Whereas , the above functions will take O(n) Space. + * Outputs the nth fibonacci number + *

    + * This is optimized version of Fibonacci Program. Without using Hashmap and + * recursion. It saves both memory and time. Space Complexity will be O(1) + * Time Complexity will be O(n) + *

    + * Whereas , the above functions will take O(n) Space. * @throws IllegalArgumentException if n is negative * @author Shoaib Rayeen (https://github.com/shoaibrayeen) */ @@ -104,8 +104,9 @@ public static int fibOptimized(int n) { * = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 We first calculate * the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get * the required term. Time Complexity will be O(1) + * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number + * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibBinet(int n) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index 7a0a3da94c1e..ec1e828a9c4c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -4,7 +4,7 @@ * This class implements Kadane's Algorithm to find the maximum subarray sum * within a given array of integers. The algorithm efficiently computes the maximum * sum of a contiguous subarray in linear time. - * + *

    * Author: Siddhant Swarup Mallick */ public final class KadaneAlgorithm { @@ -15,12 +15,12 @@ private KadaneAlgorithm() { * Computes the maximum subarray sum using Kadane's Algorithm and checks * if it matches a predicted answer. * - * @param a The input array of integers for which the maximum - * subarray sum is to be calculated. + * @param a The input array of integers for which the maximum + * subarray sum is to be calculated. * @param predictedAnswer The expected maximum subarray sum to be verified - * against the computed sum. + * against the computed sum. * @return true if the computed maximum subarray sum equals the predicted - * answer, false otherwise. + * answer, false otherwise. * *

    Example:

    *
    diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
    index 119d65dfe365..2a290c5c3b2f 100644
    --- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
    +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
    @@ -4,7 +4,7 @@
     
     /**
      * Provides functions to calculate the Levenshtein distance between two strings.
    - *
    + * 

    * The Levenshtein distance is a measure of the similarity between two strings by calculating the minimum number of single-character * edits (insertions, deletions, or substitutions) required to change one string into the other. */ @@ -14,19 +14,19 @@ private LevenshteinDistance() { /** * Calculates the Levenshtein distance between two strings using a naive dynamic programming approach. - * + *

    * This function computes the Levenshtein distance by constructing a dynamic programming matrix and iteratively filling it in. * It follows the standard top-to-bottom, left-to-right approach for filling in the matrix. * * @param string1 The first string. * @param string2 The second string. * @return The Levenshtein distance between the two input strings. - * + *

    * Time complexity: O(nm), * Space complexity: O(nm), - * + *

    * where n and m are lengths of `string1` and `string2`. - * + *

    * Note that this implementation uses a straightforward dynamic programming approach without any space optimization. * It may consume more memory for larger input strings compared to the optimized version. */ @@ -43,20 +43,20 @@ public static int naiveLevenshteinDistance(final String string1, final String st /** * Calculates the Levenshtein distance between two strings using an optimized dynamic programming approach. - * + *

    * This edit distance is defined as 1 point per insertion, substitution, or deletion required to make the strings equal. * * @param string1 The first string. * @param string2 The second string. * @return The Levenshtein distance between the two input strings. - * + *

    * Time complexity: O(nm), * Space complexity: O(n), - * + *

    * where n and m are lengths of `string1` and `string2`. - * + *

    * Note that this implementation utilizes an optimized dynamic programming approach, significantly reducing the space complexity from O(nm) to O(n), where n and m are the lengths of `string1` and `string2`. - * + *

    * Additionally, it minimizes space usage by leveraging the shortest string horizontally and the longest string vertically in the computation matrix. */ public static int optimizedLevenshteinDistance(final String string1, final String string2) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java index 08039b85ce40..2be2a7235960 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java @@ -23,7 +23,7 @@ private LongestAlternatingSubsequence() { * Finds the length of the longest alternating subsequence in the given array. * * @param arr an array of integers where the longest alternating subsequence is to be found - * @param n the length of the array {@code arr} + * @param n the length of the array {@code arr} * @return the length of the longest alternating subsequence * *

    The method uses dynamic programming to solve the problem. It maintains a 2D array diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java index b5ac62b4674b..01a1ce31c3b9 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java @@ -8,7 +8,7 @@ private LongestArithmeticSubsequence() { /** * Returns the length of the longest arithmetic subsequence in the given array. - * + *

    * A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value * (for 0 <= i < seq.length - 1). * diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java index 54837b5f4e71..df8ae43f5ad1 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java @@ -5,7 +5,7 @@ * The LCS of two sequences is the longest sequence that appears in both * sequences * in the same order, but not necessarily consecutively. - * + *

    * This implementation uses dynamic programming to find the LCS of two strings. */ final class LongestCommonSubsequence { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java index 8a4ab2f526a9..4b63f3e4d9b5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java @@ -5,7 +5,6 @@ *

    * A palindromic substring is a sequence of characters that reads the same backward as forward. * This class uses a dynamic programming approach to efficiently find the longest palindromic substring. - * */ public final class LongestPalindromicSubstring { private LongestPalindromicSubstring() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java index 1edb7207dee2..500129e52761 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java @@ -24,7 +24,7 @@ private MatrixChainMultiplication() { * @param matrices an ArrayList of Matrix objects representing the matrices * to be multiplied. * @return a Result object containing the matrices of minimum costs and - * optimal splits. + * optimal splits. */ public static Result calculateMatrixChainOrder(ArrayList matrices) { int size = matrices.size(); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java index 0c1031c6805c..6da82cf4fac9 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java @@ -24,7 +24,7 @@ private MatrixChainRecursiveTopDownMemoisation() { * @param p an array of integers representing the dimensions of the matrices. * The length of the array is n + 1, where n is the number of matrices. * @return the minimum number of multiplications required to multiply the chain - * of matrices. + * of matrices. */ static int memoizedMatrixChain(int[] p) { int n = p.length; @@ -46,7 +46,7 @@ static int memoizedMatrixChain(int[] p) { * @param i the starting index of the matrix chain. * @param j the ending index of the matrix chain. * @return the minimum number of multiplications needed to multiply matrices - * from i to j. + * from i to j. */ static int lookupChain(int[][] m, int[] p, int i, int j) { if (i == j) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java index 49af3ae3db88..11595357d57f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java @@ -15,6 +15,7 @@ private MaximumSumOfNonAdjacentElements() { * Approach 1: Uses a dynamic programming array to store the maximum sum at * each index. Time Complexity: O(n) - where n is the length of the input * array. Space Complexity: O(n) - due to the additional dp array. + * * @param arr The input array of integers. * @return The maximum sum of non-adjacent elements. */ @@ -54,6 +55,7 @@ public static int getMaxSumApproach1(int[] arr) { * of an array. Time Complexity: O(n) - where n is the length of the input * array. Space Complexity: O(1) - as it only uses constant space for two * variables. + * * @param arr The input array of integers. * @return The maximum sum of non-adjacent elements. */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java index 3db40148f1c2..9ce798a3687c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java @@ -29,10 +29,10 @@ private NewManShanksPrime() { * Calculates the nth New Man Shanks prime and checks if it equals the * expected answer. * - * @param n the index of the New Man Shanks prime to calculate (0-based). + * @param n the index of the New Man Shanks prime to calculate (0-based). * @param expectedAnswer the expected value of the nth New Man Shanks prime. * @return true if the calculated nth New Man Shanks prime matches the - * expected answer; false otherwise. + * expected answer; false otherwise. */ public static boolean nthManShanksPrime(int n, int expectedAnswer) { int[] a = new int[n + 1]; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index e31bb73096e8..92e9acb88ff7 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -2,9 +2,9 @@ /** * This class refers to the Optimal Job Scheduling problem with the following constrains: - * - precedence relation between the processes - * - machine pair dependent transportation delays - * + * - precedence relation between the processes + * - machine pair dependent transportation delays + *

    * https://en.wikipedia.org/wiki/Optimal_job_scheduling * * @author georgioct@csd.auth.gr @@ -19,11 +19,12 @@ public class OptimalJobScheduling { /** * Constructor of the class. + * * @param numberProcesses ,refers to the number of precedent processes(N) - * @param numberMachines ,refers to the number of different machines in our disposal(M) - * @param run , N*M matrix refers to the cost of running each process to each machine - * @param transfer ,M*M symmetric matrix refers to the transportation delay for each pair of - * machines + * @param numberMachines ,refers to the number of different machines in our disposal(M) + * @param run , N*M matrix refers to the cost of running each process to each machine + * @param transfer ,M*M symmetric matrix refers to the transportation delay for each pair of + * machines */ public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] run, int[][] transfer) { this.numberProcesses = numberProcesses; @@ -88,8 +89,9 @@ private int runningCost(int process, int machine) { /** * Function used in order to return the minimum Cost. + * * @param costArr ,an Array of size M which refers to the costs of executing a Process to each - * Machine + * Machine * @return the minimum cost */ private int findMin(int[] costArr) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java index 49c4a0a3a008..36b2b0ecb07b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java @@ -1,16 +1,16 @@ /** * @author Md Asif Joardar - * + *

    * Description: The partition problem is a classic problem in computer science * that asks whether a given set can be partitioned into two subsets such that * the sum of elements in each subset is the same. - * + *

    * Example: * Consider nums = {1, 2, 3} * We can split the array "nums" into two partitions, where each having a sum of 3. * nums1 = {1, 2} * nums2 = {3} - * + *

    * The time complexity of the solution is O(n × sum) and requires O(n × sum) space */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java index 181ac72a654d..bf2de689d337 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java @@ -5,9 +5,9 @@ * algorithm that finds if wildcard is matched with text. The matching should * cover the entire text ?-> matches single characters *-> match the sequence of * characters - * + *

    * For calculation of Time and Space Complexity. Let N be length of src and M be length of pat - * + *

    * Memoization vs Tabulation : https://www.geeksforgeeks.org/tabulation-vs-memoization/ * Question Link : https://practice.geeksforgeeks.org/problems/wildcard-pattern-matching/1 */ @@ -19,7 +19,7 @@ private RegexMatching() { * Method 1: Determines if the given source string matches the given pattern using a recursive approach. * This method directly applies recursion to check if the source string matches the pattern, considering * the wildcards '?' and '*'. - * + *

    * Time Complexity: O(2^(N+M)), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N + M) due to the recursion stack. * @@ -64,12 +64,12 @@ public static boolean regexRecursion(String src, String pat) { /** * Method 2: Determines if the given source string matches the given pattern using recursion. * This method utilizes a virtual index for both the source string and the pattern to manage the recursion. - * + *

    * Time Complexity: O(2^(N+M)) where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N + M) due to the recursion stack. * - * @param src The source string to be matched against the pattern. - * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). + * @param src The source string to be matched against the pattern. + * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @param svidx The current index in the source string. * @param pvidx The current index in the pattern. * @return {@code true} if the source string matches the pattern, {@code false} otherwise. @@ -108,15 +108,15 @@ static boolean regexRecursion(String src, String pat, int svidx, int pvidx) { /** * Method 3: Determines if the given source string matches the given pattern using top-down dynamic programming (memoization). * This method utilizes memoization to store intermediate results, reducing redundant computations and improving efficiency. - * + *

    * Time Complexity: O(N * M), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N * M) for the memoization table, plus additional space for the recursion stack. * - * @param src The source string to be matched against the pattern. - * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). + * @param src The source string to be matched against the pattern. + * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @param svidx The current index in the source string. * @param pvidx The current index in the pattern. - * @param strg A 2D array used for memoization to store the results of subproblems. + * @param strg A 2D array used for memoization to store the results of subproblems. * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ public static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[][] strg) { @@ -158,7 +158,7 @@ public static boolean regexRecursion(String src, String pat, int svidx, int pvid * Method 4: Determines if the given source string matches the given pattern using bottom-up dynamic programming (tabulation). * This method builds a solution iteratively by filling out a table, where each cell represents whether a substring * of the source string matches a substring of the pattern. - * + *

    * Time Complexity: O(N * M), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N * M) for the table used in the tabulation process. * diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java index 6d33826b6b17..d095055efff5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java @@ -15,8 +15,8 @@ private RodCutting() { * @param price An array representing the prices of different pieces, where price[i-1] * represents the price of a piece of length i. * @param n The length of the rod to be cut. - * @throws IllegalArgumentException if the price array is null or empty, or if n is less than 0. * @return The maximum obtainable value. + * @throws IllegalArgumentException if the price array is null or empty, or if n is less than 0. */ public static int cutRod(int[] price, int n) { if (price == null || price.length == 0) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java index 0c5bc2c5884d..474d797c9427 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java @@ -4,6 +4,7 @@ * Find the number of subsets present in the given array with a sum equal to target. * Based on Solution discussed on * StackOverflow + * * @author Samrat Podder */ public final class SubsetCount { @@ -14,9 +15,9 @@ private SubsetCount() { * Dynamic Programming Implementation. * Method to find out the number of subsets present in the given array with a sum equal to * target. Time Complexity is O(n*target) and Space Complexity is O(n*target) - * @param arr is the input array on which subsets are to searched - * @param target is the sum of each element of the subset taken together * + * @param arr is the input array on which subsets are to searched + * @param target is the sum of each element of the subset taken together */ public static int getCount(int[] arr, int target) { /* @@ -49,7 +50,8 @@ public static int getCount(int[] arr, int target) { * This Method is a Space Optimized version of the getCount(int[], int) method and solves the * same problem This approach is a bit better in terms of Space Used Time Complexity is * O(n*target) and Space Complexity is O(target) - * @param arr is the input array on which subsets are to searched + * + * @param arr is the input array on which subsets are to searched * @param target is the sum of each element of the subset taken together */ public static int getCountSO(int[] arr, int target) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java index da8667afd0ce..c3a11734db92 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java @@ -10,7 +10,7 @@ private SubsetSum() { * @param arr the array containing integers. * @param sum the target sum of the subset. * @return {@code true} if a subset exists that sums to the given value, - * otherwise {@code false}. + * otherwise {@code false}. */ public static boolean subsetSum(int[] arr, int sum) { int n = arr.length; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java index 946da46cb292..44b811706323 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java @@ -1,4 +1,5 @@ package com.thealgorithms.dynamicprogramming; + /* The Sum of Subset problem determines whether a subset of elements from a given array sums up to a specific target value. @@ -6,6 +7,7 @@ public final class SubsetSumSpaceOptimized { private SubsetSumSpaceOptimized() { } + /** * This method checks whether the subset of an array * contains a given sum or not. This is an space diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java index e9c15c1b4f24..95890b9ed63d 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java @@ -3,10 +3,10 @@ /** * A utility class that contains the Sum of Subset problem solution using * recursion. - * + *

    * The Sum of Subset problem determines whether a subset of elements from a * given array sums up to a specific target value. - * + *

    * Wikipedia: https://en.wikipedia.org/wiki/Subset_sum_problem */ public final class SumOfSubset { @@ -22,13 +22,13 @@ private SumOfSubset() { * @param num The index of the current element being considered. * @param key The target sum we are trying to achieve. * @return true if a subset of `arr` adds up to `key`, false otherwise. - * - * This is a recursive solution that checks for two possibilities at - * each step: - * 1. Include the current element in the subset and check if the - * remaining elements can sum up to the remaining target. - * 2. Exclude the current element and check if the remaining elements - * can sum up to the target without this element. + *

    + * This is a recursive solution that checks for two possibilities at + * each step: + * 1. Include the current element in the subset and check if the + * remaining elements can sum up to the remaining target. + * 2. Exclude the current element and check if the remaining elements + * can sum up to the target without this element. */ public static boolean subsetSum(int[] arr, int num, int key) { if (key == 0) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java index 8c7ea6179e3f..5cec8f1e7c1b 100755 --- a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java @@ -53,11 +53,11 @@ public static int countSubseq(String str) { *

    Uses a HashSet to avoid counting duplicate characters within * a single subsequence.

    * - * @param st the input string + * @param st the input string * @param idx the current index from which to calculate subsequences - * @param dp dynamic programming array used to memoize results + * @param dp dynamic programming array used to memoize results * @return the total number of unique subsequences starting from the - * current index + * current index */ public static int countSubsequences(String st, int idx, int[] dp) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java index 8e8bf3cc6606..b51da191c23b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java @@ -1,15 +1,13 @@ /** - * * Author: Janmesh Singh * Github: https://github.com/janmeshjs - + *

    * Problem Statement: To determine if the pattern matches the text. * The pattern can include two special wildcard characters: - * ' ? ': Matches any single character. - * ' * ': Matches zero or more of any character sequence. - * + * ' ? ': Matches any single character. + * ' * ': Matches zero or more of any character sequence. + *

    * Use DP to return True if the pattern matches the entire text and False otherwise - * */ package com.thealgorithms.dynamicprogramming; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java index 022b43184a88..bd753841de42 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java @@ -5,23 +5,23 @@ * Given a collection of N wines with different prices, the objective is to maximize profit by selling * one wine each year, considering the constraint that only the leftmost or rightmost wine can be sold * at any given time. - * + *

    * The price of the ith wine is pi, and the selling price increases by a factor of the year in which * it is sold. This class implements three approaches to solve the problem: - * + *

    * 1. **Recursion**: A straightforward recursive method that computes the maximum profit. - * - Time Complexity: O(2^N) - * - Space Complexity: O(N) due to recursive calls. - * + * - Time Complexity: O(2^N) + * - Space Complexity: O(N) due to recursive calls. + *

    * 2. **Top-Down Dynamic Programming (Memoization)**: This approach caches the results of subproblems - * to avoid redundant computations. - * - Time Complexity: O(N^2) - * - Space Complexity: O(N^2) for the storage of results and O(N) for recursion stack. - * + * to avoid redundant computations. + * - Time Complexity: O(N^2) + * - Space Complexity: O(N^2) for the storage of results and O(N) for recursion stack. + *

    * 3. **Bottom-Up Dynamic Programming (Tabulation)**: This method builds a table iteratively to - * compute the maximum profit for all possible subproblems. - * - Time Complexity: O(N^2) - * - Space Complexity: O(N^2) for the table. + * compute the maximum profit for all possible subproblems. + * - Time Complexity: O(N^2) + * - Space Complexity: O(N^2) for the table. */ public final class WineProblem { private WineProblem() { @@ -80,8 +80,8 @@ public static int wptd(int[] arr, int si, int ei, int[][] strg) { * Calculate maximum profit using bottom-up dynamic programming with tabulation. * * @param arr Array of wine prices. - * @throws IllegalArgumentException if the input array is null or empty. * @return Maximum profit obtainable by selling the wines. + * @throws IllegalArgumentException if the input array is null or empty. */ public static int wpbu(int[] arr) { if (arr == null || arr.length == 0) { diff --git a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java index 51d9930c0250..9ab69439fdb1 100644 --- a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java +++ b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java @@ -11,7 +11,7 @@ * *

    This algorithm uses integer arithmetic to calculate the points, * making it suitable for rasterization in computer graphics.

    - * + *

    * For more information, please visit {@link https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm} */ public final class BresenhamLine { diff --git a/src/main/java/com/thealgorithms/geometry/ConvexHull.java b/src/main/java/com/thealgorithms/geometry/ConvexHull.java index 17f400854c64..ac0872187952 100644 --- a/src/main/java/com/thealgorithms/geometry/ConvexHull.java +++ b/src/main/java/com/thealgorithms/geometry/ConvexHull.java @@ -12,9 +12,9 @@ /** * A class providing algorithms to compute the convex hull of a set of points * using brute-force and recursive methods. - * + *

    * Convex hull: The smallest convex polygon that contains all the given points. - * + *

    * Algorithms provided: * 1. Brute-Force Method * 2. Recursive (Divide-and-Conquer) Method diff --git a/src/main/java/com/thealgorithms/geometry/GrahamScan.java b/src/main/java/com/thealgorithms/geometry/GrahamScan.java index 1a373cf315a2..4c526c76910c 100644 --- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java +++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java @@ -9,7 +9,7 @@ * The time complexity is O(n) in the best case and O(n log(n)) in the worst case. * The space complexity is O(n). * This algorithm is applicable only to integral coordinates. - * + *

    * References: * https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/geometry/graham_scan_algorithm.cpp * https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/geometry/graham_scan_functions.hpp diff --git a/src/main/java/com/thealgorithms/geometry/MidpointEllipse.java b/src/main/java/com/thealgorithms/geometry/MidpointEllipse.java index fbd53c679960..0284c97cac2e 100644 --- a/src/main/java/com/thealgorithms/geometry/MidpointEllipse.java +++ b/src/main/java/com/thealgorithms/geometry/MidpointEllipse.java @@ -20,8 +20,8 @@ private MidpointEllipse() { * * @param centerX the x-coordinate of the center of the ellipse * @param centerY the y-coordinate of the center of the ellipse - * @param a the length of the semi-major axis (horizontal radius) - * @param b the length of the semi-minor axis (vertical radius) + * @param a the length of the semi-major axis (horizontal radius) + * @param b the length of the semi-minor axis (vertical radius) * @return a list of points (represented as int arrays) that form the ellipse */ public static List drawEllipse(int centerX, int centerY, int a, int b) { @@ -58,11 +58,11 @@ public static List drawEllipse(int centerX, int centerY, int a, int b) { /** * Computes points of a non-degenerate ellipse using the Midpoint Ellipse Algorithm. * - * @param points the list to which points will be added - * @param centerX the x-coordinate of the center of the ellipse - * @param centerY the y-coordinate of the center of the ellipse - * @param a the length of the semi-major axis (horizontal radius) - * @param b the length of the semi-minor axis (vertical radius) + * @param points the list to which points will be added + * @param centerX the x-coordinate of the center of the ellipse + * @param centerY the y-coordinate of the center of the ellipse + * @param a the length of the semi-major axis (horizontal radius) + * @param b the length of the semi-minor axis (vertical radius) */ private static void computeEllipsePoints(Collection points, int centerX, int centerY, int a, int b) { int x = 0; // Initial x-coordinate @@ -116,11 +116,11 @@ private static void computeEllipsePoints(Collection points, int centerX, /** * Adds points for all four quadrants of the ellipse based on symmetry. * - * @param points the list to which points will be added - * @param centerX the x-coordinate of the center of the ellipse - * @param centerY the y-coordinate of the center of the ellipse - * @param x the x-coordinate relative to the center - * @param y the y-coordinate relative to the center + * @param points the list to which points will be added + * @param centerX the x-coordinate of the center of the ellipse + * @param centerY the y-coordinate of the center of the ellipse + * @param x the x-coordinate relative to the center + * @param y the y-coordinate relative to the center */ private static void addEllipsePoints(Collection points, int centerX, int centerY, int x, int y) { points.add(new int[] {centerX + x, centerY + y}); diff --git a/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java b/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java index 87d4e89d2c8c..fa6e59ec69b7 100644 --- a/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java +++ b/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java @@ -8,7 +8,7 @@ * Finds the strongly connected components in a directed graph. * * @param adjList The adjacency list representation of the graph. - * @param n The number of nodes in the graph. + * @param n The number of nodes in the graph. * @return The number of strongly connected components. */ public class StronglyConnectedComponentOptimized { diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java b/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java index 54ba4eb650a8..c12081b1bf19 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java @@ -14,7 +14,7 @@ private ActivitySelection() { /** * Function to perform activity selection using a greedy approach. - * + *

    * The goal is to select the maximum number of activities that don't overlap * with each other, based on their start and end times. Activities are chosen * such that no two selected activities overlap. @@ -22,7 +22,7 @@ private ActivitySelection() { * @param startTimes Array containing the start times of the activities. * @param endTimes Array containing the end times of the activities. * @return A list of indices representing the selected activities that can be - * performed without overlap. + * performed without overlap. */ public static ArrayList activitySelection(int[] startTimes, int[] endTimes) { int n = startTimes.length; diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java b/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java index 074c76b9f33f..90acb345d617 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java @@ -8,8 +8,9 @@ public class BinaryAddition { /** * Computes the sum of two binary characters and a carry. - * @param a First binary character ('0' or '1'). - * @param b Second binary character ('0' or '1'). + * + * @param a First binary character ('0' or '1'). + * @param b Second binary character ('0' or '1'). * @param carry The carry from the previous operation ('0' or '1'). * @return The sum as a binary character ('0' or '1'). */ @@ -26,10 +27,12 @@ public char sum(char a, char b, char carry) { } return count % 2 == 0 ? '0' : '1'; } + /** * Computes the carry for the next higher bit from two binary characters and a carry. - * @param a First binary character ('0' or '1'). - * @param b Second binary character ('0' or '1'). + * + * @param a First binary character ('0' or '1'). + * @param b Second binary character ('0' or '1'). * @param carry The carry from the previous operation ('0' or '1'). * @return The carry for the next bit ('0' or '1'). */ @@ -46,8 +49,10 @@ public char carry(char a, char b, char carry) { } return count >= 2 ? '1' : '0'; } + /** * Adds two binary strings and returns their sum as a binary string. + * * @param a First binary string. * @param b Second binary string. * @return Binary string representing the sum of the two binary inputs. diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java b/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java index 8054581d21d7..514011595ef0 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java @@ -9,6 +9,7 @@ public final class CoinChange { private CoinChange() { } + // Function to solve the coin change problem public static ArrayList coinChangeProblem(int amount) { // Define an array of coin denominations in descending order diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java b/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java index bee5f98cd2ee..f30dd81f2e02 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java @@ -10,8 +10,10 @@ public class DigitSeparation { public DigitSeparation() { } + /** * Separates the digits of a large positive number into a list in reverse order. + * * @param largeNumber The large number to separate digits from. * @return A list of digits in reverse order. */ @@ -27,8 +29,10 @@ public List digitSeparationReverseOrder(long largeNumber) { } return result; } + /** * Separates the digits of a large positive number into a list in forward order. + * * @param largeNumber The large number to separate digits from. * @return A list of digits in forward order. */ diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java b/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java index 9535a7c6190e..b69052b23602 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java @@ -7,11 +7,11 @@ * The FractionalKnapsack class provides a method to solve the fractional knapsack problem * using a greedy algorithm approach. It allows for selecting fractions of items to maximize * the total value in a knapsack with a given weight capacity. - * + *

    * The problem consists of a set of items, each with a weight and a value, and a knapsack * that can carry a maximum weight. The goal is to maximize the value of items in the knapsack, * allowing for the inclusion of fractions of items. - * + *

    * Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem */ public final class FractionalKnapsack { @@ -21,8 +21,8 @@ private FractionalKnapsack() { /** * Computes the maximum value that can be accommodated in a knapsack of a given capacity. * - * @param weight an array of integers representing the weights of the items - * @param value an array of integers representing the values of the items + * @param weight an array of integers representing the weights of the items + * @param value an array of integers representing the values of the items * @param capacity an integer representing the maximum weight capacity of the knapsack * @return the maximum value that can be obtained by including the items in the knapsack */ diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java b/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java index 07bd0b73326f..14ddc7261f8b 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java @@ -7,7 +7,7 @@ /** * Problem Statement: * Given an array of intervals where intervals[i] = [starti, endi]. - * + *

    * Merge all overlapping intervals and return an array of the non-overlapping * intervals * that cover all the intervals in the input. @@ -22,7 +22,7 @@ private MergeIntervals() { /** * Merges overlapping intervals from the given array of intervals. - * + *

    * The method sorts the intervals by their start time, then iterates through the * sorted intervals * and merges overlapping intervals. If an interval overlaps with the last @@ -33,10 +33,10 @@ private MergeIntervals() { * @param intervals A 2D array representing intervals where each element is an * interval [starti, endi]. * @return A 2D array of merged intervals where no intervals overlap. - * - * Example: - * Input: {{1, 3}, {2, 6}, {8, 10}, {15, 18}} - * Output: {{1, 6}, {8, 10}, {15, 18}} + *

    + * Example: + * Input: {{1, 3}, {2, 6}, {8, 10}, {15, 18}} + * Output: {{1, 6}, {8, 10}, {15, 18}} */ public static int[][] merge(int[][] intervals) { // Sort the intervals by their start time (ascending order) diff --git a/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java b/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java index 6e8611b86332..c66d09a34a11 100644 --- a/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java +++ b/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java @@ -7,15 +7,15 @@ * @author shikarisohan * @since 10/4/24 * Cohen-Sutherland Line Clipping Algorithm - * + *

    * This algorithm is used to clip a line segment to a rectangular window. * It assigns a region code to each endpoint of the line segment, and * then efficiently determines whether the line segment is fully inside, * fully outside, or partially inside the window. - * + *

    * Reference: * https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm - * + *

    * Clipping window boundaries are defined as (xMin, yMin) and (xMax, yMax). * The algorithm computes the clipped line segment if it's partially or * fully inside the clipping window. diff --git a/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java b/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java index 723e2bb2fbf9..cc16c4e0905a 100644 --- a/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java +++ b/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java @@ -6,16 +6,16 @@ /** * @author shikarisohan * @since 10/5/24 - * - * * The Liang-Barsky line clipping algorithm is an efficient algorithm for - * * line clipping against a rectangular window. It is based on the parametric - * * equation of a line and checks the intersections of the line with the - * * window boundaries. This algorithm calculates the intersection points, - * * if any, and returns the clipped line that lies inside the window. - * * - * * Reference: - * * https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm - * + *

    + * * The Liang-Barsky line clipping algorithm is an efficient algorithm for + * * line clipping against a rectangular window. It is based on the parametric + * * equation of a line and checks the intersections of the line with the + * * window boundaries. This algorithm calculates the intersection points, + * * if any, and returns the clipped line that lies inside the window. + * * + * * Reference: + * * https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm + *

    * Clipping window boundaries are defined as (xMin, yMin) and (xMax, yMax). * The algorithm computes the clipped line segment if it's partially or * fully inside the clipping window. diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java index a85ef09079c9..9527ebf34556 100644 --- a/src/main/java/com/thealgorithms/maths/ADTFraction.java +++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java @@ -61,7 +61,7 @@ public ADTFraction reciprocal() { * Calculates the result of the fraction. * * @return The numerical result of the division between {@code numerator} and {@code - * denominator} + * denominator} */ public float value() { return (float) this.numerator / this.denominator; diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index b30831bfdc58..f77b5a3f359b 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -22,6 +22,7 @@ public final class AmicableNumber { private AmicableNumber() { } + /** * Finds all the amicable numbers in a given range. * diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index ff4ae027a0b7..91b8f2e47e6b 100644 --- a/src/main/java/com/thealgorithms/maths/Armstrong.java +++ b/src/main/java/com/thealgorithms/maths/Armstrong.java @@ -4,7 +4,7 @@ * This class checks whether a given number is an Armstrong number or not. * An Armstrong number is a number that is equal to the sum of its own digits, * each raised to the power of the number of digits. - * + *

    * For example, 370 is an Armstrong number because 3^3 + 7^3 + 0^3 = 370. * 1634 is an Armstrong number because 1^4 + 6^4 + 3^4 + 4^4 = 1634. * An Armstrong number is often called a Narcissistic number. diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java index 31f81da63f03..53c80b3b5e24 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -1,6 +1,7 @@ package com.thealgorithms.maths; import java.math.BigInteger; + /** * Automorphic Number * A number is said to be an Automorphic, if it is present in the last digit(s) @@ -17,7 +18,7 @@ private AutomorphicNumber() { * * @param n The number to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise - * {@code false} + * {@code false} */ public static boolean isAutomorphic(long n) { if (n < 0) { @@ -39,7 +40,7 @@ public static boolean isAutomorphic(long n) { * * @param n The number to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise - * {@code false} + * {@code false} */ public static boolean isAutomorphic2(long n) { if (n < 0) { @@ -54,7 +55,7 @@ public static boolean isAutomorphic2(long n) { * * @param s The number in String to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise - * {@code false} + * {@code false} */ public static boolean isAutomorphic3(String s) { BigInteger n = new BigInteger(s); diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java index faec049b08a7..9be4b9e0911c 100644 --- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java +++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java @@ -20,7 +20,7 @@ private BinomialCoefficient() { * @param totalObjects Total number of objects * @param numberOfObjects Number of objects to be chosen from total_objects * @return number of ways in which no_of_objects objects can be chosen from total_objects - * objects + * objects */ public static int binomialCoefficient(int totalObjects, int numberOfObjects) { diff --git a/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java b/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java index c26e67cffb59..37e5b9a4c56c 100644 --- a/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java +++ b/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java @@ -4,8 +4,7 @@ /** * @brief Implementation of the Chinese Remainder Theorem (CRT) algorithm - * @details - * The Chinese Remainder Theorem (CRT) is used to solve systems of + * @details The Chinese Remainder Theorem (CRT) is used to solve systems of * simultaneous congruences. Given several pairwise coprime moduli * and corresponding remainders, the algorithm finds the smallest * positive solution. @@ -15,10 +14,10 @@ private ChineseRemainderTheorem() { } /** - * @brief Solves the Chinese Remainder Theorem problem. * @param remainders The list of remainders. - * @param moduli The list of pairwise coprime moduli. + * @param moduli The list of pairwise coprime moduli. * @return The smallest positive solution that satisfies all the given congruences. + * @brief Solves the Chinese Remainder Theorem problem. */ public static int solveCRT(List remainders, List moduli) { int product = 1; @@ -46,11 +45,11 @@ public static int solveCRT(List remainders, List moduli) { } /** - * @brief Computes the modular inverse of a number with respect to a modulus using - * the Extended Euclidean Algorithm. * @param a The number for which to find the inverse. * @param m The modulus. * @return The modular inverse of a modulo m. + * @brief Computes the modular inverse of a number with respect to a modulus using + * the Extended Euclidean Algorithm. */ private static int modInverse(int a, int m) { int m0 = m; diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java index 87fc5af57b8d..656b542dfdd7 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -17,7 +17,7 @@ private CircularConvolutionFFT() { /** * This method pads the signal with zeros until it reaches the new size. * - * @param x The signal to be padded. + * @param x The signal to be padded. * @param newSize The new size of the signal. */ private static void padding(Collection x, int newSize) { diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index ed1ba1bbefc3..6f45b33fa109 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -17,7 +17,7 @@ private ConvolutionFFT() { /** * This method pads the signal with zeros until it reaches the new size. * - * @param x The signal to be padded. + * @param x The signal to be padded. * @param newSize The new size of the signal. */ private static void padding(Collection x, int newSize) { @@ -61,7 +61,7 @@ public static ArrayList convolutionFFT(ArrayList a, Ar } FFT.fft(convolved, true); // IFFT convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came - // from + // from // paddingPowerOfTwo() method inside the fft() method. return convolved; diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java index e8f5305c7569..1719b24a0048 100644 --- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java +++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java @@ -4,13 +4,13 @@ * @author Suraj Kumar Modi * You are given a number n. You need to find the digital root of n. * DigitalRoot of a number is the recursive sum of its digits until we get a single digit number. - * + *

    * Test Case 1: * Input: * n = 1 * Output: 1 * Explanation: Digital root of 1 is 1 - * + *

    * Test Case 2: * Input: * n = 99999 @@ -41,7 +41,7 @@ private 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 + // return the value return single(n); } else { return digitalRoot(single(n)); diff --git a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java index acf1e55d49c8..3d9fa1cee38f 100644 --- a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java +++ b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java @@ -1,8 +1,8 @@ /** * A number is said to be Dudeney if the sum of the digits, is the cube root of the entered number. * Example- Let the number be 512, its sum of digits is 5+1+2=8. The cube root of 512 is also 8. - * Since, the sum of the digits is equal to the cube root of the entered number; - * it is a Dudeney Number. + * Since, the sum of the digits is equal to the cube root of the entered number; + * it is a Dudeney Number. */ package com.thealgorithms.maths; diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index 3663b6c534aa..4364934f4d54 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -49,9 +49,9 @@ public static void main(String[] args) { * calculates the next y-value based on the current value of x, y and the * stepSize the console. * - * @param xCurrent Current x-value. - * @param stepSize Step-size on the x-axis. - * @param yCurrent Current y-value. + * @param xCurrent Current x-value. + * @param stepSize Step-size on the x-axis. + * @param yCurrent Current y-value. * @param differentialEquation The differential equation to be solved. * @return The next y-value. */ @@ -66,10 +66,10 @@ public static double eulerStep(double xCurrent, double stepSize, double yCurrent * Loops through all the steps until xEnd is reached, adds a point for each * step and then returns all the points * - * @param xStart First x-value. - * @param xEnd Last x-value. - * @param stepSize Step-size on the x-axis. - * @param yStart First y-value. + * @param xStart First x-value. + * @param xEnd Last x-value. + * @param stepSize Step-size on the x-axis. + * @param yStart First y-value. * @param differentialEquation The differential equation to be solved. * @return The points constituting the solution of the differential * equation. diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java index 91754bd1a80b..117d36deedb9 100644 --- a/src/main/java/com/thealgorithms/maths/FFT.java +++ b/src/main/java/com/thealgorithms/maths/FFT.java @@ -187,8 +187,9 @@ public double imaginary() { * https://www.geeksforgeeks.org/iterative-fast-fourier-transformation-polynomial-multiplication/ * https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm * https://cp-algorithms.com/algebra/fft.html - * @param x The discrete signal which is then converted to the FFT or the - * IFFT of signal x. + * + * @param x The discrete signal which is then converted to the FFT or the + * IFFT of signal x. * @param inverse True if you want to find the inverse FFT. * @return */ @@ -263,7 +264,7 @@ public static ArrayList inverseFFT(int n, boolean inverse, ArrayList x, boolean inverse) { diff --git a/src/main/java/com/thealgorithms/maths/FactorialRecursion.java b/src/main/java/com/thealgorithms/maths/FactorialRecursion.java index d9bafd1e39e9..743d8afd03fe 100644 --- a/src/main/java/com/thealgorithms/maths/FactorialRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FactorialRecursion.java @@ -3,6 +3,7 @@ public final class FactorialRecursion { private FactorialRecursion() { } + /** * Recursive FactorialRecursion Method * diff --git a/src/main/java/com/thealgorithms/maths/FastExponentiation.java b/src/main/java/com/thealgorithms/maths/FastExponentiation.java index 27f49e27ff30..8bfce27b34f1 100644 --- a/src/main/java/com/thealgorithms/maths/FastExponentiation.java +++ b/src/main/java/com/thealgorithms/maths/FastExponentiation.java @@ -14,7 +14,7 @@ *

    * *

    Time complexity: O(log(exp)) — much faster than naive exponentiation (O(exp)).

    - * + *

    * For more information, please visit {@link https://en.wikipedia.org/wiki/Exponentiation_by_squaring} */ public final class FastExponentiation { @@ -33,11 +33,11 @@ private FastExponentiation() { * the exponent at each step. It multiplies the base to the result when the exponent is odd. * * @param base the base number to be raised to the power of exp - * @param exp the exponent to which the base is raised - * @param mod the modulus to ensure the result does not overflow - * @return (base^exp) % mod + * @param exp the exponent to which the base is raised + * @param mod the modulus to ensure the result does not overflow + * @return (base ^ exp) % mod * @throws IllegalArgumentException if the modulus is less than or equal to 0 - * @throws ArithmeticException if the exponent is negative (not supported in this implementation) + * @throws ArithmeticException if the exponent is negative (not supported in this implementation) */ public static long fastExponentiation(long base, long exp, long mod) { if (mod <= 0) { diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java index 01a52b913d30..77ff463104f5 100644 --- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java +++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java @@ -8,11 +8,12 @@ public final class FastInverseSqrt { private FastInverseSqrt() { } + /** * 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 - * + *

    * OUTPUT : * Input - number = 4522 * Output: it calculates the inverse squareroot of a number and returns true with it matches the diff --git a/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java b/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java index 781275d3130d..68b71b5eeec3 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java @@ -8,12 +8,13 @@ public final class FibonacciNumberCheck { private FibonacciNumberCheck() { } + /** * Check if a number is perfect square number * * @param number the number to be checked * @return true if {@code number} is a perfect square, otherwise - * false + * false */ public static boolean isPerfectSquare(long number) { long sqrt = (long) Math.sqrt(number); @@ -26,7 +27,7 @@ public static boolean isPerfectSquare(long number) { * * @param number the number * @return true if {@code number} is a Fibonacci number, otherwise - * false + * false * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification */ public static boolean isFibonacciNumber(long number) { diff --git a/src/main/java/com/thealgorithms/maths/FindMax.java b/src/main/java/com/thealgorithms/maths/FindMax.java index 0ff2bdd191ac..cbb9dc9af545 100644 --- a/src/main/java/com/thealgorithms/maths/FindMax.java +++ b/src/main/java/com/thealgorithms/maths/FindMax.java @@ -5,11 +5,10 @@ private FindMax() { } /** - * @brief finds the maximum value stored in the input array - * * @param array the input array - * @exception IllegalArgumentException input array is empty * @return the maximum value stored in the input array + * @throws IllegalArgumentException input array is empty + * @brief finds the maximum value stored in the input array */ public static int findMax(final int[] array) { int n = array.length; diff --git a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java index 950a0ebe0085..989a497fa85d 100644 --- a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java @@ -4,12 +4,13 @@ public final class FindMaxRecursion { private FindMaxRecursion() { } + /** * Get max of an array using divide and conquer algorithm * * @param array contains elements - * @param low the index of the first element - * @param high the index of the last element + * @param low the index of the first element + * @param high the index of the last element * @return max of {@code array} */ public static int max(final int[] array, final int low, final int high) { diff --git a/src/main/java/com/thealgorithms/maths/FindMin.java b/src/main/java/com/thealgorithms/maths/FindMin.java index 76fa2e815ee0..62a938d72870 100644 --- a/src/main/java/com/thealgorithms/maths/FindMin.java +++ b/src/main/java/com/thealgorithms/maths/FindMin.java @@ -5,11 +5,10 @@ private FindMin() { } /** - * @brief finds the minimum value stored in the input array - * * @param array the input array - * @exception IllegalArgumentException input array is empty * @return the mimum value stored in the input array + * @throws IllegalArgumentException input array is empty + * @brief finds the minimum value stored in the input array */ public static int findMin(final int[] array) { if (array.length == 0) { diff --git a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java index a2cf1b36d6cb..3027b93b7d31 100644 --- a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java @@ -9,8 +9,8 @@ private FindMinRecursion() { * Get min of an array using divide and conquer algorithm * * @param array contains elements - * @param low the index of the first element - * @param high the index of the last element + * @param low the index of the first element + * @param high the index of the last element * @return min of {@code array} */ diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index df27516367b2..307d6752974e 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -1,12 +1,12 @@ package com.thealgorithms.maths; /** - * This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers. - * + * This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers. + *

    * The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers without leaving a remainder. - * + *

    * The GCD can be computed using the Euclidean algorithm, which is based on the principle that the GCD of two numbers also divides their difference. - * + *

    * For more information, refer to the * Greatest Common Divisor Wikipedia page. * @@ -18,6 +18,7 @@ * int result2 = GCD.gcd(48, 18, 30); * System.out.println("GCD of 48, 18, and 30: " + result2); // Output: 6 *

    + * * @author Oskar Enmalm 3/10/17 */ public final class GCD { @@ -49,10 +50,9 @@ public static int gcd(int num1, int num2) { } /** - * @brief computes gcd of an array of numbers - * * @param numbers the input array * @return gcd of all of the numbers in the input array + * @brief computes gcd of an array of numbers */ public static int gcd(int... numbers) { int result = 0; diff --git a/src/main/java/com/thealgorithms/maths/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java index 5792e925a8aa..30c93c3b3b26 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -11,7 +11,7 @@ private HarshadNumber() { * * @param n The number to be checked * @return {@code true} if {@code a} is Harshad number, otherwise - * {@code false} + * {@code false} */ public static boolean isHarshad(long n) { if (n <= 0) { @@ -33,7 +33,7 @@ public static boolean isHarshad(long n) { * * @param s The number in String to be checked * @return {@code true} if {@code a} is Harshad number, otherwise - * {@code false} + * {@code false} */ public static boolean isHarshad(String s) { final Long n = Long.valueOf(s); diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java index 98d839011a7f..75bb19bceb1a 100644 --- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java +++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java @@ -5,18 +5,18 @@ * 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 - */ + *

    + * 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 final class JosephusProblem { private JosephusProblem() { } diff --git a/src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java b/src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java index 298fcb7e85f8..779f1ed874ce 100644 --- a/src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java +++ b/src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java @@ -24,7 +24,7 @@ * Then, the product of x and y can be expressed as: * x * y = (a * c) * 10^(2*m) + ((a * d) + (b * c)) * 10^m + (b * d) * - * + *

    * The Karatsuba algorithm calculates this more efficiently by reducing the number of * multiplications from four to three by using the identity: * diff --git a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java index 03f18aca786f..e02ddab53596 100644 --- a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java +++ b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java @@ -2,9 +2,9 @@ /** * Utility class for checking if a number is a Krishnamurthy number. - * + *

    * A Krishnamurthy number (also known as a Strong number) is a number whose sum of the factorials of its digits is equal to the number itself. - * + *

    * For example, 145 is a Krishnamurthy number because 1! + 4! + 5! = 1 + 24 + 120 = 145. * Example usage: *

    diff --git a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java
    index 9ec11e9b3220..11f3e1141cac 100644
    --- a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java
    +++ b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java
    @@ -4,6 +4,7 @@
      * 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 final class LeastCommonMultiple {
    diff --git a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java
    index c0f55f5e3485..04d21434d4f0 100644
    --- a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java
    +++ b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java
    @@ -20,8 +20,8 @@ private 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
    +     * @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) {
    diff --git a/src/main/java/com/thealgorithms/maths/LongDivision.java b/src/main/java/com/thealgorithms/maths/LongDivision.java
    index 45e97b1c14c3..7a04a49f6b3a 100644
    --- a/src/main/java/com/thealgorithms/maths/LongDivision.java
    +++ b/src/main/java/com/thealgorithms/maths/LongDivision.java
    @@ -11,6 +11,7 @@
     public final class LongDivision {
         private LongDivision() {
         }
    +
         public static int divide(int dividend, int divisor) {
             long newDividend1 = dividend;
             long newDivisor1 = divisor;
    diff --git a/src/main/java/com/thealgorithms/maths/MatrixRank.java b/src/main/java/com/thealgorithms/maths/MatrixRank.java
    index 7a628b92dccb..b91ac58b168d 100644
    --- a/src/main/java/com/thealgorithms/maths/MatrixRank.java
    +++ b/src/main/java/com/thealgorithms/maths/MatrixRank.java
    @@ -21,10 +21,9 @@ private MatrixRank() {
         private static final double EPSILON = 1e-10;
     
         /**
    -     * @brief Computes the rank of the input matrix
    -     *
          * @param matrix The input matrix
          * @return The rank of the input matrix
    +     * @brief Computes the rank of the input matrix
          */
         public static int computeRank(double[][] matrix) {
             validateInputMatrix(matrix);
    @@ -88,11 +87,10 @@ private static boolean hasValidRows(double[][] matrix) {
         }
     
         /**
    -     * @brief Checks if the input matrix is a jagged matrix.
    -     * Jagged matrix is a matrix where the number of columns in each row is not the same.
    -     *
          * @param matrix The input matrix
          * @return True if the input matrix is a jagged matrix, false otherwise
    +     * @brief Checks if the input matrix is a jagged matrix.
    +     * Jagged matrix is a matrix where the number of columns in each row is not the same.
          */
         private static boolean isJaggedMatrix(double[][] matrix) {
             int numColumns = matrix[0].length;
    @@ -105,16 +103,15 @@ private static boolean isJaggedMatrix(double[][] matrix) {
         }
     
         /**
    +     * @param matrix    The input matrix
    +     * @param rowMarked An array indicating which rows have been marked
    +     * @param colIndex  The column index
    +     * @return The pivot row index, or the number of rows if no suitable pivot row was found
          * @brief The pivot row is the row in the matrix that is used to eliminate other rows and reduce the matrix to its row echelon form.
          * The pivot row is selected as the first row (from top to bottom) where the value in the current column (the pivot column) is not zero.
          * This row is then used to "eliminate" other rows, by subtracting multiples of the pivot row from them, so that all other entries in the pivot column become zero.
          * This process is repeated for each column, each time selecting a new pivot row, until the matrix is in row echelon form.
          * The number of pivot rows (rows with a leading entry, or pivot) then gives the rank of the matrix.
    -     *
    -     * @param matrix The input matrix
    -     * @param rowMarked An array indicating which rows have been marked
    -     * @param colIndex The column index
    -     * @return The pivot row index, or the number of rows if no suitable pivot row was found
          */
         private static int findPivotRow(double[][] matrix, boolean[] rowMarked, int colIndex) {
             int numRows = matrix.length;
    @@ -127,12 +124,11 @@ private static int findPivotRow(double[][] matrix, boolean[] rowMarked, int colI
         }
     
         /**
    -     * @brief This method divides all values in the pivot row by the value in the given column.
    -     * This ensures that the pivot value itself will be 1, which simplifies further calculations.
    -     *
    -     * @param matrix The input matrix
    +     * @param matrix   The input matrix
          * @param pivotRow The pivot row index
          * @param colIndex The column index
    +     * @brief This method divides all values in the pivot row by the value in the given column.
    +     * This ensures that the pivot value itself will be 1, which simplifies further calculations.
          */
         private static void normalizePivotRow(double[][] matrix, int pivotRow, int colIndex) {
             int numColumns = matrix[0].length;
    @@ -142,13 +138,12 @@ private static void normalizePivotRow(double[][] matrix, int pivotRow, int colIn
         }
     
         /**
    +     * @param matrix   The input matrix
    +     * @param pivotRow The pivot row index
    +     * @param colIndex The column index
          * @brief This method subtracts multiples of the pivot row from all other rows,
          * so that all values in the given column of other rows will be zero.
          * This is a key step in reducing the matrix to row echelon form.
    -     *
    -     * @param matrix The input matrix
    -     * @param pivotRow The pivot row index
    -     * @param colIndex The column index
          */
         private static void eliminateRows(double[][] matrix, int pivotRow, int colIndex) {
             int numRows = matrix.length;
    diff --git a/src/main/java/com/thealgorithms/maths/MaxValue.java b/src/main/java/com/thealgorithms/maths/MaxValue.java
    index d88291060f51..a82a61137afd 100644
    --- a/src/main/java/com/thealgorithms/maths/MaxValue.java
    +++ b/src/main/java/com/thealgorithms/maths/MaxValue.java
    @@ -3,6 +3,7 @@
     public final class MaxValue {
         private MaxValue() {
         }
    +
         /**
          * Returns the greater of two {@code int} values. That is, the result is the
          * argument closer to the value of {@link Integer#MAX_VALUE}. If the
    diff --git a/src/main/java/com/thealgorithms/maths/Means.java b/src/main/java/com/thealgorithms/maths/Means.java
    index dccc820b172e..9ce230c656d7 100644
    --- a/src/main/java/com/thealgorithms/maths/Means.java
    +++ b/src/main/java/com/thealgorithms/maths/Means.java
    @@ -14,10 +14,10 @@ private Means() {
         }
     
         /**
    -     * @brief computes the [Arithmetic Mean](https://en.wikipedia.org/wiki/Arithmetic_mean) of the input
          * @param numbers the input numbers
    -     * @throws IllegalArgumentException empty input
          * @return the arithmetic mean of the input numbers
    +     * @throws IllegalArgumentException empty input
    +     * @brief computes the [Arithmetic Mean](https://en.wikipedia.org/wiki/Arithmetic_mean) of the input
          */
         public static Double arithmetic(final Iterable numbers) {
             checkIfNotEmpty(numbers);
    @@ -25,10 +25,10 @@ public static Double arithmetic(final Iterable numbers) {
         }
     
         /**
    -     * @brief computes the [Geometric Mean](https://en.wikipedia.org/wiki/Geometric_mean) of the input
          * @param numbers the input numbers
    -     * @throws IllegalArgumentException empty input
          * @return the geometric mean of the input numbers
    +     * @throws IllegalArgumentException empty input
    +     * @brief computes the [Geometric Mean](https://en.wikipedia.org/wiki/Geometric_mean) of the input
          */
         public static Double geometric(final Iterable numbers) {
             checkIfNotEmpty(numbers);
    @@ -36,10 +36,10 @@ public static Double geometric(final Iterable numbers) {
         }
     
         /**
    -     * @brief computes the [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) of the input
          * @param numbers the input numbers
    -     * @throws IllegalArgumentException empty input
          * @return the harmonic mean of the input numbers
    +     * @throws IllegalArgumentException empty input
    +     * @brief computes the [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) of the input
          */
         public static Double harmonic(final Iterable numbers) {
             checkIfNotEmpty(numbers);
    diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java
    index e4daec8fc11a..70ddde444154 100644
    --- a/src/main/java/com/thealgorithms/maths/Median.java
    +++ b/src/main/java/com/thealgorithms/maths/Median.java
    @@ -11,6 +11,7 @@ private Median() {
     
         /**
          * Calculate average median
    +     *
          * @param values sorted numbers to find median of
          * @return median of given {@code values}
          */
    diff --git a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
    index f889213abfcb..2db6bf30d0cd 100644
    --- a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
    +++ b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
    @@ -14,8 +14,8 @@ private MillerRabinPrimalityCheck() {
          *
          * @param n Whole number which is tested on primality
          * @param k Number of iterations
    -     *       If n is composite then running k iterations of the Miller–Rabin
    -     *       test will declare n probably prime with a probability at most 4^(−k)
    +     *          If n is composite then running k iterations of the Miller–Rabin
    +     *          test will declare n probably prime with a probability at most 4^(−k)
          * @return true or false whether the given number is probably prime or not
          */
     
    @@ -70,9 +70,8 @@ public static boolean deterministicMillerRabin(long n) { // returns true if n is
          * @param a Random number (prime base) to check if it holds certain equality
          * @param d Number which holds this equation: 'n - 1 = 2^s * d'
          * @param s Number of twos in (n - 1) factorization
    -     *
          * @return true or false whether the numbers hold the equation or not
    -     *          the equations are described on the websites mentioned at the beginning of the class
    +     * the equations are described on the websites mentioned at the beginning of the class
          */
         private static boolean checkComposite(long n, long a, long d, int s) {
             long x = powerModP(a, d, n);
    diff --git a/src/main/java/com/thealgorithms/maths/MinValue.java b/src/main/java/com/thealgorithms/maths/MinValue.java
    index 88e28e8816c6..2f8e80595e10 100644
    --- a/src/main/java/com/thealgorithms/maths/MinValue.java
    +++ b/src/main/java/com/thealgorithms/maths/MinValue.java
    @@ -3,6 +3,7 @@
     public final class MinValue {
         private MinValue() {
         }
    +
         /**
          * Returns the smaller of two {@code int} values. That is, the result the
          * argument closer to the value of {@link Integer#MIN_VALUE}. If the
    diff --git a/src/main/java/com/thealgorithms/maths/MobiusFunction.java b/src/main/java/com/thealgorithms/maths/MobiusFunction.java
    index 915d0d9a6dae..2ada83729bd3 100644
    --- a/src/main/java/com/thealgorithms/maths/MobiusFunction.java
    +++ b/src/main/java/com/thealgorithms/maths/MobiusFunction.java
    @@ -20,10 +20,10 @@ private 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
    +     * @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) {
    diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java
    index 9c95ebde3740..2c702f14f01b 100644
    --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java
    +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java
    @@ -4,7 +4,7 @@
      * 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.
    - *
    + * 

    * Explanation of the code: * Let us assume we have an array [1, 2, 1, 2, 3, 4] * Property of XOR: num ^ num = 0. diff --git a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java index 6484026c14dd..d41e7f93da83 100644 --- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java +++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java @@ -8,21 +8,21 @@ /** * @brief class computing the n-th ugly number (when they are sorted) * @details the ugly numbers with base [2, 3, 5] are all numbers of the form 2^a*3^b^5^c, - * where the exponents a, b, c are non-negative integers. - * Some properties of ugly numbers: - * - base [2, 3, 5] ugly numbers are the 5-smooth numbers, cf. https://oeis.org/A051037 - * - base [2, 3, 5, 7] ugly numbers are 7-smooth numbers, cf. https://oeis.org/A002473 - * - base [2] ugly numbers are the non-negative powers of 2, - * - the base [2, 3, 5] ugly numbers are the same as base [5, 6, 2, 3, 5] ugly numbers + * where the exponents a, b, c are non-negative integers. + * Some properties of ugly numbers: + * - base [2, 3, 5] ugly numbers are the 5-smooth numbers, cf. https://oeis.org/A051037 + * - base [2, 3, 5, 7] ugly numbers are 7-smooth numbers, cf. https://oeis.org/A002473 + * - base [2] ugly numbers are the non-negative powers of 2, + * - the base [2, 3, 5] ugly numbers are the same as base [5, 6, 2, 3, 5] ugly numbers */ public class NthUglyNumber { private ArrayList uglyNumbers = new ArrayList<>(Arrays.asList(1L)); private ArrayList> positions = new ArrayList<>(); /** - * @brief initialized the object allowing to compute ugly numbers with given base * @param baseNumbers the given base of ugly numbers - * @exception IllegalArgumentException baseNumber is empty + * @throws IllegalArgumentException baseNumber is empty + * @brief initialized the object allowing to compute ugly numbers with given base */ NthUglyNumber(final int[] baseNumbers) { if (baseNumbers.length == 0) { @@ -36,8 +36,8 @@ public class NthUglyNumber { /** * @param n the zero-based-index of the queried ugly number - * @exception IllegalArgumentException n is negative * @return the n-th ugly number (starting from index 0) + * @throws IllegalArgumentException n is negative */ public Long get(final int n) { if (n < 0) { diff --git a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java index fc538196c7da..26732ae93520 100644 --- a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java @@ -6,6 +6,7 @@ public final class NumberOfDigits { private NumberOfDigits() { } + /** * Find the number of digits in a number. * diff --git a/src/main/java/com/thealgorithms/maths/PalindromeNumber.java b/src/main/java/com/thealgorithms/maths/PalindromeNumber.java index a22d63897b37..55c8a2db7311 100644 --- a/src/main/java/com/thealgorithms/maths/PalindromeNumber.java +++ b/src/main/java/com/thealgorithms/maths/PalindromeNumber.java @@ -3,6 +3,7 @@ public final class PalindromeNumber { private PalindromeNumber() { } + /** * Check if {@code n} is palindrome number or not * diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index 9a9d4450cb98..452917051399 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -5,35 +5,34 @@ private 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 the French mathematician Blaise Pascal, although other mathematicians studied it - *centuries before him in India, Persia, China, Germany, and Italy. - * + * 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 the French mathematician Blaise Pascal, although other mathematicians studied it + * centuries before him in India, Persia, China, Germany, and Italy. + *

    * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top - *(the 0th row). The entries in each row are numbered from the left beginning with k=0 and are - *usually staggered relative to the numbers in the adjacent rows. The triangle may be - *constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero - *entry 1. Each entry of each subsequent row is constructed by adding the number above and to - *the left with the number above and to the right, treating blank entries as 0. For example, the - *initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers - *1 and 3 in the third row are added to produce the number 4 in the fourth row. * - * - *

    - * link:-https://en.wikipedia.org/wiki/Pascal%27s_triangle + * (the 0th row). The entries in each row are numbered from the left beginning with k=0 and are + * usually staggered relative to the numbers in the adjacent rows. The triangle may be + * constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero + * entry 1. Each entry of each subsequent row is constructed by adding the number above and to + * the left with the number above and to the right, treating blank entries as 0. For example, the + * initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers + * 1 and 3 in the third row are added to produce the number 4 in the fourth row. * * *

    - * Example:- - * 1 - * 1 1 - * 1 2 1 - * 1 3 3 1 - * 1 4 6 4 1 - * 1 5 10 10 5 1 - * 1 6 15 20 15 6 1 - * 1 7 21 35 35 21 7 1 - * 1 8 28 56 70 56 28 8 1 + * link:-https://en.wikipedia.org/wiki/Pascal%27s_triangle * + *

    + * Example:- + * 1 + * 1 1 + * 1 2 1 + * 1 3 3 1 + * 1 4 6 4 1 + * 1 5 10 10 5 1 + * 1 6 15 20 15 6 1 + * 1 7 21 35 35 21 7 1 + * 1 8 28 56 70 56 28 8 1 */ public static int[][] pascal(int n) { diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java index 2a935b067094..1c84173925ea 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -5,7 +5,7 @@ * sum of its positive divisors, excluding the number itself. For instance, 6 * has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a * perfect number. - * + *

    * link:https://en.wikipedia.org/wiki/Perfect_number */ public final class PerfectNumber { diff --git a/src/main/java/com/thealgorithms/maths/Perimeter.java b/src/main/java/com/thealgorithms/maths/Perimeter.java index f8aa1876d388..84639b517cea 100644 --- a/src/main/java/com/thealgorithms/maths/Perimeter.java +++ b/src/main/java/com/thealgorithms/maths/Perimeter.java @@ -10,7 +10,7 @@ private Perimeter() { * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular * Hexagon. * - * @param n for number of sides. + * @param n for number of sides. * @param side for length of each side. * @return Perimeter of given polygon */ @@ -40,7 +40,7 @@ public static float perimeterIrregularPolygon(float side1, float side2, float si /** * Calculate the Perimeter of rectangle * - * @param length for length of rectangle + * @param length for length of rectangle * @param breadth for breadth of rectangle * @return Perimeter of given rectangle */ diff --git a/src/main/java/com/thealgorithms/maths/PiNilakantha.java b/src/main/java/com/thealgorithms/maths/PiNilakantha.java index 6d43f134c94c..0711eae1235e 100644 --- a/src/main/java/com/thealgorithms/maths/PiNilakantha.java +++ b/src/main/java/com/thealgorithms/maths/PiNilakantha.java @@ -17,9 +17,9 @@ public static void main(String[] args) { /** * @param iterations number of times the infinite series gets repeated Pi - * get more accurate the higher the value of iterations is Values from 0 up - * to 500 are allowed since double precision is not sufficient for more than - * about 500 repetitions of this algorithm + * get more accurate the higher the value of iterations is Values from 0 up + * to 500 are allowed since double precision is not sufficient for more than + * about 500 repetitions of this algorithm * @return the pi value of the calculation with a precision of x iteration */ public static double calculatePi(int iterations) { diff --git a/src/main/java/com/thealgorithms/maths/PollardRho.java b/src/main/java/com/thealgorithms/maths/PollardRho.java index 7fa913b21b7e..09d538587802 100644 --- a/src/main/java/com/thealgorithms/maths/PollardRho.java +++ b/src/main/java/com/thealgorithms/maths/PollardRho.java @@ -42,9 +42,9 @@ private PollardRho() { /** * This method returns a polynomial in x computed modulo n * - * @param base Integer base of the polynomial + * @param base Integer base of the polynomial * @param modulus Integer is value which is to be used to perform modulo operation over the - * polynomial + * polynomial * @return Integer (((base * base) - 1) % modulus) */ static int g(int base, int modulus) { diff --git a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java index 93c8252ab929..24b9a36bcaa9 100644 --- a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java +++ b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java @@ -2,6 +2,7 @@ /** * calculate Power using Recursion + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ diff --git a/src/main/java/com/thealgorithms/maths/PrimeCheck.java b/src/main/java/com/thealgorithms/maths/PrimeCheck.java index 628a819aeba4..07a5e0da9360 100644 --- a/src/main/java/com/thealgorithms/maths/PrimeCheck.java +++ b/src/main/java/com/thealgorithms/maths/PrimeCheck.java @@ -69,10 +69,11 @@ public static boolean fermatPrimeChecking(int n, int iteration) { /** * * + * * @param a basis * @param b exponent * @param c modulo - * @return (a^b) mod c + * @return (a ^ b) mod c */ private static long modPow(long a, long b, long c) { long res = 1; diff --git a/src/main/java/com/thealgorithms/maths/ReverseNumber.java b/src/main/java/com/thealgorithms/maths/ReverseNumber.java index 667a0a43fc2c..3409fe7e86ab 100644 --- a/src/main/java/com/thealgorithms/maths/ReverseNumber.java +++ b/src/main/java/com/thealgorithms/maths/ReverseNumber.java @@ -8,10 +8,10 @@ private ReverseNumber() { } /** - * @brief reverses the input number * @param number the input number - * @exception IllegalArgumentException number is negative * @return the number created by reversing the order of digits of the input number + * @throws IllegalArgumentException number is negative + * @brief reverses the input number */ public static int reverseNumber(int number) { if (number < 0) { diff --git a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java index 8f5d44dbe146..e2389ab64079 100644 --- a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java +++ b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java @@ -3,10 +3,10 @@ /** * Translates numbers into the Roman Numeral System. * - * @see Roman - * numerals * @author Sokratis Fotkatzikis * @version 1.0 + * @see Roman + * numerals */ public final class RomanNumeralUtil { private RomanNumeralUtil() { diff --git a/src/main/java/com/thealgorithms/maths/SecondMinMax.java b/src/main/java/com/thealgorithms/maths/SecondMinMax.java index e5a2d3b89085..43a9bac60978 100644 --- a/src/main/java/com/thealgorithms/maths/SecondMinMax.java +++ b/src/main/java/com/thealgorithms/maths/SecondMinMax.java @@ -6,8 +6,9 @@ public final class SecondMinMax { /** * Utility class for finding second maximum or minimum based on BiPredicate - * @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same + * * @return the second minimum / maximum value from the input array + * @throws IllegalArgumentException => if input array is of length less than 2 also if all elements are same * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) */ @@ -31,10 +32,10 @@ private static int secondBest(final int[] arr, final int initialVal, final BiPre } /** - * @brief Finds the Second minimum / maximum value from the array * @param arr the input array - * @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same * @return the second minimum / maximum value from the input array + * @throws IllegalArgumentException => if input array is of length less than 2 also if all elements are same + * @brief Finds the Second minimum / maximum value from the array * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) */ diff --git a/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java index f22d22e8c6af..9c0af07d3734 100644 --- a/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java @@ -50,10 +50,10 @@ private static int[] extractPrimes(Type[] isPrimeArray) { } /** - * @brief finds all of the prime numbers up to the given upper (inclusive) limit * @param n upper (inclusive) limit - * @exception IllegalArgumentException n is non-positive * @return the array of all primes up to the given number (inclusive) + * @throws IllegalArgumentException n is non-positive + * @brief finds all of the prime numbers up to the given upper (inclusive) limit */ public static int[] findPrimesTill(int n) { return extractPrimes(sievePrimesTill(n)); diff --git a/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java b/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java index caa1abfc3203..b815f7f775f1 100644 --- a/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java +++ b/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java @@ -6,7 +6,7 @@ * This class implements the Solovay-Strassen primality test, * which is a probabilistic algorithm to determine whether a number is prime. * The algorithm is based on properties of the Jacobi symbol and modular exponentiation. - * + *

    * For more information, go to {@link https://en.wikipedia.org/wiki/Solovay%E2%80%93Strassen_primality_test} */ final class SolovayStrassenPrimalityTest { @@ -35,10 +35,10 @@ public static SolovayStrassenPrimalityTest getSolovayStrassenPrimalityTest(int s /** * Calculates modular exponentiation using the method of exponentiation by squaring. * - * @param base the base number + * @param base the base number * @param exponent the exponent - * @param mod the modulus - * @return (base^exponent) mod mod + * @param mod the modulus + * @return (base ^ exponent) mod mod */ private static long calculateModularExponentiation(long base, long exponent, long mod) { long x = 1; // This will hold the result of (base^exponent) % mod @@ -60,7 +60,7 @@ private static long calculateModularExponentiation(long base, long exponent, lon /** * Computes the Jacobi symbol (a/n), which is a generalization of the Legendre symbol. * - * @param a the numerator + * @param a the numerator * @param num the denominator (must be an odd positive integer) * @return the Jacobi symbol value: 1, -1, or 0 */ @@ -101,7 +101,7 @@ public int calculateJacobi(long a, long num) { /** * Performs the Solovay-Strassen primality test on a given number. * - * @param num the number to be tested for primality + * @param num the number to be tested for primality * @param iterations the number of iterations to run for accuracy * @return true if num is likely prime, false if it is composite */ diff --git a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java index 22e9fee00605..519397a62074 100644 --- a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java +++ b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java @@ -17,12 +17,13 @@ public final class SquareFreeInteger { private SquareFreeInteger() { } + /** * This method returns whether an integer is square free * * @param number Integer value which is to be checked * @return false when number has repeated prime factors - * true when number has non repeated prime factors + * true when number has non repeated prime factors * @throws IllegalArgumentException when number is negative or zero */ public static boolean isSquareFreeInteger(int number) { diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 80d185c93785..f3a658c92106 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -23,7 +23,7 @@ public static double squareRoot(int 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. + // 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); } diff --git a/src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java b/src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java index bcd9a8467e50..77139b6becb4 100644 --- a/src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java +++ b/src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java @@ -12,6 +12,7 @@ public class StrobogrammaticNumber { /** * Check if a number is strobogrammatic + * * @param number the number to be checked * @return true if the number is strobogrammatic, false otherwise */ diff --git a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java index 315f0d3a7d28..1301b0b5e7d6 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java +++ b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java @@ -17,7 +17,7 @@ private SumOfArithmeticSeries() { /** * Calculate sum of arithmetic series * - * @param firstTerm the initial term of an arithmetic series + * @param firstTerm the initial term of an arithmetic series * @param commonDiff the common difference of an arithmetic series * @param numOfTerms the total terms of an arithmetic series * @return sum of given arithmetic series diff --git a/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java b/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java index c0a1e782659a..0b47575131dd 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java +++ b/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java @@ -2,7 +2,7 @@ /** * This program calculates the sum of the first n odd numbers. - * + *

    * https://www.cuemath.com/algebra/sum-of-odd-numbers/ */ diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java index 5369182a0a94..7431e2a2b035 100644 --- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java +++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java @@ -5,10 +5,11 @@ public class SumWithoutArithmeticOperators { /** * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). * All the integers associated are unsigned 32-bit integers - *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator - *@param a - It is the first number - *@param b - It is the second number - *@return returns an integer which is the sum of the first and second number + * https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator + * + * @param a - It is the first number + * @param b - It is the second number + * @return returns an integer which is the sum of the first and second number */ public int getSum(int a, int b) { diff --git a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java index 877ef4227afc..d708c2792d74 100644 --- a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java +++ b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java @@ -4,7 +4,7 @@ * The trinomial triangle is a variation of Pascal’s triangle. The difference * between the two is that an entry in the trinomial triangle is the sum of the * three (rather than the two in Pasacal’s triangle) entries above it - * + *

    * Example Input: n = 4 Output 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 */ public final class TrinomialTriangle { diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java index e2769744bcda..6d508eb1e8e5 100644 --- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java +++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java @@ -1,13 +1,11 @@ package com.thealgorithms.maths; /** + * @author [Syed](https : / / github.com / roeticvampire) * @file - * * @brief Calculates the [Cross * Product](https://en.wikipedia.org/wiki/Cross_product) and the magnitude of * two mathematical 3D vectors. - * - * * @details Cross Product of two vectors gives a vector. Direction Ratios of a * vector are the numeric parts of the given vector. They are the tree parts of * the vector which determine the magnitude (value) of the vector. The method of @@ -18,26 +16,24 @@ * it's value expressed as a number. Let the direction ratios of the first * vector, P be: a, b, c Let the direction ratios of the second vector, Q be: x, * y, z Therefore the calculation for the cross product can be arranged as: - * + *

    * ``` P x Q: 1 1 1 a b c x y z ``` - * + *

    * The direction ratios (DR) are calculated as follows: 1st DR, J: (b * z) - (c * * y) 2nd DR, A: -((a * z) - (c * x)) 3rd DR, N: (a * y) - (b * x) - * + *

    * Therefore, the direction ratios of the cross product are: J, A, N The * following Java Program calculates the direction ratios of the cross products * of two vector. The program uses a function, cross() for doing so. The * direction ratios for the first and the second vector has to be passed one by * one separated by a space character. - * + *

    * Magnitude of a vector is the square root of the sum of the squares of the * direction ratios. - * - * + *

    + *

    * For maintaining filename consistency, Vector class has been termed as * VectorCrossProduct - * - * @author [Syed](https://github.com/roeticvampire) */ public class VectorCrossProduct { diff --git a/src/main/java/com/thealgorithms/maths/Volume.java b/src/main/java/com/thealgorithms/maths/Volume.java index 0f282b2abae2..8d3feff872d4 100644 --- a/src/main/java/com/thealgorithms/maths/Volume.java +++ b/src/main/java/com/thealgorithms/maths/Volume.java @@ -72,8 +72,8 @@ public static double volumeCone(double radius, double height) { /** * Calculate the volume of a prism. * - * @param baseArea area of the given prism's base - * @param height of given prism + * @param baseArea area of the given prism's base + * @param height of given prism * @return volume of given prism */ public static double volumePrism(double baseArea, double height) { @@ -83,8 +83,8 @@ public static double volumePrism(double baseArea, double height) { /** * Calculate the volume of a pyramid. * - * @param baseArea of the given pyramid's base - * @param height of given pyramid + * @param baseArea of the given pyramid's base + * @param height of given pyramid * @return volume of given pyramid */ public static double volumePyramid(double baseArea, double height) { @@ -94,8 +94,8 @@ public static double volumePyramid(double baseArea, double height) { /** * Calculate the volume of a frustum of a cone. * - * @param r1 radius of the top of the frustum - * @param r2 radius of the bottom of the frustum + * @param r1 radius of the top of the frustum + * @param r2 radius of the bottom of the frustum * @param height height of the frustum * @return volume of the frustum */ diff --git a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java index afd34933047a..b72a1ce137eb 100644 --- a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java @@ -5,7 +5,6 @@ /** * @author Anirudh Buvanesh (https://github.com/anirudhb11) For more information * see https://www.geeksforgeeks.org/matrix-exponentiation/ - * */ public final class Fibonacci { private Fibonacci() { @@ -50,7 +49,7 @@ private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) { * Calculates the fibonacci number using matrix exponentiaition technique * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth * fibonacci number + * Outputs the nth * fibonacci number * @return a 2 X 1 array as { {F_n+1}, {F_n} } */ public static int[][] fib(int n) { diff --git a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java index a7e3f651cc85..5b7cd77e9825 100644 --- a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java +++ b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java @@ -3,20 +3,20 @@ import java.awt.Color; /** + * @author [Seth Falco](https://github.com/SethFalco) * @brief A Java implementation of the official W3 documented procedure to * calculate contrast ratio between colors on the web. This is used to calculate * the readability of a foreground color on top of a background color. - * @since 2020-10-15 * @see Color Contrast Ratio - * @author [Seth Falco](https://github.com/SethFalco) + * @since 2020-10-15 */ public class ColorContrastRatio { /** - * @brief Calculates the contrast ratio between two given colors. * @param a Any color, used to get the red, green, and blue values. * @param b Another color, which will be compared against the first color. * @return The contrast ratio between the two colors. + * @brief Calculates the contrast ratio between two given colors. */ public double getContrastRatio(Color a, Color b) { final double aColorLuminance = getRelativeLuminance(a); @@ -30,9 +30,9 @@ public double getContrastRatio(Color a, Color b) { } /** - * @brief Calculates the relative luminance of a given color. * @param color Any color, used to get the red, green, and blue values. * @return The relative luminance of the color. + * @brief Calculates the relative luminance of a given color. * @see More info on relative luminance. */ public double getRelativeLuminance(Color color) { @@ -44,9 +44,9 @@ public double getRelativeLuminance(Color color) { } /** - * @brief Calculates the final value for a color to be used in the relative luminance formula as described in step 1. * @param color8Bit 8-bit representation of a color component value. * @return Value for the provided color component to be used in the relative luminance formula. + * @brief Calculates the final value for a color to be used in the relative luminance formula as described in step 1. */ public double getColor(int color8Bit) { final double sRgb = getColorSRgb(color8Bit); @@ -54,9 +54,9 @@ public double getColor(int color8Bit) { } /** - * @brief Calculates the Color sRGB value as denoted in step 1 of the procedure document. * @param color8Bit 8-bit representation of a color component value. * @return A percentile value of the color component. + * @brief Calculates the Color sRGB value as denoted in step 1 of the procedure document. */ private double getColorSRgb(double color8Bit) { return color8Bit / 255.0; diff --git a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java index 706feab0c69d..8f939fe99b52 100644 --- a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java +++ b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java @@ -45,6 +45,7 @@ public static double[][] invert(double[][] a) { } return x; } + /** * Method to carry out the partial-pivoting Gaussian * elimination. Here index[] stores pivoting order. diff --git a/src/main/java/com/thealgorithms/misc/MapReduce.java b/src/main/java/com/thealgorithms/misc/MapReduce.java index c076957344f9..854e8fc9488b 100644 --- a/src/main/java/com/thealgorithms/misc/MapReduce.java +++ b/src/main/java/com/thealgorithms/misc/MapReduce.java @@ -18,6 +18,7 @@ public final class MapReduce { private MapReduce() { } + /* *Counting all the words frequency within a sentence. */ diff --git a/src/main/java/com/thealgorithms/misc/MatrixTranspose.java b/src/main/java/com/thealgorithms/misc/MatrixTranspose.java index 743682780b01..ed6659298673 100644 --- a/src/main/java/com/thealgorithms/misc/MatrixTranspose.java +++ b/src/main/java/com/thealgorithms/misc/MatrixTranspose.java @@ -1,10 +1,8 @@ package com.thealgorithms.misc; /** - * - * *

    Find the Transpose of Matrix!

    - * + *

    * Simply take input from the user and print the matrix before the transpose and * after the transpose. * @@ -24,9 +22,9 @@ private MatrixTranspose() { * Calculate the transpose of the given matrix. * * @param matrix The matrix to be transposed + * @return The transposed matrix * @throws IllegalArgumentException if the matrix is empty * @throws NullPointerException if the matrix is null - * @return The transposed matrix */ public static int[][] transpose(int[][] matrix) { if (matrix == null || matrix.length == 0) { diff --git a/src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java b/src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java index 89dfce3fe049..d5f9e3bc57cc 100644 --- a/src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java +++ b/src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java @@ -38,6 +38,7 @@ public static int[][] mirrorMatrix(final int[][] originalMatrix) { } return mirroredMatrix; } + private static int[] reverseRow(final int[] inRow) { int[] res = new int[inRow.length]; for (int i = 0; i < inRow.length; ++i) { diff --git a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java index 51dc099ba32e..90b98dd44990 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java @@ -6,7 +6,7 @@ * A simple way of knowing if a singly linked list is palindrome is to push all * the values into a Stack and then compare the list to popped vales from the * Stack. - * + *

    * See more: * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ */ @@ -64,9 +64,11 @@ public static boolean isPalindromeOptimised(Node head) { } return true; } + static class Node { int val; Node next; + Node(int val) { this.val = val; this.next = null; diff --git a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java index 2fc4ed09a792..e1b42fb2797c 100644 --- a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java @@ -11,6 +11,7 @@ private TwoSumProblem() { /** * The function "twoSum" takes an array of integers and a target integer as input, and returns an * array of two indices where the corresponding elements in the input array add up to the target. + * * @param values An array of integers. * @param target The target is the sum that we are trying to find using two numbers from the given array. * @return A pair or indexes such that sum of values at these indexes equals to the target diff --git a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java index b54cbec08f74..20bad20ea7fb 100644 --- a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java +++ b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java @@ -15,7 +15,7 @@ private ArrayLeftRotation() { * Performs a left rotation on the given array by the specified number of positions. * * @param arr the array to be rotated - * @param n the number of positions to rotate the array to the left + * @param n the number of positions to rotate the array to the left * @return a new array containing the elements of the input array rotated to the left */ public static int[] rotateLeft(int[] arr, int n) { diff --git a/src/main/java/com/thealgorithms/others/ArrayRightRotation.java b/src/main/java/com/thealgorithms/others/ArrayRightRotation.java index 125edadb6e73..f731588d9a34 100644 --- a/src/main/java/com/thealgorithms/others/ArrayRightRotation.java +++ b/src/main/java/com/thealgorithms/others/ArrayRightRotation.java @@ -4,7 +4,7 @@ * Provides a method to perform a right rotation on an array. * A left rotation operation shifts each element of the array * by a specified number of positions to the right. - * + *

    * https://en.wikipedia.org/wiki/Right_rotation * */ public final class ArrayRightRotation { @@ -15,7 +15,7 @@ private ArrayRightRotation() { * Performs a right rotation on the given array by the specified number of positions. * * @param arr the array to be rotated - * @param k the number of positions to rotate the array to the left + * @param k the number of positions to rotate the array to the left * @return a new array containing the elements of the input array rotated to the left */ public static int[] rotateRight(int[] arr, int k) { @@ -35,9 +35,10 @@ public static int[] rotateRight(int[] arr, int k) { /** * Performs reversing of a array - * @param arr the array to be reversed + * + * @param arr the array to be reversed * @param start starting position - * @param end ending position + * @param end ending position */ private static void reverseArray(int[] arr, int start, int end) { while (start < end) { diff --git a/src/main/java/com/thealgorithms/others/BFPRT.java b/src/main/java/com/thealgorithms/others/BFPRT.java index 58c6d4e56830..2160bbd35069 100644 --- a/src/main/java/com/thealgorithms/others/BFPRT.java +++ b/src/main/java/com/thealgorithms/others/BFPRT.java @@ -14,7 +14,7 @@ private BFPRT() { * Returns the k smallest elements from the array using the BFPRT algorithm. * * @param arr the input array - * @param k the number of smallest elements to return + * @param k the number of smallest elements to return * @return an array containing the k smallest elements, or null if k is invalid */ public static int[] getMinKNumsByBFPRT(int[] arr, int k) { @@ -39,7 +39,7 @@ public static int[] getMinKNumsByBFPRT(int[] arr, int k) { * Returns the k-th smallest element from the array using the BFPRT algorithm. * * @param arr the input array - * @param k the rank of the smallest element to find + * @param k the rank of the smallest element to find * @return the k-th smallest element */ public static int getMinKthByBFPRT(int[] arr, int k) { @@ -62,10 +62,10 @@ public static int[] copyArray(int[] arr) { /** * BFPRT recursive method to find the k-th smallest element. * - * @param arr the input array + * @param arr the input array * @param begin the starting index - * @param end the ending index - * @param i the index of the desired smallest element + * @param end the ending index + * @param i the index of the desired smallest element * @return the k-th smallest element */ public static int bfprt(int[] arr, int begin, int end, int i) { @@ -86,9 +86,9 @@ public static int bfprt(int[] arr, int begin, int end, int i) { /** * Finds the median of medians as the pivot element. * - * @param arr the input array + * @param arr the input array * @param begin the starting index - * @param end the ending index + * @param end the ending index * @return the median of medians */ public static int medianOfMedians(int[] arr, int begin, int end) { @@ -104,10 +104,10 @@ public static int medianOfMedians(int[] arr, int begin, int end) { /** * Partitions the array around a pivot. * - * @param arr the input array + * @param arr the input array * @param begin the starting index - * @param end the ending index - * @param num the pivot element + * @param end the ending index + * @param num the pivot element * @return the range where the pivot is located */ public static int[] partition(int[] arr, int begin, int end, int num) { @@ -129,9 +129,9 @@ public static int[] partition(int[] arr, int begin, int end, int num) { /** * Finds the median of the elements between the specified range. * - * @param arr the input array + * @param arr the input array * @param begin the starting index - * @param end the ending index + * @param end the ending index * @return the median of the specified range */ public static int getMedian(int[] arr, int begin, int end) { @@ -144,9 +144,9 @@ public static int getMedian(int[] arr, int begin, int end) { /** * Sorts a portion of the array using insertion sort. * - * @param arr the input array + * @param arr the input array * @param begin the starting index - * @param end the ending index + * @param end the ending index */ public static void insertionSort(int[] arr, int begin, int end) { if (arr == null || arr.length < 2) { @@ -167,8 +167,8 @@ public static void insertionSort(int[] arr, int begin, int end) { * Swaps two elements in an array. * * @param arr the input array - * @param i the index of the first element - * @param j the index of the second element + * @param i the index of the first element + * @param j the index of the second element */ public static void swap(int[] arr, int i, int j) { int temp = arr[i]; diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index 836526529374..65ffaea401a8 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -5,16 +5,16 @@ /** * This file contains an implementation of BANKER'S ALGORITM Wikipedia: * https://en.wikipedia.org/wiki/Banker%27s_algorithm - * + *

    * The algorithm for finding out whether or not a system is in a safe state can * be described as follows: 1. Let Work and Finish be vectors of length ‘m’ and * ‘n’ respectively. Initialize: Work= Available Finish [i]=false; for * i=1,2,……,n 2. Find an i such that both a) Finish [i]=false b) Need_i<=work - * + *

    * if no such i exists goto step (4) 3. Work=Work + Allocation_i Finish[i]= true * goto step(2) 4. If Finish[i]=true for all i, then the system is in safe * state. - * + *

    * Time Complexity: O(n*n*m) Space Complexity: O(n*m) where n = number of * processes and m = number of resources. * @@ -38,16 +38,15 @@ static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocatio /** * This method find the system is in safe state or not * - * @param processes[] int array of processes (0...n-1), size = n - * @param availableArray[] int array of number of instances of each - * resource, size = m - * @param maxArray[][] int matrix(2-D array) of maximum demand of each - * process in a system, size = n*m + * @param processes[] int array of processes (0...n-1), size = n + * @param availableArray[] int array of number of instances of each + * resource, size = m + * @param maxArray[][] int matrix(2-D array) of maximum demand of each + * process in a system, size = n*m * @param allocationArray[][] int matrix(2-D array) of the number of - * resources of each type currently allocated to each process, size = n*m - * @param totalProcess number of total processes, n - * @param totalResources number of total resources, m - * + * resources of each type currently allocated to each process, size = n*m + * @param totalProcess number of total processes, n + * @param totalResources number of total resources, m * @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) { diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 3fb97724b5ac..0be386bff740 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -1,11 +1,12 @@ package com.thealgorithms.others; + import java.util.Optional; /** * Utility class implementing Boyer-Moore's Voting Algorithm to find the majority element * in an array. The majority element is defined as the element that appears more than n/2 times * in the array, where n is the length of the array. - * + *

    * For more information on the algorithm, refer to: * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ @@ -55,7 +56,7 @@ private static int findCandidate(final int[] array) { * Counts the occurrences of the candidate element in the array. * * @param candidate the candidate element - * @param array the input array + * @param array the input array * @return the number of times the candidate appears in the array */ private static int countOccurrences(final int candidate, final int[] array) { @@ -71,7 +72,7 @@ private static int countOccurrences(final int candidate, final int[] array) { /** * Determines if the count of the candidate element is more than n/2, where n is the length of the array. * - * @param count the number of occurrences of the candidate + * @param count the number of occurrences of the candidate * @param totalCount the total number of elements in the array * @return true if the candidate is the majority element, false otherwise */ diff --git a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java index 284a290a5af8..9be40642f37d 100644 --- a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java @@ -33,10 +33,10 @@ public class CRCAlgorithm { * The algorithm's main constructor. The most significant variables, used in * the algorithm, are set in their initial values. * - * @param str The binary number P, in a string form, which is used by the - * CRC algorithm + * @param str The binary number P, in a string form, which is used by the + * CRC algorithm * @param size The size of every transmitted message - * @param ber The Bit Error Rate + * @param ber The Bit Error Rate */ public CRCAlgorithm(String str, int size, double ber) { messageChanged = false; @@ -124,7 +124,7 @@ public void generateRandomMess() { * message. * * @param check the variable used to determine, if the message is going to - * be checked from the receiver if true, it is checked otherwise, it is not + * be checked from the receiver if true, it is checked otherwise, it is not */ public void divideMessageWithP(boolean check) { ArrayList x = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/others/Damm.java b/src/main/java/com/thealgorithms/others/Damm.java index 55a4c5b81a89..1bec5c06a73e 100644 --- a/src/main/java/com/thealgorithms/others/Damm.java +++ b/src/main/java/com/thealgorithms/others/Damm.java @@ -44,8 +44,8 @@ private Damm() { * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only - * digits - * @throws NullPointerException if input is null + * digits + * @throws NullPointerException if input is null */ public static boolean dammCheck(String digits) { checkInput(digits); @@ -66,8 +66,8 @@ public static boolean dammCheck(String digits) { * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only - * digits - * @throws NullPointerException if input is null + * digits + * @throws NullPointerException if input is null */ public static String addDammChecksum(String initialDigits) { checkInput(initialDigits); diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java index a379100a2f3b..d848b83756d9 100644 --- a/src/main/java/com/thealgorithms/others/Dijkstra.java +++ b/src/main/java/com/thealgorithms/others/Dijkstra.java @@ -4,6 +4,7 @@ import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; + /** * Dijkstra's algorithm,is a graph search algorithm that solves the * single-source shortest path problem for a graph with nonnegative edge path @@ -205,7 +206,7 @@ private void dijkstra(final NavigableSet q) { u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) { break; // we can ignore u (and any other remaining vertices) since they are - // unreachable + // unreachable } // look at distances to each neighbour for (Map.Entry a : u.neighbours.entrySet()) { diff --git a/src/main/java/com/thealgorithms/others/FibbonaciSeries.java b/src/main/java/com/thealgorithms/others/FibbonaciSeries.java index a4815296e547..7feb830a98df 100644 --- a/src/main/java/com/thealgorithms/others/FibbonaciSeries.java +++ b/src/main/java/com/thealgorithms/others/FibbonaciSeries.java @@ -11,7 +11,7 @@ * *

    * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number - * + *

    * Problem Statement: print all Fibonacci numbers that are smaller than your * given input N */ diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index 46b8edb1f177..4d313dd18658 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -77,8 +77,8 @@ public static void main(String[] args) { * increases exponentially. * * @param initialVectors The vectors composing the shape to which the - * algorithm is applied. - * @param steps The number of iterations. + * algorithm is applied. + * @param steps The number of iterations. * @return The transformed vectors after the iteration-steps. */ public static ArrayList iterate(ArrayList initialVectors, int steps) { @@ -94,7 +94,7 @@ public static ArrayList iterate(ArrayList initialVectors, int * Method to render the Koch snowflake to a image. * * @param imageWidth The width of the rendered image. - * @param steps The number of iterations. + * @param steps The number of iterations. * @return The image of the rendered Koch snowflake. */ public static BufferedImage getKochSnowflake(int imageWidth, int steps) { @@ -123,7 +123,7 @@ public static BufferedImage getKochSnowflake(int imageWidth, int steps) { * constructed through a 60 degree rotation so it is bent outwards. * * @param vectors The vectors composing the shape to which the algorithm is - * applied. + * applied. * @return The transformed vectors after the iteration-step. */ private static ArrayList iterationStep(List vectors) { @@ -145,8 +145,8 @@ private static ArrayList iterationStep(List vectors) { /** * Utility-method to render the Koch snowflake to an image. * - * @param vectors The vectors defining the edges to be rendered. - * @param imageWidth The width of the rendered image. + * @param vectors The vectors defining the edges to be rendered. + * @param imageWidth The width of the rendered image. * @param imageHeight The height of the rendered image. * @return The image of the rendered edges. */ diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java index b7db964c98d0..412bc289960d 100644 --- a/src/main/java/com/thealgorithms/others/LineSweep.java +++ b/src/main/java/com/thealgorithms/others/LineSweep.java @@ -7,10 +7,10 @@ * The Line Sweep algorithm is used to solve range problems efficiently. It works by: * 1. Sorting a list of ranges by their start values in non-decreasing order. * 2. Sweeping through the number line (x-axis) while updating a count for each point based on the ranges. - * + *

    * An overlapping range is defined as: * - (StartA <= EndB) AND (EndA >= StartB) - * + *

    * References: * - https://en.wikipedia.org/wiki/Sweep_line_algorithm * - https://en.wikipedia.org/wiki/De_Morgan%27s_laws diff --git a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java index 36bcca3edc00..d1aaae01a3ae 100644 --- a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java +++ b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java @@ -21,8 +21,8 @@ public class LinearCongruentialGenerator { * * @param multiplier * @param increment - * @param modulo The maximum number that can be generated (exclusive). A - * common value is 2^32. + * @param modulo The maximum number that can be generated (exclusive). A + * common value is 2^32. */ public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { this(System.currentTimeMillis(), multiplier, increment, modulo); @@ -35,8 +35,8 @@ public LinearCongruentialGenerator(double multiplier, double increment, double m * @param seed * @param multiplier * @param increment - * @param modulo The maximum number that can be generated (exclusive). A - * common value is 2^32. + * @param modulo The maximum number that can be generated (exclusive). A + * common value is 2^32. */ public LinearCongruentialGenerator(double seed, double multiplier, double increment, double modulo) { this.previousValue = seed; diff --git a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java index 76d1ed4aba1d..8091dcc1f12f 100644 --- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java +++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java @@ -5,7 +5,7 @@ /** * @brief Class for finding the lowest base in which a given integer is a palindrome. - cf. https://oeis.org/A016026 + * cf. https://oeis.org/A016026 */ public final class LowestBasePalindrome { private LowestBasePalindrome() { @@ -39,9 +39,9 @@ private static void checkNumber(int number) { * Computes the digits of a given number in a specified base. * * @param number the number to be converted - * @param base the base to be used for the conversion + * @param base the base to be used for the conversion * @return a list of digits representing the number in the given base, with the most - * significant digit at the end of the list + * significant digit at the end of the list * @throws IllegalArgumentException if the number is negative or the base is less than 2 */ public static List computeDigitsInBase(int number, int base) { @@ -76,7 +76,7 @@ public static boolean isPalindromic(List list) { * Checks if the representation of a given number in a specified base is palindromic. * * @param number the number to be checked - * @param base the base in which the number will be represented + * @param base the base in which the number will be represented * @return {@code true} if the number is palindromic in the specified base, {@code false} otherwise * @throws IllegalArgumentException if the number is negative or the base is less than 2 */ diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 600128a7725b..9c1012f07719 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -71,7 +71,7 @@ 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 + // symbol checkAndPrint(validInput); checkAndPrint(invalidInput); @@ -94,6 +94,7 @@ private static void checkAndPrint(int[] input) { Business usage example ======================== */ + /** * Object representation of credit card. */ @@ -102,10 +103,10 @@ private record CreditCard(int[] digits) { /** * @param cardNumber string representation of credit card number - 16 - * digits. Can have spaces for digits separation + * digits. Can have spaces for digits separation * @return credit card object * @throws IllegalArgumentException if input string is not 16 digits or - * if Luhn check was failed + * if Luhn check was failed */ public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 6d7588090ba8..ac94555fe373 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -63,12 +63,12 @@ public static void main(String[] args) { * area of the Mandelbrot set is roughly between "-1.5 < x < 0.5" and "-1 < * y < 1" in the figure-coordinates. * - * @param imageWidth The width of the rendered image. - * @param imageHeight The height of the rendered image. - * @param figureCenterX The x-coordinate of the center of the figure. - * @param figureCenterY The y-coordinate of the center of the figure. - * @param figureWidth The width of the figure. - * @param maxStep Maximum number of steps to check for divergent behavior. + * @param imageWidth The width of the rendered image. + * @param imageHeight The height of the rendered image. + * @param figureCenterX The x-coordinate of the center of the figure. + * @param figureCenterY The y-coordinate of the center of the figure. + * @param figureWidth The width of the figure. + * @param maxStep Maximum number of steps to check for divergent behavior. * @param useDistanceColorCoding Render in color or black and white. * @return The image of the rendered Mandelbrot set. */ diff --git a/src/main/java/com/thealgorithms/others/MaximumSlidingWindow.java b/src/main/java/com/thealgorithms/others/MaximumSlidingWindow.java index d0b2c2a0e56d..aac9fcdeca7a 100644 --- a/src/main/java/com/thealgorithms/others/MaximumSlidingWindow.java +++ b/src/main/java/com/thealgorithms/others/MaximumSlidingWindow.java @@ -5,11 +5,11 @@ /** * Maximum Sliding Window Algorithm - * + *

    * This algorithm finds the maximum element in each sliding window of size k * in a given array of integers. It uses a deque (double-ended queue) to * efficiently keep track of potential maximum values in the current window. - * + *

    * Time Complexity: O(n), where n is the number of elements in the input array * Space Complexity: O(k), where k is the size of the sliding window */ @@ -19,7 +19,7 @@ public class MaximumSlidingWindow { /** * Finds the maximum values in each sliding window of size k. * - * @param nums The input array of integers + * @param nums The input array of integers * @param windowSize The size of the sliding window * @return An array of integers representing the maximums in each window */ diff --git a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java index c05f1af4e327..9e3aa212e6bb 100644 --- a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java +++ b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java @@ -5,7 +5,7 @@ /** * References: https://en.wikipedia.org/wiki/Streaming_algorithm - * + *

    * This model involves computing the maximum sum of subarrays of a fixed size \( K \) from a stream of integers. * As the stream progresses, elements from the end of the window are removed, and new elements from the stream are added. * @@ -18,9 +18,8 @@ private MaximumSumOfDistinctSubarraysWithLengthK() { /** * Finds the maximum sum of a subarray of size K consisting of distinct elements. * - * @param k The size of the subarray. + * @param k The size of the subarray. * @param nums The array from which subarrays will be considered. - * * @return The maximum sum of any distinct-element subarray of size K. If no such subarray exists, returns 0. */ public static long maximumSubarraySum(int k, int... nums) { diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index 0924b8569942..53517a69507a 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -1,6 +1,7 @@ package com.thealgorithms.others; import java.util.ArrayList; + /** * @author Alexandros Lemonaris */ @@ -12,10 +13,11 @@ public abstract class MemoryManagementAlgorithms { * Abstract method since it is implemented different for each algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). - * @param sizeOfBlocks an int array that contains the sizes of the memory - * blocks available. + * + * @param sizeOfBlocks an int array that contains the sizes of the memory + * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the - * processes we need memory blocks for. + * processes we need memory blocks for. * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ @@ -61,7 +63,7 @@ private static int findMaxElement(int[] array) { * Method to find the index of the memory block that is going to fit the * given process based on the best fit algorithm. * - * @param blocks: the array with the available memory blocks. + * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. @@ -71,7 +73,7 @@ private static int findBestFit(int[] blockSizes, int processSize) { // processSize. int minDiff = findMaxElement(blockSizes); int index = NO_ALLOCATION; // If there is no block that can fit the process, return - // NO_ALLOCATION as the + // 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) { @@ -87,10 +89,10 @@ private static int findBestFit(int[] blockSizes, int processSize) { * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * - * @param sizeOfBlocks: an int array that contains the sizes of the memory - * blocks available. + * @param sizeOfBlocks: an int array that contains the sizes of the memory + * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the - * processes we need memory blocks for. + * processes we need memory blocks for. * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ @@ -119,7 +121,7 @@ class WorstFitCPU extends MemoryManagementAlgorithms { * Method to find the index of the memory block that is going to fit the * given process based on the worst fit algorithm. * - * @param blocks: the array with the available memory blocks. + * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. @@ -145,10 +147,10 @@ private static int findWorstFit(int[] blockSizes, int processSize) { * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * - * @param sizeOfBlocks: an int array that contains the sizes of the memory - * blocks available. + * @param sizeOfBlocks: an int array that contains the sizes of the memory + * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the - * processes we need memory blocks for. + * processes we need memory blocks for. * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ @@ -177,7 +179,7 @@ class FirstFitCPU extends MemoryManagementAlgorithms { * Method to find the index of the memory block that is going to fit the * given process based on the first fit algorithm. * - * @param blocks: the array with the available memory blocks. + * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. @@ -197,10 +199,10 @@ private static int findFirstFit(int[] blockSizes, int processSize) { * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * - * @param sizeOfBlocks: an int array that contains the sizes of the memory - * blocks available. + * @param sizeOfBlocks: an int array that contains the sizes of the memory + * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the - * processes we need memory blocks for. + * processes we need memory blocks for. * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ @@ -233,7 +235,7 @@ class NextFit extends MemoryManagementAlgorithms { * if the search is interrupted in between, the new search is carried out from the last * location. * - * @param blocks: the array with the available memory blocks. + * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. @@ -258,10 +260,10 @@ private int findNextFit(int[] blockSizes, int processSize) { * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * - * @param sizeOfBlocks: an int array that contains the sizes of the memory - * blocks available. + * @param sizeOfBlocks: an int array that contains the sizes of the memory + * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the - * processes we need memory blocks for. + * processes we need memory blocks for. * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index cd2cd02ab908..49baf34550f3 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -6,7 +6,7 @@ /** * MiniMax is an algorithm used int artificial intelligence and game theory for * minimizing the possible loss for the worst case scenario. - * + *

    * See more (https://en.wikipedia.org/wiki/Minimax, * https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/). * @@ -48,10 +48,10 @@ public static void main(String[] args) { /** * Returns the optimal score assuming that both players play their best. * - * @param depth Indicates how deep we are into the game tree. + * @param depth Indicates how deep we are into the game tree. * @param isMaximizer True if it is maximizers turn; otherwise false. - * @param index Index of the leaf node that is being evaluated. - * @param verbose True to show each players choices. + * @param index Index of the leaf node that is being evaluated. + * @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) { @@ -89,7 +89,7 @@ public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { /** * Returns an array of random numbers which lenght is a power of 2. * - * @param size The power of 2 that will determine the lenght of the array. + * @param size The power of 2 that will determine the lenght of the array. * @param maxScore The maximum possible score. * @return An array of random numbers. */ diff --git a/src/main/java/com/thealgorithms/others/PerlinNoise.java b/src/main/java/com/thealgorithms/others/PerlinNoise.java index e6551ed6b9ee..1b255c8418e5 100644 --- a/src/main/java/com/thealgorithms/others/PerlinNoise.java +++ b/src/main/java/com/thealgorithms/others/PerlinNoise.java @@ -12,11 +12,11 @@ private PerlinNoise() { } /** - * @param width width of noise array - * @param height height of noise array + * @param width width of noise array + * @param height height of noise array * @param octaveCount numbers of layers used for blending noise * @param persistence value of impact each layer get while blending - * @param seed used for randomizer + * @param seed used for randomizer * @return float array containing calculated "Perlin-Noise" values */ static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) { @@ -65,8 +65,8 @@ static float[][] generatePerlinNoise(int width, int height, int octaveCount, flo } /** - * @param base base random float array - * @param width width of noise array + * @param base base random float array + * @param width width of noise array * @param height height of noise array * @param octave current layer * @return float array containing calculated "Perlin-Noise-Layer" values @@ -105,10 +105,10 @@ static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, } /** - * @param a value of point a - * @param b value of point b + * @param a value of point a + * @param b value of point b * @param alpha determine which value has more impact (closer to 0 -> a, - * closer to 1 -> b) + * closer to 1 -> b) * @return interpolated value */ static float interpolate(float a, float b, float alpha) { diff --git a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java index de36673512a0..76155228bfc5 100644 --- a/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java +++ b/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java @@ -29,8 +29,8 @@ public static void reverse(Stack stack) { /** * Inserts an element at the bottom of the given stack. * - * @param stack the stack where the element will be inserted - * @param element the element to be inserted at the bottom + * @param stack the stack where the element will be inserted + * @param element the element to be inserted at the bottom */ private static void insertAtBottom(Stack stack, int element) { if (stack.isEmpty()) { diff --git a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java index 6ad0ef024342..2c71163ab1dc 100644 --- a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java +++ b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java @@ -1,6 +1,7 @@ package com.thealgorithms.others; import java.util.Scanner; + /** * Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here * is the algorithm for this problem . diff --git a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java index 7017ed03f843..3ffa9fb98d68 100644 --- a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java +++ b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java @@ -8,7 +8,7 @@ * 1. Only one disc can be moved at a time. * 2. A disc can only be placed on top of a larger disc. * 3. All discs must start on one pole and end on another. - * + *

    * This implementation recursively calculates the steps required to solve the puzzle and stores them * in a provided list. * @@ -16,7 +16,7 @@ * For more information about the Tower of Hanoi, see * Tower of Hanoi on Wikipedia. *

    - * + *

    * The {@code shift} method takes the number of discs and the names of the poles, * and appends the steps required to solve the puzzle to the provided list. * Time Complexity: O(2^n) - Exponential time complexity due to the recursive nature of the problem. diff --git a/src/main/java/com/thealgorithms/others/Verhoeff.java b/src/main/java/com/thealgorithms/others/Verhoeff.java index 9088612aaa43..7687fd0b6c9d 100644 --- a/src/main/java/com/thealgorithms/others/Verhoeff.java +++ b/src/main/java/com/thealgorithms/others/Verhoeff.java @@ -89,8 +89,8 @@ private Verhoeff() { * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only - * digits - * @throws NullPointerException if input is null + * digits + * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); @@ -114,8 +114,8 @@ public static boolean verhoeffCheck(String digits) { * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only - * digits - * @throws NullPointerException if input is null + * digits + * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); diff --git a/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java b/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java index 1e5512be9edd..0241146f9694 100644 --- a/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java @@ -7,7 +7,7 @@ * AgingScheduling is an algorithm designed to prevent starvation * by gradually increasing the priority of waiting tasks. * The longer a process waits, the higher its priority becomes. - * + *

    * Use Case: Useful in systems with mixed workloads to avoid * lower-priority tasks being starved by higher-priority tasks. * @@ -36,7 +36,7 @@ public AgingScheduling() { /** * Adds a task to the scheduler with a given priority. * - * @param name name of the task + * @param name name of the task * @param priority priority of the task */ public void addTask(String name, int priority) { diff --git a/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java b/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java index 776fc59c0c4d..5c8c718685f3 100644 --- a/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java @@ -7,7 +7,7 @@ * FairShareScheduling allocates CPU resources equally among users or groups * instead of individual tasks. Each group gets a proportional share, * preventing resource hogging by a single user's processes. - * + *

    * Use Case: Multi-user systems where users submit multiple tasks simultaneously, * such as cloud environments. * diff --git a/src/main/java/com/thealgorithms/scheduling/GangScheduling.java b/src/main/java/com/thealgorithms/scheduling/GangScheduling.java index ac1ce8ddd6ae..b76b5b976623 100644 --- a/src/main/java/com/thealgorithms/scheduling/GangScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/GangScheduling.java @@ -8,7 +8,7 @@ /** * GangScheduling groups related tasks (gangs) to run simultaneously on multiple processors. * All tasks in a gang are executed together or not at all. - * + *

    * Use Case: Parallel computing environments where multiple threads of a program * need to run concurrently for optimal performance. * diff --git a/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java b/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java index 8ed689698557..281bb33702ba 100644 --- a/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java @@ -13,7 +13,7 @@ *

      *     Response Ratio = (waiting time + burst time) / burst time
      * 
    - * + *

    * HRRN is designed to reduce the average waiting time and improve overall * system performance by balancing between short and long processes, * minimizing process starvation. @@ -62,9 +62,9 @@ private static class Process { * in the system from arrival to completion. It is the sum of the burst time * and the waiting time.

    * - * @param processNames Array of process names. - * @param arrivalTimes Array of arrival times corresponding to each process. - * @param burstTimes Array of burst times for each process. + * @param processNames Array of process names. + * @param arrivalTimes Array of arrival times corresponding to each process. + * @param burstTimes Array of burst times for each process. * @param noOfProcesses The number of processes. * @return An array of Turn Around Times for each process. */ @@ -106,7 +106,7 @@ public static int[] calculateTurnAroundTime(final String[] processNames, final i * Calculates the Waiting Time (WT) for each process. * * @param turnAroundTime The Turn Around Times for each process. - * @param burstTimes The burst times for each process. + * @param burstTimes The burst times for each process. * @return An array of Waiting Times for each process. */ public static int[] calculateWaitingTime(int[] turnAroundTime, int[] burstTimes) { @@ -120,7 +120,7 @@ public static int[] calculateWaitingTime(int[] turnAroundTime, int[] burstTimes) /** * Finds the next process to be scheduled based on arrival times and the current time. * - * @param processes Array of Process objects. + * @param processes Array of Process objects. * @param currentTime The current time in the scheduling process. * @return The index of the next process to be scheduled, or PROCESS_NOT_FOUND if no process is ready. */ @@ -135,7 +135,7 @@ private static int findNextProcess(Process[] processes, int currentTime) { * (waiting time + burst time) / burst time * where waiting time = current time - arrival time

    * - * @param processes Array of Process objects. + * @param processes Array of Process objects. * @param currentTime The current time in the scheduling process. * @return The index of the process with the highest response ratio, or PROCESS_NOT_FOUND if no process is ready. */ diff --git a/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java b/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java index 49638d39fc2a..603399e2ce1b 100644 --- a/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java +++ b/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java @@ -6,7 +6,7 @@ /** * A class that implements a job scheduling algorithm to maximize profit * while adhering to job deadlines and arrival times. - * + *

    * This class provides functionality to schedule jobs based on their profit, * arrival time, and deadlines to ensure that the maximum number of jobs is completed * within the given timeframe. It sorts the jobs in decreasing order of profit @@ -18,7 +18,7 @@ private JobSchedulingWithDeadline() { /** * Represents a job with an ID, arrival time, deadline, and profit. - * + *

    * Each job has a unique identifier, an arrival time (when it becomes available for scheduling), * a deadline by which it must be completed, and a profit associated with completing the job. */ @@ -31,10 +31,10 @@ static class Job { /** * Constructs a Job instance with the specified job ID, arrival time, deadline, and profit. * - * @param jobId Unique identifier for the job + * @param jobId Unique identifier for the job * @param arrivalTime Time when the job becomes available for scheduling - * @param deadline Deadline for completing the job - * @param profit Profit earned upon completing the job + * @param deadline Deadline for completing the job + * @param profit Profit earned upon completing the job */ Job(int jobId, int arrivalTime, int deadline, int profit) { this.jobId = jobId; @@ -46,7 +46,7 @@ static class Job { /** * Schedules jobs to maximize profit while respecting their deadlines and arrival times. - * + *

    * This method sorts the jobs in descending order of profit and attempts * to allocate them to time slots that are before or on their deadlines, * provided they have arrived. The function returns an array where the first element @@ -55,8 +55,8 @@ static class Job { * @param jobs An array of Job objects, each representing a job with an ID, arrival time, * deadline, and profit. * @return An array of two integers: the first element is the count of jobs - * that were successfully scheduled, and the second element is the - * total profit earned from those jobs. + * that were successfully scheduled, and the second element is the + * total profit earned from those jobs. */ public static int[] jobSequencingWithDeadlines(Job[] jobs) { Arrays.sort(jobs, Comparator.comparingInt(job -> - job.profit)); diff --git a/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java b/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java index 113b1691dec1..5a19690bc908 100644 --- a/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java @@ -9,7 +9,7 @@ * MultiAgentScheduling assigns tasks to different autonomous agents * who independently decide the execution order of their assigned tasks. * The focus is on collaboration between agents to optimize the overall schedule. - * + *

    * Use Case: Distributed scheduling in decentralized systems like IoT networks. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java b/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java index 1d8e2c5160ff..46caf24191ce 100644 --- a/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java @@ -48,7 +48,7 @@ static class Process implements Comparable { * * @param other The other process to compare against * @return A negative integer, zero, or a positive integer as this process - * is less than, equal to, or greater than the specified process. + * is less than, equal to, or greater than the specified process. */ @Override public int compareTo(Process other) { diff --git a/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java b/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java index fd78dc571819..5ac769923c31 100644 --- a/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java @@ -7,7 +7,7 @@ * ProportionalFairScheduling allocates resources to processes based on their * proportional weight or importance. It aims to balance fairness with * priority, ensuring that higher-weight processes receive a larger share of resources. - * + *

    * Use Case: Network bandwidth allocation in cellular networks (4G/5G), * where devices receive a proportional share of bandwidth. * diff --git a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java index 6d105003e68f..1d2f6de5c7b2 100644 --- a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java @@ -16,14 +16,16 @@ public class SJFScheduling { /** * a simple constructor + * * @param processes a list of processes the user wants to schedule - * it also sorts the processes based on the time of their arrival + * it also sorts the processes based on the time of their arrival */ SJFScheduling(final ArrayList processes) { this.processes = processes; schedule = new ArrayList<>(); sortByArrivalTime(); } + protected void sortByArrivalTime() { int size = processes.size(); int i; @@ -84,9 +86,10 @@ public void scheduleProcesses() { /** * this function evaluates the shortest job of all the ready processes (based on a process * burst time) + * * @param readyProcesses an array list of ready processes * @return returns the process' with the shortest burst time OR NULL if there are no ready - * processes + * processes */ private ProcessDetails findShortestJob(List readyProcesses) { if (readyProcesses.isEmpty()) { diff --git a/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java b/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java index 99214fff20c4..ee05a3851123 100644 --- a/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java @@ -22,6 +22,7 @@ public class SRTFScheduling { /** * Constructor + * * @param processes ArrayList of ProcessDetails given as input */ public SRTFScheduling(ArrayList processes) { diff --git a/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java b/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java index 15159a07d2d4..1885041c7150 100644 --- a/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java @@ -7,7 +7,7 @@ * their priority based on real-time feedback, such as wait time and CPU usage. * Tasks that wait longer will automatically increase their priority, * allowing for better responsiveness and fairness in task handling. - * + *

    * Use Case: Real-time systems that require dynamic prioritization * of tasks to maintain system responsiveness and fairness. * diff --git a/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java b/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java index bbfd36f0f660..273cf45e4780 100644 --- a/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java @@ -8,7 +8,7 @@ * SlackTimeScheduling is an algorithm that prioritizes tasks based on their * slack time, which is defined as the difference between the task's deadline * and the time required to execute it. Tasks with less slack time are prioritized. - * + *

    * Use Case: Real-time systems with hard deadlines, such as robotics or embedded systems. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java index beba69b05eca..9e074e06e508 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java @@ -15,6 +15,7 @@ public class LookScheduling { private final int currentPosition; private boolean movingUp; private int farthestPosition; + public LookScheduling(int startPosition, boolean initialDirection, int maxTrack) { this.currentPosition = startPosition; this.movingUp = initialDirection; diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java index 261c1a388393..727606c9100c 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java @@ -5,16 +5,16 @@ import java.util.List; /** - *https://en.wikipedia.org/wiki/Shortest_seek_first + * https://en.wikipedia.org/wiki/Shortest_seek_first * Shortest Seek First (SFF) Scheduling algorithm implementation. * The SFF algorithm selects the next request to be serviced based on the shortest distance * from the current position of the disk arm. It continuously evaluates all pending requests * and chooses the one that requires the least amount of movement to service. - * + *

    * This approach minimizes the average seek time, making it efficient in terms of response * time for individual requests. However, it may lead to starvation for requests located * further away from the current position of the disk arm. - * + *

    * The SFF algorithm is particularly effective in systems where quick response time * is crucial, as it ensures that the most accessible requests are prioritized for servicing. */ diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java index 2c4fa7844a12..c32708910930 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java @@ -10,11 +10,11 @@ * The SCAN algorithm moves the disk arm towards one end of the disk, servicing all requests * along the way until it reaches the end. Once it reaches the end, it reverses direction * and services the requests on its way back. - * + *

    * This algorithm ensures that all requests are serviced in a fair manner, * while minimizing the seek time for requests located close to the current position * of the disk arm. - * + *

    * The SCAN algorithm is particularly useful in environments with a large number of * disk requests, as it reduces the overall movement of the disk arm compared to */ diff --git a/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java b/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java index aeddc591b32b..240059227749 100644 --- a/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java +++ b/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java @@ -10,6 +10,7 @@ * Inverted Index implementation with BM25 Scoring for movie search. * This class supports adding movie documents and searching for terms * within those documents using the BM25 algorithm. + * * @author Prayas Kumar (https://github.com/prayas7102) */ @@ -22,11 +23,12 @@ class Movie { /** * Constructor for the Movie class. - * @param docId Unique identifier for the movie. - * @param name Name of the movie. - * @param imdbRating IMDb rating of the movie. + * + * @param docId Unique identifier for the movie. + * @param name Name of the movie. + * @param imdbRating IMDb rating of the movie. * @param releaseYear Release year of the movie. - * @param content Content or description of the movie. + * @param content Content or description of the movie. */ Movie(int docId, String name, double imdbRating, int releaseYear, String content) { this.docId = docId; @@ -39,6 +41,7 @@ class Movie { /** * Get all the words from the movie's name and content. * Converts the name and content to lowercase and splits on non-word characters. + * * @return Array of words from the movie name and content. */ public String[] getWords() { @@ -58,7 +61,8 @@ class SearchResult { /** * Constructor for SearchResult class. - * @param docId Document ID (movie) for this search result. + * + * @param docId Document ID (movie) for this search result. * @param relevanceScore The relevance score based on BM25 scoring. */ SearchResult(int docId, double relevanceScore) { @@ -119,11 +123,12 @@ public final class BM25InvertedIndex { /** * Add a movie to the index. - * @param docId Unique identifier for the movie. - * @param name Name of the movie. - * @param imdbRating IMDb rating of the movie. + * + * @param docId Unique identifier for the movie. + * @param name Name of the movie. + * @param imdbRating IMDb rating of the movie. * @param releaseYear Release year of the movie. - * @param content Content or description of the movie. + * @param content Content or description of the movie. */ public void addMovie(int docId, String name, double imdbRating, int releaseYear, String content) { Movie movie = new Movie(docId, name, imdbRating, releaseYear, content); @@ -159,6 +164,7 @@ public int getMoviesLength() { /** * Search for documents containing a term using BM25 scoring. + * * @param term The search term. * @return A list of search results sorted by relevance score. */ @@ -196,9 +202,10 @@ public List search(String term) { /** * Compute the BM25 score for a given term and document. + * * @param termFrequency The frequency of the term in the document. - * @param docLength The length of the document. - * @param idf The inverse document frequency of the term. + * @param docLength The length of the document. + * @param idf The inverse document frequency of the term. * @return The BM25 relevance score for the term in the document. */ private double computeBM25Score(int termFrequency, double docLength, double idf) { @@ -210,6 +217,7 @@ private double computeBM25Score(int termFrequency, double docLength, double idf) /** * Compute the inverse document frequency (IDF) of a term. * The IDF measures the importance of a term across the entire document set. + * * @param docFrequency The number of documents that contain the term. * @return The inverse document frequency (IDF) value. */ diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index bedad1667f33..64959b5dce06 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -19,12 +19,21 @@ class BinarySearch implements SearchAlgorithm { /** * @param array is an array where the element should be found - * @param key is an element which should be found - * @param is any comparable type + * @param key is an element which should be found + * @param is any comparable type * @return index of the element */ @Override public > int find(T[] array, T key) { + if (array == null) { + throw new NullPointerException("Input array cannot be null"); + } + if (key == null) { + throw new NullPointerException("Key cannot be null"); + } + if (array.length == 0) { + return -1; // Explicitly handle empty array + } return search(array, key, 0, array.length - 1); } @@ -32,8 +41,8 @@ public > int find(T[] array, T key) { * This method implements the Generic Binary Search * * @param array The array to make the binary search - * @param key The number you are looking for - * @param left The lower bound + * @param key The number you are looking for + * @param left The lower bound * @param right The upper bound * @return the location of the key */ diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index aa938447b864..b26d742b1ff4 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -6,7 +6,7 @@ * The search is performed using a combination of binary search on rows and * columns. * The 2D array must be strictly sorted in both rows and columns. - * + *

    * The algorithm works by: * 1. Performing a binary search on the middle column of the 2D array. * 2. Depending on the value found, it eliminates rows above or below the middle @@ -26,7 +26,7 @@ private BinarySearch2dArray() { * @param arr The 2D array to search in. * @param target The value to search for. * @return An array containing the row and column indices of the target, or [-1, - * -1] if the target is not found. + * -1] if the target is not found. */ static int[] binarySearch(int[][] arr, int target) { int rowCount = arr.length; @@ -101,7 +101,7 @@ else if (arr[midRow][midCol] < target) { * @param colStart The starting column index for the search. * @param colEnd The ending column index for the search. * @return An array containing the row and column indices of the target, or [-1, - * -1] if the target is not found. + * -1] if the target is not found. */ static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) { // Perform binary search within the specified column range. diff --git a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java index 7ac9c7b01526..c00915fe6f6e 100644 --- a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java @@ -11,6 +11,7 @@ /** * Breadth-First Search implementation for tree/graph traversal. + * * @author caos321 * @co-author @manishraj27 * @see Breadth-first search @@ -22,7 +23,7 @@ public class BreadthFirstSearch { /** * Performs a breadth-first search to find a node with the given value. * - * @param root The root node to start the search from + * @param root The root node to start the search from * @param value The value to search for * @return Optional containing the found node, or empty if not found */ diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java index 9187dcbc2f4b..f9ef6b73cff8 100644 --- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java +++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java @@ -25,8 +25,8 @@ class ExponentialSearch implements SearchAlgorithm { * Finds the index of the specified key in a sorted array using exponential search. * * @param array The sorted array to search. - * @param key The element to search for. - * @param The type of the elements in the array, which must be comparable. + * @param key The element to search for. + * @param The type of the elements in the array, which must be comparable. * @return The index of the key if found, otherwise -1. */ @Override diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index 2124938bc258..dfb5b31608a1 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -21,10 +21,10 @@ public class FibonacciSearch implements SearchAlgorithm { * Finds the index of the specified key in a sorted array using Fibonacci search. * * @param array The sorted array to search. - * @param key The element to search for. - * @param The type of the elements in the array, which must be comparable. - * @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null. + * @param key The element to search for. + * @param The type of the elements in the array, which must be comparable. * @return The index of the key if found, otherwise -1. + * @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null. */ @Override public > int find(T[] array, T key) { diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java index 3ac6be25bf53..1ac6c7f7e710 100644 --- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java +++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java @@ -24,7 +24,7 @@ class InterpolationSearch { * Finds the index of the specified key in a sorted array using interpolation search. * * @param array The sorted array to search. - * @param key The value to search for. + * @param key The value to search for. * @return The index of the key if found, otherwise -1. */ public int find(int[] array, int key) { diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java index 05fab0534267..94e3060dc161 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -24,7 +24,7 @@ public final class IterativeBinarySearch implements SearchAlgorithm { * This method implements an iterative version of binary search algorithm * * @param array a sorted array - * @param key the key to search in array + * @param key the key to search in array * @return the index of key in the array or -1 if not found */ @Override diff --git a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java index ba3cff915f5f..5998837768fa 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java @@ -37,10 +37,10 @@ class Searcher extends Thread { /** * Constructor to initialize the Searcher. * - * @param arr The array to search in - * @param left The starting index of the segment + * @param arr The array to search in + * @param left The starting index of the segment * @param right The ending index of the segment - * @param x The number to search for + * @param x The number to search for */ Searcher(int[] arr, int left, int right, int x) { this.arr = arr; diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index 5a1401edd3c2..37826f2b3504 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -24,8 +24,8 @@ class LowerBound implements SearchAlgorithm { /** * @param array is an array where the LowerBound value is to be found - * @param key is an element for which the LowerBound is to be found - * @param is any comparable type + * @param key is an element for which the LowerBound is to be found + * @param is any comparable type * @return index of the LowerBound element */ @Override @@ -37,8 +37,8 @@ public > int find(T[] array, T key) { * This method implements the Generic Binary Search * * @param array The array to make the binary search - * @param key The number you are looking for - * @param left The lower bound + * @param key The number you are looking for + * @param left The lower bound * @param right The upper bound * @return the location of the key */ diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index aa74398b708b..024acf28ed33 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -8,7 +8,7 @@ /** * Monte Carlo Tree Search (MCTS) is a heuristic search algorithm used in * decition taking problems especially games. - * + *

    * See more: https://en.wikipedia.org/wiki/Monte_Carlo_tree_search, * https://www.baeldung.com/java-monte-carlo-tree-search */ @@ -85,7 +85,7 @@ public void addChildNodes(Node node, int childCount) { /** * Uses UCT to find a promising child node to be explored. - * + *

    * UCT: Upper Confidence bounds applied to Trees. * * @param rootNode Root node of the tree. diff --git a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java index 495e2e41bc5b..444fb04b8a74 100644 --- a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java @@ -18,8 +18,8 @@ public class PerfectBinarySearch implements SearchAlgorithm { /** * @param array is an array where the element should be found - * @param key is an element which should be found - * @param is any comparable type + * @param key is an element which should be found + * @param is any comparable type * @return index of the element */ @Override diff --git a/src/main/java/com/thealgorithms/searches/RandomSearch.java b/src/main/java/com/thealgorithms/searches/RandomSearch.java index 3417ff7ddb21..119d887cdf19 100644 --- a/src/main/java/com/thealgorithms/searches/RandomSearch.java +++ b/src/main/java/com/thealgorithms/searches/RandomSearch.java @@ -24,7 +24,7 @@ public class RandomSearch implements SearchAlgorithm { * Finds the index of a given element using random search. * * @param array Array to search through - * @param key Element to search for + * @param key Element to search for * @return Index of the element if found, -1 otherwise */ @Override diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index 3b4b0b08377f..d71c5e6bc115 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -5,10 +5,10 @@ /** * The search is for any array which is sorted row and column-wise too. For ex : * {{10, 20, 30, 40}, - * {15, 25, 35, 45}, - * {18, 28, 38, 48}, - * {21, 31, 41, 51}} - * + * {15, 25, 35, 45}, + * {18, 28, 38, 48}, + * {21, 31, 41, 51}} + *

    * This array is sorted in both row and column manner. * In this two pointers are taken, the first points to the 0th row and the second one points to end * column, and then the element corresponding to the pointers placed in the array is compared with diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 192c4d26c735..7d2821825c8d 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -25,9 +25,9 @@ private SaddlebackSearch() { * @param row the current row. * @param col the current column. * @param key the element that we want to search for. - * @throws IllegalArgumentException if the array is empty. * @return The index(row and column) of the element if found. Else returns * -1 -1. + * @throws IllegalArgumentException if the array is empty. */ static int[] find(int[][] arr, int row, int col, int key) { if (arr.length == 0) { diff --git a/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java index 6a2a46c2821f..6397f3fec7f8 100644 --- a/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java @@ -1,7 +1,9 @@ package com.thealgorithms.searches; + public final class SortOrderAgnosticBinarySearch { private SortOrderAgnosticBinarySearch() { } + public static int find(int[] arr, int key) { int start = 0; int end = arr.length - 1; diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index 4d9f55ea9917..71691f574e26 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -20,7 +20,7 @@ public class TernarySearch implements SearchAlgorithm { /** - * @param arr The **Sorted** array in which we will search the element. + * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @@ -30,10 +30,10 @@ public > int find(T[] arr, T value) { } /** - * @param arr The **Sorted** array in which we will search the element. - * @param key The value that we want to search for. + * @param arr The **Sorted** array in which we will search the element. + * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. - * @param end The ending index till which we will Search. + * @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) { diff --git a/src/main/java/com/thealgorithms/searches/UnionFind.java b/src/main/java/com/thealgorithms/searches/UnionFind.java index 01202a982266..47bd607d08c9 100644 --- a/src/main/java/com/thealgorithms/searches/UnionFind.java +++ b/src/main/java/com/thealgorithms/searches/UnionFind.java @@ -8,10 +8,10 @@ * The Union-Find data structure, also known as Disjoint Set Union (DSU), * is a data structure that tracks a set of elements partitioned into * disjoint (non-overlapping) subsets. It supports two main operations: - * + *

    * 1. **Find**: Determine which subset a particular element is in. * 2. **Union**: Join two subsets into a single subset. - * + *

    * This implementation uses path compression in the `find` operation * and union by rank in the `union` operation for efficiency. */ diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java index ec52c7a0ae5c..04ce3b6fd7b9 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -24,8 +24,8 @@ class UpperBound implements SearchAlgorithm { /** * @param array is an array where the UpperBound value is to be found - * @param key is an element for which the UpperBound is to be found - * @param is any comparable type + * @param key is an element for which the UpperBound is to be found + * @param is any comparable type * @return index of the UpperBound element */ @Override @@ -37,8 +37,8 @@ public > int find(T[] array, T key) { * This method implements the Generic Binary Search * * @param array The array to make the binary search - * @param key The number you are looking for - * @param left The lower bound + * @param key The number you are looking for + * @param left The lower bound * @param right The upper bound * @return the location of the key */ diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/ConstrainedShuffle.java b/src/main/java/com/thealgorithms/shufflealogrithm/ConstrainedShuffle.java new file mode 100644 index 000000000000..7cb22c2ca468 --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/ConstrainedShuffle.java @@ -0,0 +1,44 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.Arrays; +import java.util.Random; + +public final class ConstrainedShuffle { + + private ConstrainedShuffle() { + // Prevent instantiation + } + + /** + * Shuffles elements in the array while ensuring that the first and last + * elements remain fixed. + * + * @param array the input array to shuffle + */ + public static void constrainedShuffle(int[] array) { + // Edge case: If the array has less than 3 elements, no shuffling can occur + if (array == null || array.length < 3) { + return; + } + + Random random = new Random(); + // Start loop from the second last element and exclude the first and last + // elements + for (int i = array.length - 2; i > 1; i--) { + // Generate a random index between 1 and i (inclusive) + int j = random.nextInt(i - 1) + 1; + + // Swap the elements at positions i and j + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + } + + public static void main(String[] args) { + int[] array = {1, 2, 3, 4, 5}; + System.out.println("Original Array: " + Arrays.toString(array)); + constrainedShuffle(array); + System.out.println("Constrained Shuffled Array: " + Arrays.toString(array)); + } +} diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/GroupShuffle.java b/src/main/java/com/thealgorithms/shufflealogrithm/GroupShuffle.java new file mode 100644 index 000000000000..b9062ff7254b --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/GroupShuffle.java @@ -0,0 +1,53 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class GroupShuffle { + + private GroupShuffle() { + // Prevent instantiation + } + + /** + * Groups and shuffles elements in the array. + * + * @param array the input array to shuffle + * @param groupSize the size of each group + * @return a list of shuffled groups + */ + public static List> groupShuffle(int[] array, int groupSize) { + List> groups = new ArrayList<>(); + + // Edge case: Check if the group size is valid + if (array == null || groupSize <= 0) { + return groups; + } + + for (int i = 0; i < array.length; i += groupSize) { + List group = new ArrayList<>(); + for (int j = i; j < Math.min(i + groupSize, array.length); j++) { + group.add(array[j]); + } + groups.add(group); + } + + // Shuffle only if the group size is greater than 1 + if (groupSize > 1) { + Collections.shuffle(groups); + } + + return groups; + } + + public static void main(String[] args) { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + List> shuffledGroups = groupShuffle(array, 3); + + System.out.println("Shuffled Groups:"); + for (List group : shuffledGroups) { + System.out.println(group); + } + } +} diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/ShuffleByRange.java b/src/main/java/com/thealgorithms/shufflealogrithm/ShuffleByRange.java new file mode 100644 index 000000000000..48ebf2480ed8 --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/ShuffleByRange.java @@ -0,0 +1,48 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.Random; + +public final class ShuffleByRange { + + private ShuffleByRange() { + // Prevent instantiation + } + + /** + * Shuffles elements in the specified range of the array. + * + * @param array the input array to shuffle + * @param start the starting index of the range (inclusive) + * @param end the ending index of the range (exclusive) + */ + public static void shuffleByRange(int[] array, int start, int end) { + // Edge case: Check if the range is valid + if (array == null || start < 0 || end > array.length || start >= end) { + return; + } + + Random random = new Random(); + for (int i = end - 1; i > start; i--) { + int j = random.nextInt(i - start + 1) + start; + + // Swap the elements at positions i and j + int temp = array[i]; // Temporarily store the element at i + array[i] = array[j]; // Move element from j to i + array[j] = temp; // Place the stored element in position j + } + } + + public static void main(String[] args) { + int[] array = {1, 2, 3, 4, 5, 6}; + System.out.println("Original Array: "); + for (int num : array) { + System.out.print(num + " "); + } + + shuffleByRange(array, 1, 5); + System.out.println("\nShuffled Array (Range 1 to 5): "); + for (int num : array) { + System.out.print(num + " "); + } + } +} diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/UnderstandingShuffleAlgo.java b/src/main/java/com/thealgorithms/shufflealogrithm/UnderstandingShuffleAlgo.java new file mode 100644 index 000000000000..9b6d6632828e --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/UnderstandingShuffleAlgo.java @@ -0,0 +1,59 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.Random; + +public final class UnderstandingShuffleAlgo { + + private UnderstandingShuffleAlgo() { + // Prevent instantiation + } + + /** + * Shuffles the elements in the array randomly. + * Uses a method that gives each item an equal chance to appear in any + * position. + * + * @param array the array to be shuffled + */ + public static void shuffle(int[] array) { + // Create a Random object to generate random numbers + Random random = new Random(); + + // Loop from the last element to the second element + for (int i = array.length - 1; i > 0; i--) { + // Generate a random index from 0 to i (inclusive) + int j = random.nextInt(i + 1); + + // Swap the elements at positions i and j + int temp = array[i]; // Temporarily store the element at i + array[i] = array[j]; // Move element from j to i + array[j] = temp; // Place the stored element in position j + } + } + + /** + * Main method to demonstrate the shuffle function. + * Shows the array before and after shuffling. + * + * @param args command-line arguments (not used here) + */ + public static void main(String[] args) { + // Create an example array of numbers from 1 to 9 + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + + // Display the original array + System.out.println("Original Array:"); + for (int num : array) { + System.out.print(num + " "); + } + + // Call the shuffle method to randomize the array + shuffle(array); + + // Display the shuffled array + System.out.println("\nShuffled Array:"); + for (int num : array) { + System.out.print(num + " "); + } + } +} diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/UniquePairShuffle.java b/src/main/java/com/thealgorithms/shufflealogrithm/UniquePairShuffle.java new file mode 100644 index 000000000000..b958cc9e8079 --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/UniquePairShuffle.java @@ -0,0 +1,55 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class UniquePairShuffle { + + private UniquePairShuffle() { + // Prevent instantiation + } + + /** + * Pairs each element in the array with another element randomly, ensuring no + * pair repeats. If the array length is odd, pairing cannot be completed, so + * an empty list is returned. + * + * @param array the input array to pair elements from + * @return a list of unique pairs where each pair is represented as an integer + * array of length 2 + */ + public static List pairShuffle(int[] array) { + List pairs = new ArrayList<>(); + + // Handle edge case: If the array length is odd, pairing is not possible + if (array.length < 2 || array.length % 2 != 0) { + return pairs; + } + + List shuffledList = new ArrayList<>(); + for (int num : array) { + shuffledList.add(num); + } + + // Shuffle elements to create random pairs + Collections.shuffle(shuffledList); + + // Form pairs from the shuffled elements + for (int i = 0; i < shuffledList.size(); i += 2) { + pairs.add(new int[] {shuffledList.get(i), shuffledList.get(i + 1)}); + } + + return pairs; + } + + public static void main(String[] args) { + int[] array = {1, 2, 3, 4}; + List pairs = pairShuffle(array); + + System.out.println("Generated Unique Pairs:"); + for (int[] pair : pairs) { + System.out.println(pair[0] + " - " + pair[1]); + } + } +} diff --git a/src/main/java/com/thealgorithms/shufflealogrithm/WeightedShuffle.java b/src/main/java/com/thealgorithms/shufflealogrithm/WeightedShuffle.java new file mode 100644 index 000000000000..acbb9c52bc29 --- /dev/null +++ b/src/main/java/com/thealgorithms/shufflealogrithm/WeightedShuffle.java @@ -0,0 +1,54 @@ +package com.thealgorithms.shufflealogrithm; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.Random; + +public final class WeightedShuffle { + + private WeightedShuffle() { + // Prevent instantiation + } + + /** + * Shuffles elements based on their weights. Higher weight elements are more + * likely to appear earlier. + * + * @param array the input array to shuffle + * @param weights the weights for each corresponding element in the array + */ + public static void weightedShuffle(int[] array, int[] weights) { + // Edge case: Check if weights match the array size + if (array == null || weights == null || array.length != weights.length) { + return; + } + + Integer[] indices = new Integer[array.length]; + for (int i = 0; i < array.length; i++) { + indices[i] = i; + } + + Random random = new Random(); + + // Sort indices by weights in descending order, prioritizing higher weights + Arrays.sort(indices, Comparator.comparingInt((Integer i) -> - weights[i]).thenComparingInt(i -> random.nextInt())); + + int[] result = new int[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[indices[i]]; + } + + System.arraycopy(result, 0, array, 0, array.length); + } + + public static void main(String[] args) { + int[] array = {10, 20, 30}; + int[] weights = {1, 3, 2}; + weightedShuffle(array, weights); + + System.out.println("Weighted Shuffled Array:"); + for (int num : array) { + System.out.print(num + " "); + } + } +} diff --git a/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java index 0641730d8b09..f5fd3797cd66 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java +++ b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java @@ -1,4 +1,5 @@ package com.thealgorithms.slidingwindow; + import java.util.HashSet; /** @@ -12,7 +13,7 @@ * Worst-case space complexity O(min(n, m)), where n is the length of the string * and m is the size of the character set. * - * @author (https://github.com/Chiefpatwal) + * @author (https : / / github.com / Chiefpatwal) */ public final class LongestSubstringWithoutRepeatingCharacters { diff --git a/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java b/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java index 40a5441fa7a0..f31ffb272d17 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java +++ b/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java @@ -1,4 +1,5 @@ package com.thealgorithms.slidingwindow; + /** * The Sliding Window algorithm is used to find the minimum sum of a subarray * of a fixed size k within a given array. @@ -8,7 +9,7 @@ * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) - * + *

    * This class provides a static method to find the minimum sum of a subarray * with a specified length k. * diff --git a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java index b6f5d92e7928..984553a986bc 100644 --- a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java @@ -10,7 +10,7 @@ public class BinaryInsertionSort implements SortAlgorithm { /** * Sorts the given array using the Binary Insertion Sort algorithm. * - * @param the type of elements in the array, which must implement the Comparable interface + * @param the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java index 90d204818729..d596652cda8c 100644 --- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java +++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java @@ -15,7 +15,7 @@ private enum Direction { /** * Sorts the given array using the Bitonic Sort algorithm. * - * @param the type of elements in the array, which must implement the Comparable interface + * @param the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ @@ -54,10 +54,10 @@ private > void bitonicSort(final T[] array, final int lo /** * Merges the bitonic sequence in the specified direction. * - * @param the type of elements in the array, which must be Comparable - * @param array the array containing the bitonic sequence to be merged - * @param low the starting index of the sequence to be merged - * @param cnt the number of elements in the sequence to be merged + * @param the type of elements in the array, which must be Comparable + * @param array the array containing the bitonic sequence to be merged + * @param low the starting index of the sequence to be merged + * @param cnt the number of elements in the sequence to be merged * @param direction the direction of sorting */ private > void bitonicMerge(T[] array, int low, int cnt, Direction direction) { @@ -101,7 +101,7 @@ private static int nextPowerOfTwo(int n) { /** * Finds the maximum element in the given array. * - * @param the type of elements in the array, which must implement the Comparable interface + * @param the type of elements in the array, which must implement the Comparable interface * @param array the array to be searched * @return the maximum element in the array * @throws IllegalArgumentException if the array is null or empty diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSort.java b/src/main/java/com/thealgorithms/sorts/BubbleSort.java index 6823c68d0a74..5fb85109581a 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSort.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSort.java @@ -11,7 +11,7 @@ class BubbleSort implements SortAlgorithm { * Implements generic bubble sort algorithm. * * @param array the array to be sorted. - * @param the type of elements in the array. + * @param the type of elements in the array. * @return the sorted array. */ @Override diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java index d9cc00f95b69..43787884f1b4 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java @@ -18,7 +18,7 @@ public > T[] sort(T[] array) { * BubbleSort algorithm implements using recursion * * @param array array contains elements - * @param len length of given array + * @param len length of given array */ private static > void bubbleSort(T[] array, int len) { boolean swapped = false; diff --git a/src/main/java/com/thealgorithms/sorts/BucketSort.java b/src/main/java/com/thealgorithms/sorts/BucketSort.java index 62c5e929593b..9fa8f7e3287a 100644 --- a/src/main/java/com/thealgorithms/sorts/BucketSort.java +++ b/src/main/java/com/thealgorithms/sorts/BucketSort.java @@ -43,7 +43,7 @@ private int calculateNumberOfBuckets(final int arrayLength) { * Initializes a list of empty buckets. * * @param numberOfBuckets the number of buckets to initialize - * @param the type of elements to be sorted + * @param the type of elements to be sorted * @return a list of empty buckets */ private > List> initializeBuckets(int numberOfBuckets) { @@ -57,12 +57,12 @@ private > List> initializeBuckets(int numberOfBu /** * Distributes elements from the array into the appropriate buckets. * - * @param array the array of elements to distribute - * @param buckets the list of buckets - * @param min the minimum value in the array - * @param max the maximum value in the array + * @param array the array of elements to distribute + * @param buckets the list of buckets + * @param min the minimum value in the array + * @param max the maximum value in the array * @param numberOfBuckets the total number of buckets - * @param the type of elements in the array + * @param the type of elements in the array */ private > void distributeElementsIntoBuckets(T[] array, List> buckets, final T min, final T max, final int numberOfBuckets) { for (final T element : array) { @@ -75,8 +75,8 @@ private > void distributeElementsIntoBuckets(T[] array, * Concatenates the sorted buckets back into the original array. * * @param buckets the list of sorted buckets - * @param array the original array - * @param the type of elements in the array + * @param array the original array + * @param the type of elements in the array * @return the sorted array */ private > T[] concatenateBuckets(Iterable> buckets, T[] array) { @@ -95,11 +95,11 @@ private > T[] concatenateBuckets(Iterable> bucke * This is done by "normalizing" the element within the range of the array's minimum (min) and maximum (max) values, * and then mapping this normalized value to a specific bucket index. * - * @param element the element of the array - * @param min the minimum value in the array - * @param max the maximum value in the array + * @param element the element of the array + * @param min the minimum value in the array + * @param max the maximum value in the array * @param numberOfBuckets the total number of buckets - * @param the type of elements in the array + * @param the type of elements in the array * @return the index of the bucket */ private > int hash(final T element, final T min, final T max, final int numberOfBuckets) { diff --git a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java index 600ae8d3efc9..d48e90c5fe0d 100644 --- a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java +++ b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java @@ -14,7 +14,7 @@ class CocktailShakerSort implements SortAlgorithm { /** * Sorts the given array using the Cocktail Shaker Sort algorithm. * - * @param The type of elements in the array, which must be comparable + * @param The type of elements in the array, which must be comparable * @param array The array to be sorted * @return The sorted array */ diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 5d54205032d4..3af55d1365b4 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -7,12 +7,11 @@ * This implementation has a time complexity of O(n + k), where n is the number * of elements in the input array and k is the range of the input. * It works only with integer arrays. - * + *

    * The space complexity is O(k), where k is the range of the input integers. - * + *

    * Note: This implementation handles negative integers as it * calculates the range based on the minimum and maximum values of the array. - * */ public final class CountingSort { private CountingSort() { diff --git a/src/main/java/com/thealgorithms/sorts/CycleSort.java b/src/main/java/com/thealgorithms/sorts/CycleSort.java index 4ef051419cbb..af1de355f70c 100644 --- a/src/main/java/com/thealgorithms/sorts/CycleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CycleSort.java @@ -3,6 +3,7 @@ /** * This class implements the cycle sort algorithm. * Cycle sort is an in-place sorting algorithm, unstable, and efficient for scenarios with limited memory usage. + * * @author Podshivalov Nikita (https://github.com/nikitap492) */ class CycleSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/FlashSort.java b/src/main/java/com/thealgorithms/sorts/FlashSort.java index e8dbf8c42742..69d7f7708032 100644 --- a/src/main/java/com/thealgorithms/sorts/FlashSort.java +++ b/src/main/java/com/thealgorithms/sorts/FlashSort.java @@ -2,7 +2,7 @@ /** * Implementation of Flash Sort algorithm that implements the SortAlgorithm interface. - * + *

    * Sorts an array using the Flash Sort algorithm. *

    * Flash Sort is a distribution sorting algorithm that partitions the data into @@ -49,7 +49,7 @@ public void setClassificationRatio(double classificationRatio) { * Sorts an array using the Flash Sort algorithm. * * @param array the array to be sorted. - * @param the type of elements to be sorted, must be comparable. + * @param the type of elements to be sorted, must be comparable. * @return the sorted array. */ @Override @@ -128,11 +128,11 @@ private > int findMaxIndex(final T[] arr) { /** * Classifies elements of the array into the classification array classificationArray. * - * @param arr the array to be classified. + * @param arr the array to be classified. * @param classificationArray the classification array holding the count of elements in each class. - * @param c1 the normalization constant used to map the elements to the classification array. - * @param min the minimum value in the array. - * @param the type of elements in the array, must be comparable. + * @param c1 the normalization constant used to map the elements to the classification array. + * @param min the minimum value in the array. + * @param the type of elements in the array, must be comparable. */ private > void classify(final T[] arr, final int[] classificationArray, final double c1, final T min) { for (int i = 0; i < arr.length; i++) { @@ -155,13 +155,13 @@ private void transform(final int[] classificationArray) { /** * Permutes the array into sorted order based on the classification array classificationArray. * - * @param arr the array to be permuted. + * @param arr the array to be permuted. * @param classificationArray the classification array holding the count of elements in each class. - * @param c1 the normalization constant used to map the elements to the classification array. - * @param min the minimum value in the array. - * @param n the length of the array. - * @param m the number of classes in the classification array. - * @param the type of elements in the array, must be comparable. + * @param c1 the normalization constant used to map the elements to the classification array. + * @param min the minimum value in the array. + * @param n the length of the array. + * @param m the number of classes in the classification array. + * @param the type of elements in the array, must be comparable. */ private > void permute(final T[] arr, final int[] classificationArray, final double c1, T min, int n, int m) { int move = 0; diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java index 800d78f36549..dba48667455a 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -1,6 +1,7 @@ package com.thealgorithms.sorts; import java.util.Arrays; + /** * @author Siddhant Swarup Mallick * Program description - To sort the LinkList as per sorting technique @@ -44,8 +45,8 @@ public static boolean isSorted(int[] p, int option) { // array b is sorted and it will return true when checked with sorted list LinkListSort uu = new LinkListSort(); return uu.compare(a, b); - // 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; Node prev1 = null; @@ -73,8 +74,8 @@ public static boolean isSorted(int[] p, int option) { LinkListSort uu1 = new LinkListSort(); // array b is not sorted and it will return false when checked with sorted list return uu1.compare(a, b); - // 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; @@ -103,8 +104,8 @@ public static boolean isSorted(int[] p, int option) { // array b is sorted and it will return true when checked with sorted list LinkListSort uu2 = new LinkListSort(); return uu2.compare(a, b); - // 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"); @@ -112,6 +113,7 @@ public static boolean isSorted(int[] p, int option) { // Switch case is used to call the classes as per the user requirement return false; } + /** * OUTPUT : * Input - {89,56,98,123,26,75,12,40,39,68,91} is same for all the 3 classes diff --git a/src/main/java/com/thealgorithms/sorts/MergeSort.java b/src/main/java/com/thealgorithms/sorts/MergeSort.java index 9949783ca21b..598b1fdd0c41 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSort.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSort.java @@ -15,7 +15,7 @@ class MergeSort implements SortAlgorithm { * Generic merge sort algorithm implements. * * @param unsorted the array which should be sorted. - * @param Comparable class. + * @param Comparable class. * @return sorted array. */ @Override @@ -26,8 +26,8 @@ public > T[] sort(T[] unsorted) { } /** - * @param arr the array to be sorted. - * @param left the first index of the array. + * @param arr the array to be sorted. + * @param left the first index of the array. * @param right the last index of the array. */ private > void doSort(T[] arr, int left, int right) { @@ -42,11 +42,11 @@ private > void doSort(T[] arr, int left, int right) { /** * Merges two parts of an array. * - * @param arr the array to be merged. - * @param left the first index of the array. - * @param mid the middle index of the array. + * @param arr the array to be merged. + * @param left the first index of the array. + * @param mid the middle index of the array. * @param right the last index of the array merges two parts of an array in - * increasing order. + * increasing order. */ @SuppressWarnings("unchecked") private > void merge(T[] arr, int left, int mid, int right) { diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java index 7aa3b56e068c..30ccba35edf6 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java @@ -33,9 +33,9 @@ public static int[] sort(int[] array) { /** * Recursively divides the array into two halves, sorts and merges them. * - * @param array the array to be sorted - * @param start the starting index of the array - * @param end the ending index of the array + * @param array the array to be sorted + * @param start the starting index of the array + * @param end the ending index of the array * @param maxElement the value greater than any element in the array, used for encoding */ public static void mergeSort(int[] array, int start, int end, int maxElement) { @@ -50,10 +50,10 @@ public static void mergeSort(int[] array, int start, int end, int maxElement) { /** * Merges two sorted subarrays [start...middle] and [middle+1...end] in place. * - * @param array the array containing the subarrays to be merged - * @param start the starting index of the first subarray - * @param middle the ending index of the first subarray and starting index of the second subarray - * @param end the ending index of the second subarray + * @param array the array containing the subarrays to be merged + * @param start the starting index of the first subarray + * @param middle the ending index of the first subarray and starting index of the second subarray + * @param end the ending index of the second subarray * @param maxElement the value greater than any element in the array, used for encoding */ private static void merge(int[] array, int start, int middle, int end, int maxElement) { diff --git a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java index ac94982c1474..779242ecba24 100644 --- a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java +++ b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java @@ -5,14 +5,13 @@ * Odd-even sort is a comparison sort related to bubble sort. * It operates by comparing all (odd, even)-indexed pairs of adjacent elements in the list and, if a pair is in the wrong order, swapping them. * The next step repeats this process for (even, odd)-indexed pairs. This process continues until the list is sorted. - * */ public final class OddEvenSort implements SortAlgorithm { /** * Sorts the given array using the Odd-Even Sort algorithm. * - * @param the type of elements in the array, which must implement the Comparable interface + * @param the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ diff --git a/src/main/java/com/thealgorithms/sorts/PancakeSort.java b/src/main/java/com/thealgorithms/sorts/PancakeSort.java index 6079672a1d77..2fb74d01dfaa 100644 --- a/src/main/java/com/thealgorithms/sorts/PancakeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PancakeSort.java @@ -25,9 +25,9 @@ public > T[] sort(T[] array) { /** * Finds the index of the maximum element in the array up to the given size. * - * @param array the array to be searched + * @param array the array to be searched * @param currentSize the current size of the unsorted portion of the array - * @param the type of elements in the array + * @param the type of elements in the array * @return the index of the maximum element */ private > int findMaxIndex(T[] array, int currentSize) { diff --git a/src/main/java/com/thealgorithms/sorts/PatienceSort.java b/src/main/java/com/thealgorithms/sorts/PatienceSort.java index 0edce8d9a15d..5608245dc143 100644 --- a/src/main/java/com/thealgorithms/sorts/PatienceSort.java +++ b/src/main/java/com/thealgorithms/sorts/PatienceSort.java @@ -15,7 +15,7 @@ public class PatienceSort implements SortAlgorithm { * Sorts an array of comparable elements using the Patience Sort algorithm. * * @param array the array to be sorted - * @param the type of elements in the array, must be comparable + * @param the type of elements in the array, must be comparable * @return the sorted array */ @Override @@ -37,7 +37,7 @@ public > T[] sort(T[] array) { * to find the appropriate pile for each element. * * @param array the array of elements to be organized into piles - * @param the type of elements in the array, must be comparable + * @param the type of elements in the array, must be comparable * @return a list of piles */ private static > List> formPiles(final T[] array) { @@ -69,7 +69,7 @@ private static > List> formPiles(final T[] array * prioritized. * * @param piles the list of piles to be merged - * @param the type of elements in the piles, must be comparable + * @param the type of elements in the piles, must be comparable * @return a priority queue containing the top element of each pile */ private static > PriorityQueue> mergePiles(final Iterable> piles) { @@ -84,8 +84,8 @@ private static > PriorityQueue> mergePiles(f * Extracts elements from the priority queue to form the sorted array. * * @param array the array to be filled with sorted elements - * @param pq the priority queue containing the elements to be extracted - * @param the type of elements in the array, must be comparable + * @param pq the priority queue containing the elements to be extracted + * @param the type of elements in the array, must be comparable */ private static > void extractPiles(final T[] array, final PriorityQueue> pq) { int index = 0; diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java index 19f4291d8213..184723823897 100644 --- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -12,8 +12,8 @@ private PigeonholeSort() { * Sorts the given array using the pigeonhole sort algorithm. * * @param array the array to be sorted - * @throws IllegalArgumentException if any negative integers are found * @return the sorted array + * @throws IllegalArgumentException if any negative integers are found */ public static int[] sort(int[] array) { @@ -63,7 +63,7 @@ private static List> createPigeonHoles(int maxElement) { /** * Populates the pigeonholes with elements from the array. * - * @param array the array to be sorted + * @param array the array to be sorted * @param pigeonHoles the pigeonholes to be populated */ private static void populatePigeonHoles(int[] array, List> pigeonHoles) { @@ -75,7 +75,7 @@ private static void populatePigeonHoles(int[] array, List> pigeonH /** * Collects sorted elements from the pigeonholes back into the array. * - * @param array the array to be sorted + * @param array the array to be sorted * @param pigeonHoles the populated pigeonholes */ private static void collectFromPigeonHoles(int[] array, Iterable> pigeonHoles) { diff --git a/src/main/java/com/thealgorithms/sorts/QuickSort.java b/src/main/java/com/thealgorithms/sorts/QuickSort.java index 3abb1aae2306..c115773f999b 100644 --- a/src/main/java/com/thealgorithms/sorts/QuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/QuickSort.java @@ -21,7 +21,7 @@ public > T[] sort(T[] array) { /** * The sorting process * - * @param left The first index of an array + * @param left The first index of an array * @param right The last index of an array * @param array The array to be sorted */ @@ -37,7 +37,7 @@ private static > void doSort(T[] array, final int left, * Randomize the array to avoid the basically ordered sequences * * @param array The array to be sorted - * @param left The first index of an array + * @param left The first index of an array * @param right The last index of an array * @return the partition index of the array */ @@ -51,9 +51,9 @@ private static > int randomPartition(T[] array, final in * This method finds the partition index for an array * * @param array The array to be sorted - * @param left The first index of an array + * @param left The first index of an array * @param right The last index of an array Finds the partition index of an - * array + * array */ private static > int partition(T[] array, int left, int right) { final int mid = (left + right) >>> 1; diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java index dbb2b88ffcef..7f1a6e55d218 100644 --- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java +++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java @@ -5,7 +5,7 @@ public class SelectionSort implements SortAlgorithm { * Sorts an array of comparable elements in increasing order using the selection sort algorithm. * * @param array the array to be sorted - * @param the class of array elements + * @param the class of array elements * @return the sorted array */ @Override diff --git a/src/main/java/com/thealgorithms/sorts/ShellSort.java b/src/main/java/com/thealgorithms/sorts/ShellSort.java index d12b181e65a2..16871360b7ae 100644 --- a/src/main/java/com/thealgorithms/sorts/ShellSort.java +++ b/src/main/java/com/thealgorithms/sorts/ShellSort.java @@ -6,7 +6,7 @@ public class ShellSort implements SortAlgorithm { * Implements generic shell sort. * * @param array the array to be sorted. - * @param the type of elements in the array. + * @param the type of elements in the array. * @return the sorted array. */ @Override @@ -53,8 +53,8 @@ private int calculateNextGap(final int currentGap) { * Performs an insertion sort for the specified gap value. * * @param array the array to be sorted. - * @param gap the current gap value. - * @param the type of elements in the array. + * @param gap the current gap value. + * @param the type of elements in the array. */ private > void performGapInsertionSort(final T[] array, final int gap) { for (int i = gap; i < array.length; i++) { diff --git a/src/main/java/com/thealgorithms/sorts/SpreadSort.java b/src/main/java/com/thealgorithms/sorts/SpreadSort.java index f1fd24f4735d..eac285481d1f 100644 --- a/src/main/java/com/thealgorithms/sorts/SpreadSort.java +++ b/src/main/java/com/thealgorithms/sorts/SpreadSort.java @@ -1,4 +1,5 @@ package com.thealgorithms.sorts; + import java.util.Arrays; /** diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 147d11340d8a..735dd0bfe585 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -12,7 +12,7 @@ public final class StrandSort implements SortAlgorithm { /** * Sorts the given array using the Strand Sort algorithm. * - * @param The type of elements to be sorted, must be Comparable. + * @param The type of elements to be sorted, must be Comparable. * @param array The array to be sorted. * @return The sorted array. */ @@ -26,7 +26,7 @@ public > T[] sort(T[] array) { /** * Strand Sort algorithm that sorts a list. * - * @param The type of elements to be sorted, must be Comparable. + * @param The type of elements to be sorted, must be Comparable. * @param list The list to be sorted. * @return The sorted list. */ @@ -54,8 +54,8 @@ private static > List strandSort(List list /** * Merges two sorted lists into one sorted list. * - * @param The type of elements to be sorted, must be Comparable. - * @param left The first sorted list. + * @param The type of elements to be sorted, must be Comparable. + * @param left The first sorted list. * @param right The second sorted list. * @return The merged sorted list. */ diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index e4ed240a9947..26bfe9fe3484 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -10,7 +10,7 @@ * The Topological Sorting algorithm linearly orders a DAG or Directed Acyclic Graph into * a linked list. A Directed Graph is proven to be acyclic when a DFS or Depth First Search is * performed, yielding no back-edges. - * + *

    * https://en.wikipedia.org/wiki/Topological_sorting * * @author Jonathan Taylor (https://github.com/Jtmonument) diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index 6f4e5509489d..e3840f936d3c 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -11,7 +11,7 @@ *

    * Tree Sort: A sorting algorithm which constructs a Binary Search Tree using * the unsorted data and then outputs the data by inorder traversal of the tree. - * + *

    * Reference: https://en.wikipedia.org/wiki/Tree_sort *

    * diff --git a/src/main/java/com/thealgorithms/sorts/WaveSort.java b/src/main/java/com/thealgorithms/sorts/WaveSort.java index 31aad52c6b4a..acae81c99c5f 100644 --- a/src/main/java/com/thealgorithms/sorts/WaveSort.java +++ b/src/main/java/com/thealgorithms/sorts/WaveSort.java @@ -9,7 +9,7 @@ public class WaveSort implements SortAlgorithm { * Sorts the given array such that every alternate element is greater than its adjacent elements. * * @param array The array to be sorted. - * @param The type of elements in the array, which must be Comparable. + * @param The type of elements in the array, which must be Comparable. * @return The sorted array. */ @Override @@ -29,7 +29,7 @@ public > T[] sort(T[] array) { * Checks if the given array is wave sorted. An array is wave sorted if every alternate element is greater than its adjacent elements. * * @param array The array to check. - * @param The type of elements in the array, which must be Comparable. + * @param The type of elements in the array, which must be Comparable. * @return true if the array is wave sorted, false otherwise. */ public > boolean isWaveSorted(T[] array) { diff --git a/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java index d3077ff54135..2df750eecc31 100644 --- a/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java +++ b/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java @@ -23,7 +23,7 @@ private BalancedBrackets() { /** * Check if {@code leftBracket} and {@code rightBracket} is paired or not * - * @param leftBracket left bracket + * @param leftBracket left bracket * @param rightBracket right bracket * @return {@code true} if {@code leftBracket} and {@code rightBracket} is * paired, otherwise {@code false} diff --git a/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java index ff6402c92695..c9d4a5e96dcf 100644 --- a/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java +++ b/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java @@ -10,7 +10,7 @@ private DecimalToAnyUsingStack() { * Convert a decimal number to another radix. * * @param number the number to be converted - * @param radix the radix + * @param radix the radix * @return the number represented in the new radix as a String * @throws IllegalArgumentException if number is negative or radix is not between 2 and 16 inclusive */ diff --git a/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java b/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java index be9d0099d38b..a02def38b06c 100644 --- a/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java +++ b/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java @@ -8,7 +8,7 @@ * The mainStack is used to store the all the elements of the stack * While the maxStack stores the maximum elements * When we want to get a maximum element, we call the top of the maximum stack - * + *

    * Problem: https://www.baeldung.com/cs/stack-constant-time */ public class GreatestElementConstantTime { @@ -27,6 +27,7 @@ public GreatestElementConstantTime() { * Pushes an element onto the top of the stack. * Checks if the element is the maximum or not * If so, then pushes to the maximum stack + * * @param data The element to be pushed onto the stack. */ public void push(int data) { diff --git a/src/main/java/com/thealgorithms/stacks/LargestRectangle.java b/src/main/java/com/thealgorithms/stacks/LargestRectangle.java index 006e03632e63..8fd8ae497ac4 100644 --- a/src/main/java/com/thealgorithms/stacks/LargestRectangle.java +++ b/src/main/java/com/thealgorithms/stacks/LargestRectangle.java @@ -3,7 +3,6 @@ import java.util.Stack; /** - * * @author mohd rameez github.com/rameez471 */ diff --git a/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java index d76122b16632..a56810975042 100644 --- a/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java +++ b/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java @@ -36,7 +36,7 @@ private MaximumMinimumWindow() { * window size using Stack Data Structure. * * @param arr Array containing the numbers - * @param n Length of the array + * @param n Length of the array * @return result array */ public static int[] calculateMaxOfMin(int[] arr, int n) { diff --git a/src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java b/src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java index f5e526b102cf..142a4af8e6fb 100644 --- a/src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java +++ b/src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java @@ -5,7 +5,7 @@ /** * Min-Stack implementation using a single stack. - * + *

    * This stack supports push, pop, and retrieving the minimum element * in constant time (O(1)) using a modified approach where the stack * stores both the element and the minimum value so far. diff --git a/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java b/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java index 98c439341a21..1a61da539db1 100644 --- a/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java +++ b/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java @@ -6,7 +6,7 @@ * A class that implements a palindrome checker using a stack. * The stack is used to store the characters of the string, * which we will pop one-by-one to create the string in reverse. - * + *

    * Reference: https://www.geeksforgeeks.org/check-whether-the-given-string-is-palindrome-using-stack/ */ public class PalindromeWithStack { diff --git a/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java b/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java index 02ef5af8da16..52ddefd75c26 100644 --- a/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java +++ b/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java @@ -58,8 +58,8 @@ private static boolean isOperator(String token) { * Applies the given operator to the two operands. * * @param operator The operator to apply. - * @param a The first operand. - * @param b The second operand. + * @param a The first operand. + * @param b The second operand. * @return The result of applying the operator to the operands. */ private static int applyOperator(String operator, int a, int b) { diff --git a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java index a8f98ac53e5d..a2a2908d25d4 100644 --- a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java @@ -4,16 +4,14 @@ /** * Postfix to Infix implementation via Stack - * + *

    * Function: String getPostfixToInfix(String postfix) * Returns the Infix Expression for the given postfix parameter. - * + *

    * Avoid using parentheses/brackets/braces for the postfix string. * Postfix Expressions don't require these. * - * * @author nikslyon19 (Nikhil Bisht) - * */ public final class PostfixToInfix { @@ -32,7 +30,7 @@ public static boolean isOperator(char token) { /** * Validates whether a given string is a valid postfix expression. - * + *

    * A valid postfix expression must meet these criteria: * 1. It should have at least one operator and two operands. * 2. The number of operands should always be greater than the number of operators at any point in the traversal. diff --git a/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java b/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java index eb2ce95e18d8..e9970ba664be 100644 --- a/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java +++ b/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java @@ -60,8 +60,8 @@ private static boolean isOperator(String token) { * Applies the given operator to the two operands. * * @param operator The operator to apply. - * @param a The first operand. - * @param b The second operand. + * @param a The first operand. + * @param b The second operand. * @return The result of applying the operator to the operands. */ private static int applyOperator(String operator, int a, int b) { diff --git a/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java b/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java index 41eb974b0e5b..33f4908ad1a7 100644 --- a/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java +++ b/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java @@ -4,7 +4,7 @@ /** * Converts a prefix expression to an infix expression using a stack. - * + *

    * The input prefix expression should consist of * valid operands (letters or digits) and operators (+, -, *, /, ^). * Parentheses are not required in the prefix string. @@ -28,7 +28,7 @@ public static boolean isOperator(char token) { * * @param prefix the prefix expression to convert * @return the equivalent infix expression - * @throws NullPointerException if the prefix expression is null + * @throws NullPointerException if the prefix expression is null */ public static String getPrefixToInfix(String prefix) { if (prefix == null) { diff --git a/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java b/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java index 9864ef9b0f97..8ca8a69f4328 100644 --- a/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java +++ b/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java @@ -8,7 +8,7 @@ * The mainStack is used to store the all the elements of the stack * While the minStack stores the minimum elements * When we want to get a minimum element, we call the top of the minimum stack - * + *

    * Problem: https://www.baeldung.com/cs/stack-constant-time */ public class SmallestElementConstantTime { @@ -27,6 +27,7 @@ public SmallestElementConstantTime() { * Pushes an element onto the top of the stack. * Checks if the element is the minimum or not * If so, then pushes to the minimum stack + * * @param data The element to be pushed onto the stack. */ public void push(int data) { diff --git a/src/main/java/com/thealgorithms/stacks/SortStack.java b/src/main/java/com/thealgorithms/stacks/SortStack.java index d07d1a5f1dc3..695e623b4b19 100644 --- a/src/main/java/com/thealgorithms/stacks/SortStack.java +++ b/src/main/java/com/thealgorithms/stacks/SortStack.java @@ -16,7 +16,7 @@ private SortStack() { * Sorts the given stack in ascending order using recursion. * The sorting is performed such that the largest element ends up on top of the stack. * This method modifies the original stack and does not return a new stack. - * + *

    * The algorithm works as follows: * 1. Remove the top element. * 2. Recursively sort the remaining stack. @@ -39,12 +39,12 @@ public static void sortStack(Stack stack) { * Helper method to insert an element into the correct position in a sorted stack. * This method is called recursively to place the given element into the stack * such that the stack remains sorted in ascending order. - * + *

    * The element is inserted in such a way that all elements below it are smaller * (if the stack is non-empty), and elements above it are larger, maintaining * the ascending order. * - * @param stack The stack in which the element needs to be inserted. + * @param stack The stack in which the element needs to be inserted. * @param element The element to be inserted into the stack in sorted order. */ private static void insertInSortedOrder(Stack stack, int element) { diff --git a/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java b/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java index 690f39d36f5c..e5e04511751b 100644 --- a/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java +++ b/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java @@ -56,10 +56,10 @@ private static void consumeExpression(Stack s, final String exp) { } /** - * @brief Evaluates the given postfix expression. * @param exp the expression to evaluate. * @return the value of the given expression. - * @exception IllegalArgumentException exp is not a valid postix expression. + * @throws IllegalArgumentException exp is not a valid postix expression. + * @brief Evaluates the given postfix expression. */ public static int postfixEvaluate(final String exp) { Stack s = new Stack<>(); diff --git a/src/main/java/com/thealgorithms/strings/CheckAnagrams.java b/src/main/java/com/thealgorithms/strings/CheckAnagrams.java index 7bf7cd9a7c66..14347dfa63eb 100644 --- a/src/main/java/com/thealgorithms/strings/CheckAnagrams.java +++ b/src/main/java/com/thealgorithms/strings/CheckAnagrams.java @@ -10,6 +10,7 @@ public final class CheckAnagrams { private CheckAnagrams() { } + /** * Check if two strings are anagrams or not * diff --git a/src/main/java/com/thealgorithms/strings/CountChar.java b/src/main/java/com/thealgorithms/strings/CountChar.java index 348905445347..34ca9aaa6da7 100644 --- a/src/main/java/com/thealgorithms/strings/CountChar.java +++ b/src/main/java/com/thealgorithms/strings/CountChar.java @@ -9,7 +9,7 @@ private CountChar() { * * @param str the input string to count the characters in * @return the number of non-whitespace characters in the specified string; - * returns 0 if the input string is null + * returns 0 if the input string is null */ public static int countCharacters(String str) { if (str == null) { diff --git a/src/main/java/com/thealgorithms/strings/HammingDistance.java b/src/main/java/com/thealgorithms/strings/HammingDistance.java index 235e317d94f1..29f361caffb5 100644 --- a/src/main/java/com/thealgorithms/strings/HammingDistance.java +++ b/src/main/java/com/thealgorithms/strings/HammingDistance.java @@ -6,6 +6,7 @@ * The Hamming distance is the number of positions at which the corresponding symbols are different. * It is used in information theory, coding theory, and computer science. *

    + * * @see Hamming distance - Wikipedia */ public final class HammingDistance { diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index d9187cbf66c4..c0f04f988557 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -56,7 +56,7 @@ private HorspoolSearch() { * Case sensitive version version of the algorithm * * @param pattern the pattern to be searched for (needle) - * @param text the text being searched in (haystack) + * @param text the text being searched in (haystack) * @return -1 if not found or first index of the pattern in the text */ public static int findFirst(String pattern, String text) { @@ -67,7 +67,7 @@ public static int findFirst(String pattern, String text) { * Case insensitive version version of the algorithm * * @param pattern the pattern to be searched for (needle) - * @param text the text being searched in (haystack) + * @param text the text being searched in (haystack) * @return -1 if not found or first index of the pattern in the text */ public static int findFirstInsensitive(String pattern, String text) { @@ -91,7 +91,7 @@ public static Integer getLastComparisons() { * the first match or when the entire text has been exhausted. * * @param pattern String to be matched in the text - * @param text text String + * @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) { @@ -132,8 +132,8 @@ private static int firstOccurrence(String pattern, String text, boolean caseSens /** * Compares the argument characters * - * @param c1 first character - * @param c2 second character + * @param c1 first character + * @param c2 second character * @param caseSensitive boolean determining case sensitivity of comparison * @return truth value of the equality comparison */ diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java index 5a7c2ce53b1c..db64de7607df 100644 --- a/src/main/java/com/thealgorithms/strings/MyAtoi.java +++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java @@ -12,11 +12,11 @@ private MyAtoi() { * The conversion discards any leading whitespace characters until the first non-whitespace character is found. * Then, it takes an optional initial plus or minus sign followed by as many numerical digits as possible and interprets them as a numerical value. * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - * + *

    * If the number is out of the range of a 32-bit signed integer: * - Returns {@code Integer.MAX_VALUE} if the value exceeds {@code Integer.MAX_VALUE}. * - Returns {@code Integer.MIN_VALUE} if the value is less than {@code Integer.MIN_VALUE}. - * + *

    * If no valid conversion could be performed, a zero is returned. * * @param s the string to convert diff --git a/src/main/java/com/thealgorithms/strings/PermuteString.java b/src/main/java/com/thealgorithms/strings/PermuteString.java index 124bdb6287b4..a366205fb3b8 100644 --- a/src/main/java/com/thealgorithms/strings/PermuteString.java +++ b/src/main/java/com/thealgorithms/strings/PermuteString.java @@ -39,8 +39,8 @@ private PermuteString() { * @param str The input string for which permutations are to be generated. * If the string is null or empty, the result will be an empty set. * @return A {@link Set} of strings containing all unique permutations of the input string. - * If the input string has duplicate characters, the set will ensure that only unique permutations - * are returned. + * If the input string has duplicate characters, the set will ensure that only unique permutations + * are returned. */ public static Set getPermutations(String str) { Set permutations = new HashSet<>(); @@ -51,9 +51,9 @@ public static Set getPermutations(String str) { /** * Generates all permutations of the given string and collects them into a set. * - * @param str the string to permute - * @param start the starting index for the current permutation - * @param end the end index (length of the string) + * @param str the string to permute + * @param start the starting index for the current permutation + * @param end the end index (length of the string) * @param permutations the set to collect all unique permutations */ private static void generatePermutations(String str, int start, int end, Set permutations) { @@ -75,8 +75,8 @@ private static void generatePermutations(String str, int start, int end, Set + * An implementation of Rabin-Karp string matching algorithm + * Program will simply end if there is no match */ public final class RabinKarp { private RabinKarp() { diff --git a/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java b/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java index 7c22cd8a5df2..17322cd677f5 100644 --- a/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java +++ b/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java @@ -9,9 +9,9 @@ private ReverseWordsInString() { } /** - * @brief Reverses words in the input string * @param s the input string * @return A string created by reversing the order of the words in {@code s} + * @brief Reverses words in the input string */ public static String reverseWordsInString(final String s) { var words = s.trim().split("\\s+"); diff --git a/src/main/java/com/thealgorithms/strings/Rotation.java b/src/main/java/com/thealgorithms/strings/Rotation.java index e1352f1197b1..1f8350dfd46d 100644 --- a/src/main/java/com/thealgorithms/strings/Rotation.java +++ b/src/main/java/com/thealgorithms/strings/Rotation.java @@ -35,7 +35,7 @@ public static String rotation(String s, int n) { * array time complexity: O(n) space complexity: O(1) * * @param values given character array - * @param n the total characters to be moved + * @param n the total characters to be moved */ public static void rotation(char[] values, int n) { reverse(values, 0, n - 1); @@ -47,8 +47,8 @@ public static void rotation(char[] values, int n) { * Reverse character array * * @param values character array - * @param from begin index of given array - * @param to end index of given array + * @param from begin index of given array + * @param to end index of given array */ public static void reverse(char[] values, int from, int to) { while (from < to) { diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java index 85bc0e4db641..b5e4f78ee8c0 100644 --- a/src/main/java/com/thealgorithms/strings/StringCompression.java +++ b/src/main/java/com/thealgorithms/strings/StringCompression.java @@ -3,11 +3,13 @@ /** * References : https://en.wikipedia.org/wiki/Run-length_encoding * String compression algorithm deals with encoding the string, that is, shortening the size of the string + * * @author Swarga-codes (https://github.com/Swarga-codes) */ public final class StringCompression { private StringCompression() { } + /** * Returns the compressed or encoded string * @@ -43,6 +45,7 @@ public static String compress(String input) { } return compressedString; } + /** * @param res the resulting string * @param count current count diff --git a/src/main/java/com/thealgorithms/strings/ValidParentheses.java b/src/main/java/com/thealgorithms/strings/ValidParentheses.java index 629fee495d84..215a0b62047e 100644 --- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java @@ -7,6 +7,7 @@ public final class ValidParentheses { private ValidParentheses() { } + public static boolean isValid(String s) { char[] stack = new char[s.length()]; int head = 0; @@ -38,6 +39,7 @@ public static boolean isValid(String s) { } return head == 0; } + public static boolean isValidParentheses(String s) { int i = -1; char[] stack = new char[s.length()]; diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java index 665e5ff3220d..3aa8fd883238 100644 --- a/src/main/java/com/thealgorithms/strings/WordLadder.java +++ b/src/main/java/com/thealgorithms/strings/WordLadder.java @@ -18,8 +18,8 @@ private WordLadder() { * Finds the shortest transformation sequence from beginWord to endWord. * * @param beginWord the starting word of the transformation sequence - * @param endWord the target word of the transformation sequence - * @param wordList a list of words that can be used in the transformation sequence + * @param endWord the target word of the transformation sequence + * @param wordList a list of words that can be used in the transformation sequence * @return the number of words in the shortest transformation sequence, or 0 if no such sequence exists */ public static int ladderLength(String beginWord, String endWord, Collection wordList) { diff --git a/src/test/java/com/thealgorithms/Recursion/GenerateSubsetsTest.java b/src/test/java/com/thealgorithms/Recursion/GenerateSubsetsTest.java index d4bc7e488f80..f920b46acb8d 100644 --- a/src/test/java/com/thealgorithms/Recursion/GenerateSubsetsTest.java +++ b/src/test/java/com/thealgorithms/Recursion/GenerateSubsetsTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.List; + import org.junit.jupiter.api.Test; public final class GenerateSubsetsTest { @@ -10,7 +11,7 @@ public final class GenerateSubsetsTest { @Test void subsetRecursionTestOne() { String str = "abc"; - String[] expected = new String[] {"abc", "ab", "ac", "a", "bc", "b", "c", ""}; + String[] expected = new String[]{"abc", "ab", "ac", "a", "bc", "b", "c", ""}; List ans = GenerateSubsets.subsetRecursion(str); assertArrayEquals(ans.toArray(), expected); @@ -19,7 +20,7 @@ void subsetRecursionTestOne() { @Test void subsetRecursionTestTwo() { String str = "cbf"; - String[] expected = new String[] {"cbf", "cb", "cf", "c", "bf", "b", "f", ""}; + String[] expected = new String[]{"cbf", "cb", "cf", "c", "bf", "b", "f", ""}; List ans = GenerateSubsets.subsetRecursion(str); assertArrayEquals(ans.toArray(), expected); @@ -28,7 +29,7 @@ void subsetRecursionTestTwo() { @Test void subsetRecursionTestThree() { String str = "aba"; - String[] expected = new String[] {"aba", "ab", "aa", "a", "ba", "b", "a", ""}; + String[] expected = new String[]{"aba", "ab", "aa", "a", "ba", "b", "a", ""}; List ans = GenerateSubsets.subsetRecursion(str); assertArrayEquals(ans.toArray(), expected); diff --git a/src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java b/src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java index 66d7d60c501b..efe355966c2b 100644 --- a/src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java +++ b/src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java @@ -19,7 +19,9 @@ void testConstructorValidOrder() { @Test void testConstructorInvalidOrder() { // Test an invalid filter creation (order <= 0) - assertThrows(IllegalArgumentException.class, () -> { new IIRFilter(0); }, "Order must be greater than zero"); + assertThrows(IllegalArgumentException.class, () -> { + new IIRFilter(0); + }, "Order must be greater than zero"); } @Test @@ -29,7 +31,9 @@ void testSetCoeffsInvalidLengthA() { // Invalid 'aCoeffs' length double[] aCoeffs = {1.0}; // too short double[] bCoeffs = {1.0, 0.5}; - assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "aCoeffs must be of size 2"); + assertThrows(IllegalArgumentException.class, () -> { + filter.setCoeffs(aCoeffs, bCoeffs); + }, "aCoeffs must be of size 2"); } @Test @@ -39,7 +43,9 @@ void testSetCoeffsInvalidLengthB() { // Invalid 'bCoeffs' length double[] aCoeffs = {1.0, 0.5}; double[] bCoeffs = {1.0}; // too short - assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "bCoeffs must be of size 2"); + assertThrows(IllegalArgumentException.class, () -> { + filter.setCoeffs(aCoeffs, bCoeffs); + }, "bCoeffs must be of size 2"); } @Test @@ -49,7 +55,9 @@ void testSetCoeffsInvalidACoeffZero() { // Invalid 'aCoeffs' where aCoeffs[0] == 0.0 double[] aCoeffs = {0.0, 0.5}; // aCoeffs[0] must not be zero double[] bCoeffs = {1.0, 0.5}; - assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "aCoeffs[0] must not be zero"); + assertThrows(IllegalArgumentException.class, () -> { + filter.setCoeffs(aCoeffs, bCoeffs); + }, "aCoeffs[0] must not be zero"); } @Test diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java index 177163b09ca1..5eddb9cd0f08 100644 --- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java +++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertIterableEquals; import java.util.List; + import org.junit.jupiter.api.Test; public class AllPathsFromSourceToTargetTest { diff --git a/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java b/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java index a6a3714cb594..6b194e709d69 100644 --- a/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java @@ -4,9 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.thealgorithms.maths.BinomialCoefficient; + import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -27,11 +29,11 @@ void testCombinationThrows(int n, int k) { private static Stream regularInputs() { return Stream.of(Arguments.of(0, 0, List.of(new ArrayList())), Arguments.of(1, 0, List.of(new ArrayList())), Arguments.of(1, 1, List.of(List.of(0))), Arguments.of(3, 0, List.of(new ArrayList())), Arguments.of(3, 1, List.of(List.of(0), List.of(1), List.of(2))), - Arguments.of(4, 2, List.of(List.of(0, 1), List.of(0, 2), List.of(0, 3), List.of(1, 2), List.of(1, 3), List.of(2, 3))), - Arguments.of(5, 3, List.of(List.of(0, 1, 2), List.of(0, 1, 3), List.of(0, 1, 4), List.of(0, 2, 3), List.of(0, 2, 4), List.of(0, 3, 4), List.of(1, 2, 3), List.of(1, 2, 4), List.of(1, 3, 4), List.of(2, 3, 4))), - Arguments.of(6, 4, - List.of(List.of(0, 1, 2, 3), List.of(0, 1, 2, 4), List.of(0, 1, 2, 5), List.of(0, 1, 3, 4), List.of(0, 1, 3, 5), List.of(0, 1, 4, 5), List.of(0, 2, 3, 4), List.of(0, 2, 3, 5), List.of(0, 2, 4, 5), List.of(0, 3, 4, 5), List.of(1, 2, 3, 4), List.of(1, 2, 3, 5), List.of(1, 2, 4, 5), - List.of(1, 3, 4, 5), List.of(2, 3, 4, 5)))); + Arguments.of(4, 2, List.of(List.of(0, 1), List.of(0, 2), List.of(0, 3), List.of(1, 2), List.of(1, 3), List.of(2, 3))), + Arguments.of(5, 3, List.of(List.of(0, 1, 2), List.of(0, 1, 3), List.of(0, 1, 4), List.of(0, 2, 3), List.of(0, 2, 4), List.of(0, 3, 4), List.of(1, 2, 3), List.of(1, 2, 4), List.of(1, 3, 4), List.of(2, 3, 4))), + Arguments.of(6, 4, + List.of(List.of(0, 1, 2, 3), List.of(0, 1, 2, 4), List.of(0, 1, 2, 5), List.of(0, 1, 3, 4), List.of(0, 1, 3, 5), List.of(0, 1, 4, 5), List.of(0, 2, 3, 4), List.of(0, 2, 3, 5), List.of(0, 2, 4, 5), List.of(0, 3, 4, 5), List.of(1, 2, 3, 4), List.of(1, 2, 3, 5), List.of(1, 2, 4, 5), + List.of(1, 3, 4, 5), List.of(2, 3, 4, 5)))); } private static Stream wrongInputs() { diff --git a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java index a9d1163f3ecd..a6d6883e3de1 100644 --- a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Set; import java.util.TreeSet; + import org.junit.jupiter.api.Test; public class CombinationTest { @@ -15,26 +16,28 @@ public class CombinationTest { @Test void testNegativeElement() { Integer[] array = {1, 2}; - assertThrows(IllegalArgumentException.class, () -> { Combination.combination(array, -1); }); + assertThrows(IllegalArgumentException.class, () -> { + Combination.combination(array, -1); + }); } @Test void testNoElement() { - List> result = Combination.combination(new Integer[] {1, 2}, 0); + List> result = Combination.combination(new Integer[]{1, 2}, 0); assertNotNull(result); assertEquals(0, result.size()); } @Test void testLengthOne() { - List> result = Combination.combination(new Integer[] {1, 2}, 1); + 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); + 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); @@ -42,7 +45,7 @@ void testLengthTwo() { @Test void testCombinationsWithStrings() { - List> result = Combination.combination(new String[] {"a", "b", "c"}, 2); + List> result = Combination.combination(new String[]{"a", "b", "c"}, 2); assertEquals(3, result.size()); assertTrue(result.contains(new TreeSet<>(Set.of("a", "b")))); assertTrue(result.contains(new TreeSet<>(Set.of("a", "c")))); diff --git a/src/test/java/com/thealgorithms/backtracking/CrosswordSolverTest.java b/src/test/java/com/thealgorithms/backtracking/CrosswordSolverTest.java index 542fd53fe5ed..a1d7850ac168 100644 --- a/src/test/java/com/thealgorithms/backtracking/CrosswordSolverTest.java +++ b/src/test/java/com/thealgorithms/backtracking/CrosswordSolverTest.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class CrosswordSolverTest { diff --git a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java index 8b860b5b46b0..0c95f2facbb0 100644 --- a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java +++ b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java @@ -27,23 +27,23 @@ void testForSingleElementImage() { @Test 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); @@ -53,23 +53,23 @@ void testForImageOne() { @Test 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); @@ -79,15 +79,15 @@ void testForImageTwo() { @Test 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); diff --git a/src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java b/src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java index 306dbf4c2ec7..7a29ec259d5e 100644 --- a/src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java +++ b/src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/backtracking/MColoringTest.java b/src/test/java/com/thealgorithms/backtracking/MColoringTest.java index f3f25933b7a1..798c0638f404 100644 --- a/src/test/java/com/thealgorithms/backtracking/MColoringTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MColoringTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; + import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java index b8e77fb38bad..4eb63b4677ca 100644 --- a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java @@ -39,25 +39,25 @@ public void testSolveMazeUsingFirstAndSecondStrategy() { int[][] solvedMap1 = MazeRecursion.solveMazeUsingFirstStrategy(map); // Solve the maze using the second strategy int[][] solvedMap2 = MazeRecursion.solveMazeUsingSecondStrategy(map2); - int[][] expectedMap1 = 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[][] expectedMap1 = 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}, }; // Assert the results diff --git a/src/test/java/com/thealgorithms/backtracking/NQueensTest.java b/src/test/java/com/thealgorithms/backtracking/NQueensTest.java index 977e3dfae2ce..7a7b584a01d8 100644 --- a/src/test/java/com/thealgorithms/backtracking/NQueensTest.java +++ b/src/test/java/com/thealgorithms/backtracking/NQueensTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class NQueensTest { diff --git a/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java b/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java index 9da16061d8f4..7fc195053ae9 100644 --- a/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java +++ b/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -24,7 +25,7 @@ void throwsForNegativeInputTests(int input) { private static Stream regularInputStream() { return Stream.of(Arguments.of(0, List.of("")), Arguments.of(1, List.of("()")), Arguments.of(2, List.of("(())", "()()")), Arguments.of(3, List.of("((()))", "(()())", "(())()", "()(())", "()()()")), - Arguments.of(4, List.of("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"))); + Arguments.of(4, List.of("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"))); } private static Stream negativeInputStream() { diff --git a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java index 76a714829109..b062d08bf13a 100644 --- a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java @@ -5,26 +5,27 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class PermutationTest { @Test void testNoElement() { - List result = Permutation.permutation(new Integer[] {}); + List result = Permutation.permutation(new Integer[]{}); assertEquals(result.get(0).length, 0); } @Test void testSingleElement() { - List result = Permutation.permutation(new Integer[] {1}); + 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})); + 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/backtracking/PowerSumTest.java b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java index b14bce2b1920..6de586ac2a65 100644 --- a/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java @@ -1,4 +1,5 @@ package com.thealgorithms.backtracking; + import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java b/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java index dac2e2675674..b318f68c6dc4 100644 --- a/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java +++ b/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -19,8 +20,8 @@ void testGenerateAll(TestCase testData) { static Stream getTestCases() { return Stream.of(new TestCase(new ArrayList<>(), List.of(List.of())), new TestCase(List.of(1, 2), List.of(List.of(), List.of(2), List.of(1), List.of(1, 2))), - new TestCase(List.of("A", "B", "C"), List.of(List.of(), List.of("C"), List.of("B"), List.of("B", "C"), List.of("A"), List.of("A", "C"), List.of("A", "B"), List.of("A", "B", "C"))), - new TestCase(List.of(1, 2, 3), List.of(List.of(), List.of(3), List.of(2), List.of(2, 3), List.of(1), List.of(1, 3), List.of(1, 2), List.of(1, 2, 3))), new TestCase(List.of(2, 2), List.of(List.of(), List.of(2), List.of(2), List.of(2, 2)))); + new TestCase(List.of("A", "B", "C"), List.of(List.of(), List.of("C"), List.of("B"), List.of("B", "C"), List.of("A"), List.of("A", "C"), List.of("A", "B"), List.of("A", "B", "C"))), + new TestCase(List.of(1, 2, 3), List.of(List.of(), List.of(3), List.of(2), List.of(2, 3), List.of(1), List.of(1, 3), List.of(1, 2), List.of(1, 2, 3))), new TestCase(List.of(2, 2), List.of(List.of(), List.of(2), List.of(2), List.of(2, 2)))); } record TestCase(List input, List> expected) { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java b/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java index 40de770e0c66..6b43107b8584 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; + public class BitSwapTest { @Test void testHighestSetBit() { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java b/src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java index 8737d05ec459..149110144312 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java @@ -9,10 +9,12 @@ import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.NOTGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.ORGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.XORGate; + import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; @@ -64,38 +66,38 @@ void testNORGate(List inputs, boolean expected) { // Helper methods to provide test data for each gate static Stream provideAndGateTestCases() { - return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, - new Object[] {Collections.emptyList(), Boolean.TRUE} // AND over no inputs is true + return Stream.of(new Object[]{Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, new Object[]{Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, new Object[]{Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, + new Object[]{Collections.emptyList(), Boolean.TRUE} // AND over no inputs is true ); } static Stream provideOrGateTestCases() { - return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, - new Object[] {Collections.emptyList(), Boolean.FALSE} // OR over no inputs is false + return Stream.of(new Object[]{Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, new Object[]{Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, new Object[]{Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, + new Object[]{Collections.emptyList(), Boolean.FALSE} // OR over no inputs is false ); } static Stream provideXorGateTestCases() { - return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // XOR over odd true - new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // XOR over single true - new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, // XOR over all false - new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE} // XOR over even true + return Stream.of(new Object[]{Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // XOR over odd true + new Object[]{Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // XOR over single true + new Object[]{Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, // XOR over all false + new Object[]{Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE} // XOR over even true ); } static Stream provideNandGateTestCases() { - return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NAND of all true is false - new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE), Boolean.TRUE}, // NAND with one false is true - new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NAND of all false is true - new Object[] {Collections.emptyList(), Boolean.FALSE} // NAND over no inputs is false (negation of AND) + return Stream.of(new Object[]{Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NAND of all true is false + new Object[]{Arrays.asList(Boolean.TRUE, Boolean.FALSE), Boolean.TRUE}, // NAND with one false is true + new Object[]{Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NAND of all false is true + new Object[]{Collections.emptyList(), Boolean.FALSE} // NAND over no inputs is false (negation of AND) ); } static Stream provideNorGateTestCases() { - return Stream.of(new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NOR of all false is true - new Object[] {Arrays.asList(Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // NOR with one true is false - new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NOR of all true is false - new Object[] {Collections.emptyList(), Boolean.TRUE} // NOR over no inputs is true (negation of OR) + return Stream.of(new Object[]{Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NOR of all false is true + new Object[]{Arrays.asList(Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // NOR with one true is false + new Object[]{Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NOR of all true is false + new Object[]{Collections.emptyList(), Boolean.TRUE} // NOR over no inputs is true (negation of OR) ); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java index 978003d21358..53aca9a9b484 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -12,8 +13,8 @@ public final class FindNthBitTest { /** * A parameterized test that checks the value of the Nth bit for different inputs. * - * @param num the number whose Nth bit is being tested - * @param n the bit position + * @param num the number whose Nth bit is being tested + * @param n the bit position * @param expected the expected value of the Nth bit (0 or 1) */ @ParameterizedTest @@ -30,10 +31,10 @@ void findNthBitParameterizedTest(int num, int n, int expected) { */ private static Stream provideTestCases() { return Stream.of(Arguments.of(13, 2, 0), // binary: 1101, 2nd bit is 0 - Arguments.of(13, 3, 1), // binary: 1101, 3rd bit is 1 - Arguments.of(4, 2, 0), // binary: 100, 2nd bit is 0 - Arguments.of(4, 3, 1), // binary: 100, 3rd bit is 1 - Arguments.of(1, 1, 1) // binary: 1, 1st bit is 1 + Arguments.of(13, 3, 1), // binary: 1101, 3rd bit is 1 + Arguments.of(4, 2, 0), // binary: 100, 2nd bit is 0 + Arguments.of(4, 3, 1), // binary: 100, 3rd bit is 1 + Arguments.of(1, 1, 1) // binary: 1, 1st bit is 1 ); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java index e3205d1d0dba..02b7cac816ad 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; class GenerateSubsetsTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java index 532f06f79ab3..eada8e98b4aa 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java @@ -8,6 +8,7 @@ /** * Test case for Highest Set Bit + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java index 9bf804373438..3388cb49a7c3 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java @@ -6,6 +6,7 @@ /** * Test case for Index Of Right Most SetBit + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java index ffd9e4ef176d..e92a3763e274 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java @@ -4,12 +4,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Test case for IsPowerTwo class + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ @@ -27,25 +29,25 @@ public void testIsPowerTwo(int number, boolean expected) { private static Stream provideNumbersForPowerTwo() { return Stream.of(Arguments.of(1, Boolean.TRUE), // 2^0 - Arguments.of(2, Boolean.TRUE), // 2^1 - Arguments.of(4, Boolean.TRUE), // 2^2 - Arguments.of(8, Boolean.TRUE), // 2^3 - Arguments.of(16, Boolean.TRUE), // 2^4 - Arguments.of(32, Boolean.TRUE), // 2^5 - Arguments.of(64, Boolean.TRUE), // 2^6 - Arguments.of(128, Boolean.TRUE), // 2^7 - Arguments.of(256, Boolean.TRUE), // 2^8 - Arguments.of(1024, Boolean.TRUE), // 2^10 - Arguments.of(0, Boolean.FALSE), // 0 is not a power of two - Arguments.of(-1, Boolean.FALSE), // Negative number - Arguments.of(-2, Boolean.FALSE), // Negative number - Arguments.of(-4, Boolean.FALSE), // Negative number - Arguments.of(3, Boolean.FALSE), // 3 is not a power of two - Arguments.of(5, Boolean.FALSE), // 5 is not a power of two - Arguments.of(6, Boolean.FALSE), // 6 is not a power of two - Arguments.of(15, Boolean.FALSE), // 15 is not a power of two - Arguments.of(1000, Boolean.FALSE), // 1000 is not a power of two - Arguments.of(1023, Boolean.FALSE) // 1023 is not a power of two + Arguments.of(2, Boolean.TRUE), // 2^1 + Arguments.of(4, Boolean.TRUE), // 2^2 + Arguments.of(8, Boolean.TRUE), // 2^3 + Arguments.of(16, Boolean.TRUE), // 2^4 + Arguments.of(32, Boolean.TRUE), // 2^5 + Arguments.of(64, Boolean.TRUE), // 2^6 + Arguments.of(128, Boolean.TRUE), // 2^7 + Arguments.of(256, Boolean.TRUE), // 2^8 + Arguments.of(1024, Boolean.TRUE), // 2^10 + Arguments.of(0, Boolean.FALSE), // 0 is not a power of two + Arguments.of(-1, Boolean.FALSE), // Negative number + Arguments.of(-2, Boolean.FALSE), // Negative number + Arguments.of(-4, Boolean.FALSE), // Negative number + Arguments.of(3, Boolean.FALSE), // 3 is not a power of two + Arguments.of(5, Boolean.FALSE), // 5 is not a power of two + Arguments.of(6, Boolean.FALSE), // 6 is not a power of two + Arguments.of(15, Boolean.FALSE), // 15 is not a power of two + Arguments.of(1000, Boolean.FALSE), // 1000 is not a power of two + Arguments.of(1023, Boolean.FALSE) // 1023 is not a power of two ); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java index 4c4d33640ad4..d039c9daa7ad 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java @@ -6,6 +6,7 @@ /** * Test case for Lowest Set Bit + * * @author Prayas Kumar (https://github.com/prayas7102) */ diff --git a/src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java b/src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java index ff7f621a64c0..023d6fcbb219 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java @@ -10,12 +10,12 @@ class ModuloPowerOfTwoTest { @ParameterizedTest @CsvSource({ - "10, 3, 2", - "15, 2, 3", - "20, 4, 4", - "7, 1, 1", - "5, 1, 1", - "36, 5, 4", + "10, 3, 2", + "15, 2, 3", + "20, 4, 4", + "7, 1, 1", + "5, 1, 1", + "36, 5, 4", }) void testModuloPowerOfTwo(int x, int n, int expected) { @@ -24,11 +24,11 @@ class ModuloPowerOfTwoTest { @ParameterizedTest @CsvSource({ - "10, 0", - "15, -2", - "20, -4", - "7, -1", - "5, -1", + "10, 0", + "15, -2", + "20, -4", + "7, -1", + "5, -1", }) void testNegativeExponent(int x, int n) { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java index c8fb9ef21b60..3db92e039332 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java @@ -9,11 +9,11 @@ class NextHigherSameBitCountTest { @ParameterizedTest @CsvSource({ - "5, 6", // 101 -> 110 - "7, 11", // 0111 -> 1011 - "3, 5", // 011 -> 101 - "12, 17", // 001100 -> 010001 - "15, 23" // 01111 -> 10111 + "5, 6", // 101 -> 110 + "7, 11", // 0111 -> 1011 + "3, 5", // 011 -> 101 + "12, 17", // 001100 -> 010001 + "15, 23" // 01111 -> 10111 }) void testNextHigherSameBitCount(int input, int expected) { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java index fe2136fd7f04..8e80be457c44 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java @@ -22,15 +22,15 @@ void testNonRepeatingNumberFinder(int[] arr, int expected) { } private static Arguments[] testCases() { - return new Arguments[] { - Arguments.of(new int[] {1, 2, 1, 2, 6}, 6), Arguments.of(new int[] {1, 2, 1, 2}, 0), // All numbers repeat - Arguments.of(new int[] {12}, 12), // Single non-repeating number - Arguments.of(new int[] {3, 5, 3, 4, 4}, 5), // More complex case - Arguments.of(new int[] {7, 8, 7, 9, 8, 10, 10}, 9), // Non-repeating in the middle - Arguments.of(new int[] {0, -1, 0, -1, 2}, 2), // Testing with negative numbers - Arguments.of(new int[] {Integer.MAX_VALUE, 1, 1}, Integer.MAX_VALUE), // Edge case with max int - Arguments.of(new int[] {2, 2, 3, 3, 4, 5, 4}, 5), // Mixed duplicates - Arguments.of(new int[] {}, 0) // Edge case: empty array (should be handled as per design) + return new Arguments[]{ + Arguments.of(new int[]{1, 2, 1, 2, 6}, 6), Arguments.of(new int[]{1, 2, 1, 2}, 0), // All numbers repeat + Arguments.of(new int[]{12}, 12), // Single non-repeating number + Arguments.of(new int[]{3, 5, 3, 4, 4}, 5), // More complex case + Arguments.of(new int[]{7, 8, 7, 9, 8, 10, 10}, 9), // Non-repeating in the middle + Arguments.of(new int[]{0, -1, 0, -1, 2}, 2), // Testing with negative numbers + Arguments.of(new int[]{Integer.MAX_VALUE, 1, 1}, Integer.MAX_VALUE), // Edge case with max int + Arguments.of(new int[]{2, 2, 3, 3, 4, 5, 4}, 5), // Mixed duplicates + Arguments.of(new int[]{}, 0) // Edge case: empty array (should be handled as per design) }; } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java index 83d458319f3b..9a7047121cdb 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -25,25 +26,25 @@ void testFindOddOccurrence(int[] input, int expected) { */ private static Stream provideTestCases() { return Stream.of( - // Single element appearing odd times (basic case) - Arguments.of(new int[] {5, 6, 7, 8, 6, 7, 5}, 8), + // Single element appearing odd times (basic case) + Arguments.of(new int[]{5, 6, 7, 8, 6, 7, 5}, 8), - // More complex case with multiple pairs - Arguments.of(new int[] {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}, 5), + // More complex case with multiple pairs + Arguments.of(new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}, 5), - // Case with only one element appearing once - Arguments.of(new int[] {10, 10, 20, 20, 30}, 30), + // Case with only one element appearing once + Arguments.of(new int[]{10, 10, 20, 20, 30}, 30), - // Negative numbers with an odd occurrence - Arguments.of(new int[] {-5, -5, -3, -3, -7, -7, -7}, -7), + // Negative numbers with an odd occurrence + Arguments.of(new int[]{-5, -5, -3, -3, -7, -7, -7}, -7), - // All elements cancel out to 0 (even occurrences of all elements) - Arguments.of(new int[] {1, 2, 1, 2}, 0), + // All elements cancel out to 0 (even occurrences of all elements) + Arguments.of(new int[]{1, 2, 1, 2}, 0), - // Array with a single element (trivial case) - Arguments.of(new int[] {42}, 42), + // Array with a single element (trivial case) + Arguments.of(new int[]{42}, 42), - // Large array with repeated patterns - Arguments.of(new int[] {1, 1, 2, 2, 3, 3, 3, 4, 4}, 3)); + // Large array with repeated patterns + Arguments.of(new int[]{1, 1, 2, 2, 3, 3, 3, 4, 4}, 3)); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java index 33e5ae048814..c87262211118 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -28,19 +29,19 @@ void testDifferentSigns(int num1, int num2, boolean expected) { private static Stream provideTestCases() { return Stream.of( - // Different signs (positive and negative) - Arguments.of(2, -1, Boolean.TRUE), Arguments.of(-3, 7, Boolean.TRUE), + // Different signs (positive and negative) + Arguments.of(2, -1, Boolean.TRUE), Arguments.of(-3, 7, Boolean.TRUE), - // Same signs (both positive) - Arguments.of(10, 20, Boolean.FALSE), Arguments.of(0, 5, Boolean.FALSE), // 0 is considered non-negative + // Same signs (both positive) + Arguments.of(10, 20, Boolean.FALSE), Arguments.of(0, 5, Boolean.FALSE), // 0 is considered non-negative - // Same signs (both negative) - Arguments.of(-5, -8, Boolean.FALSE), + // Same signs (both negative) + Arguments.of(-5, -8, Boolean.FALSE), - // Edge case: Large positive and negative values - Arguments.of(Integer.MAX_VALUE, Integer.MIN_VALUE, Boolean.TRUE), + // Edge case: Large positive and negative values + Arguments.of(Integer.MAX_VALUE, Integer.MIN_VALUE, Boolean.TRUE), - // Edge case: Same number (positive and negative) - Arguments.of(-42, -42, Boolean.FALSE), Arguments.of(42, 42, Boolean.FALSE)); + // Edge case: Same number (positive and negative) + Arguments.of(-42, -42, Boolean.FALSE), Arguments.of(42, 42, Boolean.FALSE)); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java index 6be4eb595f79..b80d9542289b 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java @@ -6,6 +6,7 @@ /** * Test case for Highest Set Bit + * * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma) */ public class OnesComplementTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/SingleBitOperationsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/SingleBitOperationsTest.java index 6c447ec9805e..07dd9d6541d2 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/SingleBitOperationsTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/SingleBitOperationsTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,7 +18,7 @@ void testFlipBit(int input, int bit, int expected) { private static Stream provideFlipBitTestCases() { return Stream.of(Arguments.of(3, 1, 1), // Binary: 11 -> 01 - Arguments.of(3, 3, 11) // Binary: 11 -> 1011 + Arguments.of(3, 3, 11) // Binary: 11 -> 1011 ); } @@ -29,9 +30,9 @@ void testSetBit(int input, int bit, int expected) { private static Stream provideSetBitTestCases() { return Stream.of(Arguments.of(4, 0, 5), // 100 -> 101 - Arguments.of(4, 2, 4), // 100 -> 100 (bit already set) - Arguments.of(0, 1, 2), // 00 -> 10 - Arguments.of(10, 2, 14) // 1010 -> 1110 + Arguments.of(4, 2, 4), // 100 -> 100 (bit already set) + Arguments.of(0, 1, 2), // 00 -> 10 + Arguments.of(10, 2, 14) // 1010 -> 1110 ); } @@ -43,7 +44,7 @@ void testClearBit(int input, int bit, int expected) { private static Stream provideClearBitTestCases() { return Stream.of(Arguments.of(7, 1, 5), // 111 -> 101 - Arguments.of(5, 1, 5) // 101 -> 101 (bit already cleared) + Arguments.of(5, 1, 5) // 101 -> 101 (bit already cleared) ); } @@ -55,7 +56,7 @@ void testGetBit(int input, int bit, int expected) { private static Stream provideGetBitTestCases() { return Stream.of(Arguments.of(6, 0, 0), // 110 -> Bit 0: 0 - Arguments.of(7, 1, 1) // 111 -> Bit 1: 1 + Arguments.of(7, 1, 1) // 111 -> Bit 1: 1 ); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java index 2e2afe99b0da..fc2962c5c929 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -13,7 +14,7 @@ public final class SingleElementTest { * Parameterized test to find the single non-duplicate element * in the given arrays. * - * @param arr the input array where every element appears twice except one + * @param arr the input array where every element appears twice except one * @param expected the expected single element result */ @ParameterizedTest @@ -28,6 +29,6 @@ void testFindSingleElement(int[] arr, int expected) { * @return Stream of arguments consisting of arrays and expected results */ private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {1, 1, 2, 2, 4, 4, 3}, 3), Arguments.of(new int[] {1, 2, 2, 3, 3}, 1), Arguments.of(new int[] {10}, 10)); + return Stream.of(Arguments.of(new int[]{1, 1, 2, 2, 4, 4, 3}, 3), Arguments.of(new int[]{1, 2, 2, 3, 3}, 1), Arguments.of(new int[]{10}, 10)); } } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java index 67c986136ab0..82eea9c2bed0 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java @@ -9,11 +9,11 @@ class SwapAdjacentBitsTest { @ParameterizedTest @CsvSource({ - "2, 1", // 2 (10 in binary) should become 1 (01 in binary) - "43, 23", // 43 should become 23 - "153, 102", // 153 should become 102 - "15, 15", // 15 (1111) remains 15 (1111) - "0, 0" // 0 (0000) remains 0 (0000) + "2, 1", // 2 (10 in binary) should become 1 (01 in binary) + "43, 23", // 43 should become 23 + "153, 102", // 153 should become 102 + "15, 15", // 15 (1111) remains 15 (1111) + "0, 0" // 0 (0000) remains 0 (0000) }) void testSwapAdjacentBits(int input, int expected) { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java index 578acc7af18c..5b833078cffd 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java @@ -7,6 +7,7 @@ /** * Test case for Highest Set Bit + * * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma) */ public class TwosComplementTest { diff --git a/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java b/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java index 2f0831e35064..2373e1be6614 100644 --- a/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java +++ b/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import javax.crypto.SecretKey; + import org.junit.jupiter.api.Test; public class AESEncryptionTest { @@ -55,7 +56,7 @@ public void testEncryptDecrypt() throws Exception { @Test public void testBytesToHex() { - byte[] bytes = new byte[] {0, 1, 15, 16, (byte) 255}; // Test with diverse byte values + byte[] bytes = new byte[]{0, 1, 15, 16, (byte) 255}; // Test with diverse byte values String hex = AESEncryption.bytesToHex(bytes); assertEquals("00010F10FF", hex, "Hex representation should match the expected value"); } diff --git a/src/test/java/com/thealgorithms/ciphers/AtbashTest.java b/src/test/java/com/thealgorithms/ciphers/AtbashTest.java index ec34bc26ad72..bd479ba00214 100644 --- a/src/test/java/com/thealgorithms/ciphers/AtbashTest.java +++ b/src/test/java/com/thealgorithms/ciphers/AtbashTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -18,26 +19,26 @@ public void testAtbashCipher(String input, String expected) { private static Stream cipherTestProvider() { return Stream.of( - // Basic tests with lowercase and uppercase - Arguments.of("Hello", "Svool"), Arguments.of("WORLD", "DLIOW"), + // Basic tests with lowercase and uppercase + Arguments.of("Hello", "Svool"), Arguments.of("WORLD", "DLIOW"), - // Mixed case with spaces and punctuation - Arguments.of("Hello World!", "Svool Dliow!"), Arguments.of("123 ABC xyz", "123 ZYX cba"), + // Mixed case with spaces and punctuation + Arguments.of("Hello World!", "Svool Dliow!"), Arguments.of("123 ABC xyz", "123 ZYX cba"), - // Palindromes and mixed cases - Arguments.of("madam", "nzwzn"), Arguments.of("Palindrome", "Kzormwilnv"), + // Palindromes and mixed cases + Arguments.of("madam", "nzwzn"), Arguments.of("Palindrome", "Kzormwilnv"), - // Non-alphabetic characters should remain unchanged - Arguments.of("@cipher 123!", "@xrksvi 123!"), Arguments.of("no-change", "ml-xszmtv"), + // Non-alphabetic characters should remain unchanged + Arguments.of("@cipher 123!", "@xrksvi 123!"), Arguments.of("no-change", "ml-xszmtv"), - // Empty string and single characters - Arguments.of("", ""), Arguments.of("A", "Z"), Arguments.of("z", "a"), + // Empty string and single characters + Arguments.of("", ""), Arguments.of("A", "Z"), Arguments.of("z", "a"), - // Numbers and symbols - Arguments.of("!@#123", "!@#123"), + // Numbers and symbols + Arguments.of("!@#123", "!@#123"), - // Full sentence with uppercase, lowercase, symbols, and numbers - Arguments.of("Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!", "Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!"), - Arguments.of("Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!", "Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!")); + // Full sentence with uppercase, lowercase, symbols, and numbers + Arguments.of("Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!", "Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!"), + Arguments.of("Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!", "Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!")); } } diff --git a/src/test/java/com/thealgorithms/ciphers/DESTest.java b/src/test/java/com/thealgorithms/ciphers/DESTest.java index ddc643a6eb35..3c3a68b7b1bc 100644 --- a/src/test/java/com/thealgorithms/ciphers/DESTest.java +++ b/src/test/java/com/thealgorithms/ciphers/DESTest.java @@ -23,9 +23,9 @@ void testEncrypt() { // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in // hexadecimal String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" - + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" - + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" - + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; // when String cipherText = des.encrypt(plainText); @@ -41,9 +41,9 @@ void testDecrypt() { // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in // hexadecimal String cipherText = "11000000100110011001111111011101111000110111100011010111111" - + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" - + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" - + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; String expectedOutput = "Your lips are smoother than vaseline\r\n"; // when diff --git a/src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java b/src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java index 6255ad22ab56..803112b735ad 100644 --- a/src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java +++ b/src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java @@ -4,6 +4,7 @@ import java.math.BigInteger; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/ciphers/ECCTest.java b/src/test/java/com/thealgorithms/ciphers/ECCTest.java index 701f801af1c8..a4b8078c1d60 100644 --- a/src/test/java/com/thealgorithms/ciphers/ECCTest.java +++ b/src/test/java/com/thealgorithms/ciphers/ECCTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.math.BigInteger; + import org.junit.jupiter.api.Test; /** @@ -66,7 +67,7 @@ void testDecryptWithKnownValues() { // 4. Define the known ciphertext containing two ECPoints (R, S) ECC.ECPoint rPoint = new ECC.ECPoint(new BigInteger("103077584019003058745849614420912636617007257617156724481937620119667345237687"), new BigInteger("68193862907937248121971710522760893811582068323088661566426323952783362061817")); ECC.ECPoint sPoint = new ECC.ECPoint(new BigInteger("31932232426664380635434632300383525435115368414929679432313910646436992147798"), new BigInteger("77299754382292904069123203569944908076819220797512755280123348910207308129766")); - ECC.ECPoint[] cipherText = new ECC.ECPoint[] {rPoint, sPoint}; + ECC.ECPoint[] cipherText = new ECC.ECPoint[]{rPoint, sPoint}; // 5. Create an ECC instance and set the private key and curve parameters ecc.setPrivateKey(knownPrivateKey); // Use setter method to set the private key diff --git a/src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java b/src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java index b1a8c78c952e..a2990b36ffe0 100644 --- a/src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java +++ b/src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/ciphers/RSATest.java b/src/test/java/com/thealgorithms/ciphers/RSATest.java index 577f56426be8..ecd25d59c8e6 100644 --- a/src/test/java/com/thealgorithms/ciphers/RSATest.java +++ b/src/test/java/com/thealgorithms/ciphers/RSATest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigInteger; + import org.junit.jupiter.api.Test; class RSATest { diff --git a/src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java b/src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java index 011a1b521e31..eefb6d69a63d 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.BitSet; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,14 +14,14 @@ public class A5CipherTest { @BeforeEach void setUp() { // Initialize the session key and frame counter - final var sessionKey = BitSet.valueOf(new long[] {0b1010101010101010L}); - final var frameCounter = BitSet.valueOf(new long[] {0b0000000000000001L}); + final var sessionKey = BitSet.valueOf(new long[]{0b1010101010101010L}); + final var frameCounter = BitSet.valueOf(new long[]{0b0000000000000001L}); a5Cipher = new A5Cipher(sessionKey, frameCounter); } @Test void testEncryptWithValidInput() { - BitSet plainText = BitSet.valueOf(new long[] {0b1100110011001100L}); // Example plaintext + BitSet plainText = BitSet.valueOf(new long[]{0b1100110011001100L}); // Example plaintext BitSet encrypted = a5Cipher.encrypt(plainText); // The expected result depends on the key stream generated. @@ -31,7 +32,7 @@ void testEncryptWithValidInput() { @Test void testEncryptAllOnesInput() { - BitSet plainText = BitSet.valueOf(new long[] {0b1111111111111111L}); // All ones + BitSet plainText = BitSet.valueOf(new long[]{0b1111111111111111L}); // All ones BitSet encrypted = a5Cipher.encrypt(plainText); // Similar to testEncryptWithValidInput, ensure that output isn't the same as input diff --git a/src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java b/src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java index c9b721f90b2d..b04912f1369a 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.BitSet; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,8 +20,8 @@ void setUp() { keyStreamGenerator = new A5KeyStreamGenerator(); // Initialize session key and frame counter for testing - final var sessionKey = BitSet.valueOf(new long[] {0b1010101010101010L}); // Example 16-bit key - frameCounter = BitSet.valueOf(new long[] {0b0000000000000001L}); // Example 16-bit frame counter + final var sessionKey = BitSet.valueOf(new long[]{0b1010101010101010L}); // Example 16-bit key + frameCounter = BitSet.valueOf(new long[]{0b0000000000000001L}); // Example 16-bit frame counter keyStreamGenerator.initialize(sessionKey, frameCounter); } diff --git a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java index 6ef478f95358..dbef59d6e8c7 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import java.util.BitSet; + import org.junit.jupiter.api.Test; // Basic tests for sanity check @@ -12,14 +13,14 @@ 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, + 58, + (byte) 139, + (byte) 184, + 30, + 124, + 77, + 47, + 78, }; // Represents 11 1010 1011 0011 1100 1011 @@ -46,7 +47,7 @@ void initialize() { expected.set(16); expected.set(17); - LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); + LFSR lfsr0 = new LFSR(19, 8, new int[]{13, 16, 17, 18}); lfsr0.initialize(sessionKey, frameCounter); assertEquals(expected.toString(), lfsr0.toString()); } @@ -56,7 +57,7 @@ void clock() { 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}); lfsr0.initialize(sessionKey, frameCounter); BitSet expected = new BitSet(19); @@ -85,7 +86,7 @@ void getClockBit() { 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()); diff --git a/src/test/java/com/thealgorithms/conversions/EndianConverterTest.java b/src/test/java/com/thealgorithms/conversions/EndianConverterTest.java index 85ffa2190962..a456725949b2 100644 --- a/src/test/java/com/thealgorithms/conversions/EndianConverterTest.java +++ b/src/test/java/com/thealgorithms/conversions/EndianConverterTest.java @@ -9,9 +9,9 @@ public class EndianConverterTest { @ParameterizedTest @CsvSource({ - "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", - "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement - "0x0000007F, 0x7F000000" // Positive boundary case + "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", + "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement + "0x0000007F, 0x7F000000" // Positive boundary case }) public void testLittleToBigEndian(String inputHex, String expectedHex) { @@ -22,9 +22,9 @@ public class EndianConverterTest { @ParameterizedTest @CsvSource({ - "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", - "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement - "0x7F000000, 0x0000007F" // Positive boundary case + "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", + "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement + "0x7F000000, 0x0000007F" // Positive boundary case }) public void testBigToLittleEndian(String inputHex, String expectedHex) { diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java index 1426eab64d2c..bd8dc4193ad3 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java @@ -16,9 +16,9 @@ public class HexaDecimalToBinaryTest { */ @ParameterizedTest @CsvSource({ - "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", - "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement - "0x0000007F, 0x7F000000" // Positive boundary case + "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", + "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement + "0x0000007F, 0x7F000000" // Positive boundary case }) public void testLittleToBigEndian(String inputHex, String expectedHex) { @@ -32,9 +32,9 @@ public class HexaDecimalToBinaryTest { */ @ParameterizedTest @CsvSource({ - "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", - "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement - "0x7F000000, 0x0000007F" // Positive boundary case + "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", + "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement + "0x7F000000, 0x0000007F" // Positive boundary case }) public void testBigToLittleEndian(String inputHex, String expectedHex) { diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java index d0d6b400e299..bda35dc3fc9c 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java @@ -10,13 +10,13 @@ public class HexaDecimalToDecimalTest { @ParameterizedTest @CsvSource({ - "A1, 161", // Simple case with two characters - "1AC, 428", // Mixed-case input - "0, 0", // Single zero - "F, 15", // Single digit - "10, 16", // Power of 16 - "FFFF, 65535", // Max 4-character hex - "7FFFFFFF, 2147483647" // Max positive int value + "A1, 161", // Simple case with two characters + "1AC, 428", // Mixed-case input + "0, 0", // Single zero + "F, 15", // Single digit + "10, 16", // Power of 16 + "FFFF, 65535", // Max 4-character hex + "7FFFFFFF, 2147483647" // Max positive int value }) public void testValidHexaToDecimal(String hexInput, int expectedDecimal) { @@ -25,10 +25,10 @@ public class HexaDecimalToDecimalTest { @ParameterizedTest @CsvSource({ - "G", // Invalid character - "1Z", // Mixed invalid input - "123G", // Valid prefix with invalid character - "#$%" // Non-hexadecimal symbols + "G", // Invalid character + "1Z", // Mixed invalid input + "123G", // Valid prefix with invalid character + "#$%" // Non-hexadecimal symbols }) public void testInvalidHexaToDecimal(String invalidHex) { diff --git a/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java b/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java index 443f865ae0dc..b5b47a5ea6a4 100644 --- a/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java +++ b/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java @@ -4,31 +4,32 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.UnknownHostException; + import org.junit.jupiter.api.Test; public class IPv6ConverterTest { private static final String VALID_IPV4 = "192." - + "0." - + "2." - + "128"; + + "0." + + "2." + + "128"; private static final String EXPECTED_IPV6_MAPPED = ":" - + ":ff" - + "ff" - + ":19" - + "2." - + "0." - + "2.128"; + + ":ff" + + "ff" + + ":19" + + "2." + + "0." + + "2.128"; private static final String INVALID_IPV6_MAPPED = "2001:" - + "db8" - + ":" - + ":1"; + + "db8" + + ":" + + ":1"; private static final String INVALID_IPV4 = "999." - + "999." - + "999." - + "999"; + + "999." + + "999." + + "999"; private static final String INVALID_IPV6_FORMAT = "invalid:ipv6" - + "::address"; + + "::address"; private static final String EMPTY_STRING = ""; @Test diff --git a/src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java b/src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java index 360af7fa0f51..dc88ae17dfde 100644 --- a/src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java +++ b/src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java @@ -9,16 +9,16 @@ public class PhoneticAlphabetConverterTest { @ParameterizedTest @CsvSource({ - "'AB', 'Alpha Bravo'", "'ABC', 'Alpha Bravo Charlie'", "'A1B2C3', 'Alpha One Bravo Two Charlie Three'", "'Hello', 'Hotel Echo Lima Lima Oscar'", "'123', 'One Two Three'", - "'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", - "'abcdefghijklmnopqrstuvwxyz0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", - "'', ''", // Empty string case - "'A B C', 'Alpha Bravo Charlie'", // String with spaces - "'A@B#C', 'Alpha @ Bravo # Charlie'", // Special characters - "'A B C 123', 'Alpha Bravo Charlie One Two Three'", // Mixed letters, digits, and spaces - "'a b c', 'Alpha Bravo Charlie'", // Lowercase letters with spaces - "'123!@#', 'One Two Three ! @ #'", // Numbers with special characters - "'HELLO WORLD', 'Hotel Echo Lima Lima Oscar Whiskey Oscar Romeo Lima Delta'" // Words with space + "'AB', 'Alpha Bravo'", "'ABC', 'Alpha Bravo Charlie'", "'A1B2C3', 'Alpha One Bravo Two Charlie Three'", "'Hello', 'Hotel Echo Lima Lima Oscar'", "'123', 'One Two Three'", + "'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", + "'abcdefghijklmnopqrstuvwxyz0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", + "'', ''", // Empty string case + "'A B C', 'Alpha Bravo Charlie'", // String with spaces + "'A@B#C', 'Alpha @ Bravo # Charlie'", // Special characters + "'A B C 123', 'Alpha Bravo Charlie One Two Three'", // Mixed letters, digits, and spaces + "'a b c', 'Alpha Bravo Charlie'", // Lowercase letters with spaces + "'123!@#', 'One Two Three ! @ #'", // Numbers with special characters + "'HELLO WORLD', 'Hotel Echo Lima Lima Oscar Whiskey Oscar Romeo Lima Delta'" // Words with space }) public void testTextToPhonetic(String input, String expectedOutput) { diff --git a/src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java b/src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java index 87e40c78e6a2..03dbc8c98d8c 100644 --- a/src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java +++ b/src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java @@ -9,20 +9,20 @@ public class TurkishToLatinConversionTest { @ParameterizedTest @CsvSource({ - "'çalışma', 'calisma'", // Turkish to Latin conversion for lowercase - "'ÇALIŞMA', 'CALISMA'", // Turkish to Latin conversion for uppercase - "'İSTANBUL', 'ISTANBUL'", // Special case of 'İ' to 'I' - "'istanbul', 'istanbul'", // Special case of 'ı' to 'i' - "'GÜL', 'GUL'", // Special case of 'Ü' to 'U' - "'gül', 'gul'", // Special case of 'ü' to 'u' - "'ÖĞRENME', 'OGRENME'", // Special case of 'Ö' to 'O' and 'Ğ' to 'G' - "'öğrenme', 'ogrenme'", // Special case of 'ö' to 'o' and 'ğ' to 'g' - "'ŞEHIR', 'SEHIR'", // Special case of 'Ş' to 'S' - "'şehir', 'sehir'", // Special case of 'ş' to 's' - "'HELLO', 'HELLO'", // String with no Turkish characters, should remain unchanged - "'Merhaba Dünya!', 'Merhaba Dunya!'", // Mixed Turkish and Latin characters with punctuation - "'Çift kişilik yataklı odalar', 'Cift kisilik yatakli odalar'", // Full sentence conversion - "'', ''" // Empty string case + "'çalışma', 'calisma'", // Turkish to Latin conversion for lowercase + "'ÇALIŞMA', 'CALISMA'", // Turkish to Latin conversion for uppercase + "'İSTANBUL', 'ISTANBUL'", // Special case of 'İ' to 'I' + "'istanbul', 'istanbul'", // Special case of 'ı' to 'i' + "'GÜL', 'GUL'", // Special case of 'Ü' to 'U' + "'gül', 'gul'", // Special case of 'ü' to 'u' + "'ÖĞRENME', 'OGRENME'", // Special case of 'Ö' to 'O' and 'Ğ' to 'G' + "'öğrenme', 'ogrenme'", // Special case of 'ö' to 'o' and 'ğ' to 'g' + "'ŞEHIR', 'SEHIR'", // Special case of 'Ş' to 'S' + "'şehir', 'sehir'", // Special case of 'ş' to 's' + "'HELLO', 'HELLO'", // String with no Turkish characters, should remain unchanged + "'Merhaba Dünya!', 'Merhaba Dunya!'", // Mixed Turkish and Latin characters with punctuation + "'Çift kişilik yataklı odalar', 'Cift kisilik yatakli odalar'", // Full sentence conversion + "'', ''" // Empty string case }) public void testConvertTurkishToLatin(String input, String expectedOutput) { diff --git a/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java b/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java index 3c4e3d5e4c54..d2400e9120f5 100644 --- a/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java +++ b/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java b/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java index 0952129efb4d..900b5fc8ef84 100644 --- a/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java +++ b/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; + import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java b/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java index b7e64851383c..79e516812006 100644 --- a/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java +++ b/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java @@ -6,7 +6,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.bags.Bag; + import java.util.Iterator; + import org.junit.jupiter.api.Test; class BagTest { diff --git a/src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java b/src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java index f6d19a3e7b20..fe8242336b07 100644 --- a/src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java +++ b/src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; + import org.junit.jupiter.api.Test; class ORSetTest { diff --git a/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java b/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java index 8fdc93e1ca22..20b9766764f2 100644 --- a/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java +++ b/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java @@ -8,6 +8,7 @@ import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.stream.Collectors; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java index dce5a6ed4b69..5df5b2b29373 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,7 +21,7 @@ public void setUp() { ArrayList graphData = new ArrayList<>(Arrays.asList(0, 1, 1, null, 0, 2, 2, null, 1, 3, 1, null, 2, 3, 1, null, 3, 4, 1, null)); AStar.initializeGraph(graph, graphData); - heuristic = new int[] {5, 4, 3, 2, 0}; // Heuristic values for each node + heuristic = new int[]{5, 4, 3, 2, 0}; // Heuristic values for each node } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java index 75fa6adc3014..8433cb32d75f 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; + import org.junit.jupiter.api.Test; public class BipartiteGraphDFSTest { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java index f089169903d6..25f64031e6aa 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java @@ -5,8 +5,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.graphs.BoruvkaAlgorithm.Graph; + import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.Test; public class BoruvkaAlgorithmTest { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java index c5df9acdf33b..5967648cae2f 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java @@ -13,16 +13,16 @@ public class DijkstraAlgorithmTest { @BeforeEach void setUp() { - 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}, + 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}, }; dijkstraAlgorithm = new DijkstraAlgorithm(graph.length); @@ -37,7 +37,7 @@ void testRunAlgorithm() { @Test void testGraphWithDisconnectedNodes() { int[][] disconnectedGraph = { - {0, 3, 0, 0}, {3, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0} // Node 3 is disconnected + {0, 3, 0, 0}, {3, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0} // Node 3 is disconnected }; DijkstraAlgorithm dijkstraDisconnected = new DijkstraAlgorithm(disconnectedGraph.length); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java index aa8e6beeb3db..e47413eea60e 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java @@ -8,11 +8,12 @@ import java.util.Collection; import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** * Unit tests for the EdmondsBlossomAlgorithm class. - * + *

    * These tests ensure that the Edmonds' Blossom Algorithm implementation * works as expected for various graph structures, returning the correct * maximum matching. @@ -46,10 +47,10 @@ private int[][] convertMatchingToArray(Collection matching) { */ @Test public void testCase1() { - List edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 0}); + List edges = Arrays.asList(new int[]{0, 1}, new int[]{1, 2}, new int[]{2, 0}); List matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 3); - int[][] expected = new int[][] {{0, 1}}; + int[][] expected = new int[][]{{0, 1}}; assertArrayEquals(expected, convertMatchingToArray(matching)); } @@ -60,10 +61,10 @@ public void testCase1() { */ @Test public void testCase2() { - List edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {3, 4}); + List edges = Arrays.asList(new int[]{0, 1}, new int[]{1, 2}, new int[]{3, 4}); List matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 5); - int[][] expected = new int[][] {{0, 1}, {3, 4}}; + int[][] expected = new int[][]{{0, 1}, {3, 4}}; assertArrayEquals(expected, convertMatchingToArray(matching)); } @@ -74,11 +75,11 @@ public void testCase2() { */ @Test public void testCase3() { - List edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 0}, new int[] {4, 5}); + List edges = Arrays.asList(new int[]{0, 1}, new int[]{1, 2}, new int[]{2, 3}, new int[]{3, 0}, new int[]{4, 5}); List matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 6); // Updated expected output to include the maximum matching pairs - int[][] expected = new int[][] {{0, 1}, {2, 3}, {4, 5}}; + int[][] expected = new int[][]{{0, 1}, {2, 3}, {4, 5}}; assertArrayEquals(expected, convertMatchingToArray(matching)); } @@ -91,7 +92,7 @@ public void testCaseNoMatching() { List edges = Collections.emptyList(); // No edges List matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 3); - int[][] expected = new int[][] {}; // No pairs expected + int[][] expected = new int[][]{}; // No pairs expected assertArrayEquals(expected, convertMatchingToArray(matching)); } @@ -102,7 +103,7 @@ public void testCaseNoMatching() { */ @Test public void testCaseLargeGraph() { - List edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 4}, new int[] {4, 5}, new int[] {5, 0}, new int[] {1, 4}, new int[] {2, 5}); + List edges = Arrays.asList(new int[]{0, 1}, new int[]{1, 2}, new int[]{2, 3}, new int[]{3, 4}, new int[]{4, 5}, new int[]{5, 0}, new int[]{1, 4}, new int[]{2, 5}); List matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 6); // Check if the size of the matching is correct (i.e., 3 pairs) @@ -110,8 +111,8 @@ public void testCaseLargeGraph() { // Check that the result contains valid pairs (any order is fine) // Valid maximum matchings could be {{0, 1}, {2, 5}, {3, 4}} or {{0, 1}, {2, 3}, {4, 5}}, etc. - int[][] possibleMatching1 = new int[][] {{0, 1}, {2, 5}, {3, 4}}; - int[][] possibleMatching2 = new int[][] {{0, 1}, {2, 3}, {4, 5}}; + int[][] possibleMatching1 = new int[][]{{0, 1}, {2, 5}, {3, 4}}; + int[][] possibleMatching2 = new int[][]{{0, 1}, {2, 3}, {4, 5}}; int[][] result = convertMatchingToArray(matching); // Assert that the result is one of the valid maximum matchings diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java index 7d6a2b239f4b..0b4f242fe4f5 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java @@ -9,7 +9,7 @@ class FloydWarshallTest { @Test void testSmallGraph() { int[][] adjacencyMatrix = {{0, 0, 0, 0}, // Ignored row (0 index) - {0, 0, 3, FloydWarshall.INFINITY}, {0, FloydWarshall.INFINITY, 0, 1}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}}; + {0, 0, 3, FloydWarshall.INFINITY}, {0, FloydWarshall.INFINITY, 0, 1}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}}; FloydWarshall fw = new FloydWarshall(3); fw.floydwarshall(adjacencyMatrix); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java index 4529606d7797..12256ebc78c1 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java @@ -12,11 +12,11 @@ class HamiltonianCycleTest { 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}, + {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)); @@ -27,11 +27,11 @@ 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}, + {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)); @@ -57,11 +57,11 @@ void testDisconnectedGraphShouldReturnInfinityArray() { void testCompleteGraphShouldReturnHamiltonianCycle() { int[] expectedArray = {0, 1, 2, 3, 4, 0}; int[][] inputArray = { - {0, 1, 1, 1, 1}, - {1, 0, 1, 1, 1}, - {1, 1, 0, 1, 1}, - {1, 1, 1, 0, 1}, - {1, 1, 1, 1, 0}, + {0, 1, 1, 1, 1}, + {1, 0, 1, 1, 1}, + {1, 1, 0, 1, 1}, + {1, 1, 1, 0, 1}, + {1, 1, 1, 1, 0}, }; assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); @@ -72,11 +72,11 @@ void testGraphWithNoEdgesShouldReturnInfinityArray() { int[] expectedArray = {-1, -1, -1, -1, -1, -1}; int[][] inputArray = { - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, }; assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); @@ -86,11 +86,11 @@ void testGraphWithNoEdgesShouldReturnInfinityArray() { void testLargeGraphWithHamiltonianCycle() { int[] expectedArray = {0, 1, 2, 3, 4, 0}; int[][] inputArray = { - {0, 1, 0, 1, 1}, - {1, 0, 1, 1, 0}, - {0, 1, 0, 1, 1}, - {1, 1, 1, 0, 1}, - {1, 0, 1, 1, 0}, + {0, 1, 0, 1, 1}, + {1, 0, 1, 1, 0}, + {0, 1, 0, 1, 1}, + {1, 1, 1, 0, 1}, + {1, 0, 1, 1, 0}, }; assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java index 8d096a4b4459..a05f4ecb44fc 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; + import org.junit.jupiter.api.Test; class KahnsAlgorithmTest { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java index 53ed26dff26f..1ee6081b3781 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class KosarajuTest { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java index b18f161ef1a6..c8e597143649 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java index cc8a2df872ce..bef95674f68c 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; class MatrixGraphsTest { @@ -99,9 +100,9 @@ void testToString() { graph.addEdge(1, 2); String expected = " 0 1 2 \n" - + "0 : 0 1 0 \n" - + "1 : 1 0 1 \n" - + "2 : 0 1 0 \n"; + + "0 : 0 1 0 \n" + + "1 : 1 0 1 \n" + + "2 : 0 1 0 \n"; assertEquals(expected, graph.toString()); } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java index 314cc415815d..db7e9851c702 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class TarjansAlgorithmTest { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java index f45c4e10be56..358333f4c9f3 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java @@ -5,14 +5,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.graphs.WelshPowell.Graph; + import java.util.Arrays; + import org.junit.jupiter.api.Test; class WelshPowellTest { @Test void testSimpleGraph() { - final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); + final var graph = WelshPowell.makeGraph(4, new int[][]{{0, 1}, {1, 2}, {2, 3}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(2, countDistinctColors(colors)); @@ -20,7 +22,7 @@ void testSimpleGraph() { @Test void testDisconnectedGraph() { - final var graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges + final var graph = WelshPowell.makeGraph(3, new int[][]{}); // No edges int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(1, countDistinctColors(colors)); @@ -28,7 +30,7 @@ void testDisconnectedGraph() { @Test void testCompleteGraph() { - final var graph = WelshPowell.makeGraph(3, new int[][] {{0, 1}, {1, 2}, {2, 0}}); + final var graph = WelshPowell.makeGraph(3, new int[][]{{0, 1}, {1, 2}, {2, 0}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(3, countDistinctColors(colors)); @@ -37,22 +39,22 @@ void testCompleteGraph() { @Test void testComplexGraph() { int[][] edges = { - {0, 7}, - {0, 1}, - {1, 3}, - {2, 3}, - {3, 8}, - {3, 10}, - {4, 10}, - {4, 5}, - {5, 6}, - {6, 10}, - {6, 7}, - {7, 8}, - {7, 9}, - {7, 10}, - {8, 9}, - {9, 10}, + {0, 7}, + {0, 1}, + {1, 3}, + {2, 3}, + {3, 8}, + {3, 10}, + {4, 10}, + {4, 5}, + {5, 6}, + {6, 10}, + {6, 7}, + {7, 8}, + {7, 9}, + {7, 10}, + {8, 9}, + {9, 10}, }; final var graph = WelshPowell.makeGraph(11, edges); // 11 vertices from A (0) to K (10) @@ -64,28 +66,38 @@ void testComplexGraph() { @Test void testNegativeVertices() { - assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(-1, new int[][] {}); }, "Number of vertices cannot be negative"); + assertThrows(IllegalArgumentException.class, () -> { + WelshPowell.makeGraph(-1, new int[][]{}); + }, "Number of vertices cannot be negative"); } @Test void testSelfLoop() { - assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 0}}); }, "Self-loops are not allowed"); + assertThrows(IllegalArgumentException.class, () -> { + WelshPowell.makeGraph(3, new int[][]{{0, 0}}); + }, "Self-loops are not allowed"); } @Test void testInvalidVertex() { - assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 3}}); }, "Vertex out of bounds"); - assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, -1}}); }, "Vertex out of bounds"); + assertThrows(IllegalArgumentException.class, () -> { + WelshPowell.makeGraph(3, new int[][]{{0, 3}}); + }, "Vertex out of bounds"); + assertThrows(IllegalArgumentException.class, () -> { + WelshPowell.makeGraph(3, new int[][]{{0, -1}}); + }, "Vertex out of bounds"); } @Test void testInvalidEdgeArray() { - assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0}}); }, "Edge array must have exactly two elements"); + assertThrows(IllegalArgumentException.class, () -> { + WelshPowell.makeGraph(3, new int[][]{{0}}); + }, "Edge array must have exactly two elements"); } @Test void testWithPreColoredVertex() { - final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); + final var graph = WelshPowell.makeGraph(4, new int[][]{{0, 1}, {1, 2}, {2, 3}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertTrue(countDistinctColors(colors) >= 2); diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java index df6d15fd9ba4..bf83ba41f72b 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.Test; public class IntersectionTest { diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java index 7dcd5eb7a8f4..dafbe69f9b06 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; public class MajorityElementTest { diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java index 44551a8adac6..bc5a1a982063 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; + import org.junit.jupiter.api.Test; abstract class MapTest { diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java index d911f3ac30d8..540b4c91ddfc 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java @@ -91,7 +91,9 @@ void testInsertNegativeKeys() { @Test void testDeleteOnEmptyHeap() { FibonacciHeap fibonacciHeap = new FibonacciHeap(); - Assertions.assertThrows(NullPointerException.class, () -> { fibonacciHeap.delete(fibonacciHeap.findMin()); }); + Assertions.assertThrows(NullPointerException.class, () -> { + fibonacciHeap.delete(fibonacciHeap.findMin()); + }); } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java index 8915a6d8aef2..730ffaa8b6e6 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java @@ -121,6 +121,8 @@ public void testGenericHeapRemoveUntilEmpty() { @Test public void testGenericHeapAddNullItem() { // Check null item - assertThrows(IllegalArgumentException.class, () -> { heap.add(null); }); + assertThrows(IllegalArgumentException.class, () -> { + heap.add(null); + }); } } diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java index c9b754619286..ad182bcbe484 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,25 +18,25 @@ public void testMergeKArrays(int[][] arrays, int[] expected) { private static Stream provideTestCases() { return Stream.of( - // Basic test case with multiple arrays - Arguments.of(new int[][] {{1, 4, 5}, {1, 3, 4}, {2, 6}}, new int[] {1, 1, 2, 3, 4, 4, 5, 6}), + // Basic test case with multiple arrays + Arguments.of(new int[][]{{1, 4, 5}, {1, 3, 4}, {2, 6}}, new int[]{1, 1, 2, 3, 4, 4, 5, 6}), - // Edge case: All arrays are empty - Arguments.of(new int[][] {{}, {}, {}}, new int[] {}), + // Edge case: All arrays are empty + Arguments.of(new int[][]{{}, {}, {}}, new int[]{}), - // Edge case: One array is empty - Arguments.of(new int[][] {{1, 3, 5}, {}, {2, 4, 6}}, new int[] {1, 2, 3, 4, 5, 6}), + // Edge case: One array is empty + Arguments.of(new int[][]{{1, 3, 5}, {}, {2, 4, 6}}, new int[]{1, 2, 3, 4, 5, 6}), - // Single array - Arguments.of(new int[][] {{1, 2, 3}}, new int[] {1, 2, 3}), + // Single array + Arguments.of(new int[][]{{1, 2, 3}}, new int[]{1, 2, 3}), - // Arrays with negative numbers - Arguments.of(new int[][] {{-5, 1, 3}, {-10, 0, 2}}, new int[] {-10, -5, 0, 1, 2, 3}), + // Arrays with negative numbers + Arguments.of(new int[][]{{-5, 1, 3}, {-10, 0, 2}}, new int[]{-10, -5, 0, 1, 2, 3}), - // Arrays with duplicate elements - Arguments.of(new int[][] {{1, 1, 2}, {1, 3, 3}, {2, 2, 4}}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 4}), + // Arrays with duplicate elements + Arguments.of(new int[][]{{1, 1, 2}, {1, 3, 3}, {2, 2, 4}}, new int[]{1, 1, 1, 2, 2, 2, 3, 3, 4}), - // Edge case: Arrays of varying lengths - Arguments.of(new int[][] {{1, 2}, {3}, {4, 5, 6, 7}}, new int[] {1, 2, 3, 4, 5, 6, 7})); + // Edge case: Arrays of varying lengths + Arguments.of(new int[][]{{1, 2}, {3}, {4, 5, 6, 7}}, new int[]{1, 2, 3, 4, 5, 6, 7})); } } diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java index 1c2caf54cdb1..35b76b9901f8 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java index 8f93bd630aa7..a0038b9332e8 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java @@ -61,7 +61,7 @@ void testHeapSort() { sortedArray[i] = queue.delete(); } - Assertions.assertArrayEquals(new int[] {1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order."); + Assertions.assertArrayEquals(new int[]{1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order."); } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java index 99a890112d31..7e6fd41b3da0 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java @@ -4,7 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertNull; import com.thealgorithms.datastructures.lists.MergeKSortedLinkedList.Node; + import java.util.Arrays; + import org.junit.jupiter.api.Test; class MergeKSortedLinkedListTest { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java index 5483bbcd0394..a5bfdf212cbb 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; class MergeSortedArrayListTest { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java index e7e3cca4083f..b2db478f692c 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; + /** * Test cases for Reverse K Group LinkedList * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) diff --git a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java index 70c0dfccafa4..10a3ce4b92eb 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java @@ -59,7 +59,7 @@ public void testRotateRightSingleNodeList() { @Test public void testRotateRightMultipleElementsList() { // Rotate a list with multiple elements (rotate by 2) - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5}); Node rotated = rotator.rotateRight(head, 2); assertEquals("4 -> 5 -> 1 -> 2 -> 3", linkedListToString(rotated)); } @@ -67,7 +67,7 @@ public void testRotateRightMultipleElementsList() { @Test public void testRotateRightFullRotation() { // Rotate by more than the length of the list - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5}); Node rotated = rotator.rotateRight(head, 7); assertEquals("4 -> 5 -> 1 -> 2 -> 3", linkedListToString(rotated)); } @@ -75,7 +75,7 @@ public void testRotateRightFullRotation() { @Test public void testRotateRightZeroRotation() { // Rotate a list by k = 0 (no rotation) - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5}); Node rotated = rotator.rotateRight(head, 0); assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated)); } @@ -83,14 +83,14 @@ public void testRotateRightZeroRotation() { @Test public void testRotateRightByListLength() { // Rotate a list by k equal to list length (no change) - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5}); Node rotated = rotator.rotateRight(head, 5); assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated)); } @Test public void testRotateRightByMultipleOfListLength() { - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5}); Node rotated = rotator.rotateRight(head, 10); // k = 2 * list length assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated)); } @@ -98,7 +98,7 @@ public void testRotateRightByMultipleOfListLength() { @Test public void testRotateRightLongerList() { // Rotate a longer list by a smaller k - Node head = createLinkedList(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}); + Node head = createLinkedList(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}); Node rotated = rotator.rotateRight(head, 4); assertEquals("6 -> 7 -> 8 -> 9 -> 1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated)); } diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java index a47434083cdb..22fa42cb6480 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java @@ -8,12 +8,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class SinglyLinkedListTest { /** * Initialize a list with natural order values with pre-defined length + * * @param length * @return linked list with pre-defined number of nodes */ @@ -102,6 +104,7 @@ void deleteNth() { list.deleteNth(6); // Index 6 has value 7 assertFalse(list.search(7)); } + // Test to check whether the method reverseList() works fine @Test void reverseList() { @@ -164,6 +167,7 @@ void reverseListTest() { i--; } } + // This is Recursive Reverse List Test // Test to check whether the method reverseListRec() works fine void recursiveReverseList() { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java index c572739ffbbf..2982a7e94ea8 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.stream.IntStream; + import org.junit.jupiter.api.Test; class SkipListTest { @@ -75,25 +76,25 @@ void checkSortedOnLowestLayer() { 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", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", }; Arrays.stream(values).forEach(skipList::add); return skipList; @@ -102,6 +103,7 @@ private SkipList createSkipList() { /** * Print Skip List representation to console. * Optional method not involved in testing process. Used only for visualisation purposes. + * * @param skipList to print */ private void print(SkipList skipList) { diff --git a/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java b/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java index 1244a2e260d2..e6390ca09e0b 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.NoSuchElementException; + import org.junit.jupiter.api.Test; class DequeTest { diff --git a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java index 157d771b5a80..ab15af3b2f08 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java @@ -6,6 +6,7 @@ import java.util.Iterator; import java.util.NoSuchElementException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java b/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java index 87f136a84631..07c1eb0f3bb7 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.NoSuchElementException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java b/src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java index e435f9192a88..6aaf04555281 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,34 +18,34 @@ public void testMaxSlidingWindow(int[] nums, int k, int[] expected) { private static Stream provideTestCases() { return Stream.of( - // Test case 1: Example from the problem statement - Arguments.of(new int[] {1, 3, -1, -3, 5, 3, 6, 7}, 3, new int[] {3, 3, 5, 5, 6, 7}), + // Test case 1: Example from the problem statement + Arguments.of(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3, new int[]{3, 3, 5, 5, 6, 7}), - // Test case 2: All elements are the same - Arguments.of(new int[] {4, 4, 4, 4, 4}, 2, new int[] {4, 4, 4, 4}), + // Test case 2: All elements are the same + Arguments.of(new int[]{4, 4, 4, 4, 4}, 2, new int[]{4, 4, 4, 4}), - // Test case 3: Window size equals the array length - Arguments.of(new int[] {2, 1, 5, 3, 6}, 5, new int[] {6}), + // Test case 3: Window size equals the array length + Arguments.of(new int[]{2, 1, 5, 3, 6}, 5, new int[]{6}), - // Test case 4: Single element array with window size 1 - Arguments.of(new int[] {7}, 1, new int[] {7}), + // Test case 4: Single element array with window size 1 + Arguments.of(new int[]{7}, 1, new int[]{7}), - // Test case 5: Window size larger than the array length - Arguments.of(new int[] {1, 2, 3}, 4, new int[] {}), + // Test case 5: Window size larger than the array length + Arguments.of(new int[]{1, 2, 3}, 4, new int[]{}), - // Test case 6: Decreasing sequence - Arguments.of(new int[] {9, 8, 7, 6, 5, 4}, 3, new int[] {9, 8, 7, 6}), + // Test case 6: Decreasing sequence + Arguments.of(new int[]{9, 8, 7, 6, 5, 4}, 3, new int[]{9, 8, 7, 6}), - // Test case 7: Increasing sequence - Arguments.of(new int[] {1, 2, 3, 4, 5}, 2, new int[] {2, 3, 4, 5}), + // Test case 7: Increasing sequence + Arguments.of(new int[]{1, 2, 3, 4, 5}, 2, new int[]{2, 3, 4, 5}), - // Test case 8: k is zero - Arguments.of(new int[] {1, 3, -1, -3, 5, 3, 6, 7}, 0, new int[] {}), + // Test case 8: k is zero + Arguments.of(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 0, new int[]{}), - // Test case 9: Array with negative numbers - Arguments.of(new int[] {-4, -2, -5, -1, -3}, 3, new int[] {-2, -1, -1}), + // Test case 9: Array with negative numbers + Arguments.of(new int[]{-4, -2, -5, -1, -3}, 3, new int[]{-2, -1, -1}), - // Test case 10: Empty array - Arguments.of(new int[] {}, 3, new int[] {})); + // Test case 10: Empty array + Arguments.of(new int[]{}, 3, new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java b/src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java index 2e2bc5adae3a..9e6a223be24e 100644 --- a/src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java +++ b/src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Stack; + import org.junit.jupiter.api.Test; class ReverseStackTest { diff --git a/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java b/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java index c8811bb3ccc2..f6e128acdac2 100644 --- a/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.datastructures.stacks; import java.util.EmptyStackException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java index 58af66bc38f4..9ef897790c4b 100644 --- a/src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.NoSuchElementException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java index aab3b82c45eb..83458f6f8d79 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java @@ -15,19 +15,19 @@ public void testNullArray() { @Test public void testEmptyArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{}); Assertions.assertNull(actualBST); } @Test public void testSingleElementArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {Integer.MIN_VALUE}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{Integer.MIN_VALUE}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } @Test public void testCreateBSTFromSmallArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {1, 2, 3}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{1, 2, 3}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java index b153c5d667de..d2ccf90d6704 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java @@ -1,13 +1,12 @@ package com.thealgorithms.datastructures.trees; -import static org.junit.jupiter.api.Assertions.assertEquals; - import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; -public class BinaryTreeTest { +public +class BinaryTreeTest { - // checks that adding populating the tree and searching for data - // retrieves the expected data + // Test for adding elements and finding data within the tree @Test void test1() { BinaryTree t = new BinaryTree(); @@ -17,12 +16,15 @@ void test1() { t.put(9); t.put(12); - assertEquals(t.find(5).data, 5); - assertEquals(t.find(7).data, 7); + Assertions.assertNotNull(t.find(5), + "Node with value 5 should exist in the tree."); + Assertions.assertEquals(5, t.find(5).data); + + Assertions.assertNotNull(t.find(7), + "Node with value 7 should exist in the tree."); + Assertions.assertEquals(7, t.find(7).data); } - // checks that removing data from the tree - // properly removes and makes the new root the expected new root @Test void test2() { BinaryTree t = new BinaryTree(); @@ -31,15 +33,27 @@ void test2() { t.put(7); t.put(9); t.put(12); + + // Perform removals and check the new root t.remove(3); t.remove(5); t.remove(7); - assertEquals(t.getRoot().data, 9); + BinaryTree.Node root = t.getRoot(); + + // Check the size of the tree to confirm it has remaining nodes + Assertions.assertEquals(2, t.size(), + "Tree should have 2 nodes left after removals."); + + // Check if new root is correct + if (root != null) { + Assertions.assertEquals(9, root.data); + } else { + Assertions.fail("Root is null after removals."); + } } - // checks that removing an unexistend node returns false - // as specified by the documentation of the function + // Test for attempting to remove a nonexistent node @Test void test3() { BinaryTree t = new BinaryTree(); @@ -49,13 +63,12 @@ void test3() { t.put(9); t.put(12); - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); + Assertions.assertTrue(t.remove(9), "Node with value 9 should be removed."); + Assertions.assertFalse(t.remove(398745987), + "Removing a nonexistent node should return false."); } - // check if the bfs, inOrder, preOrder and postOrder functions - // worg as expected, also increases the coverage measures in - // JaCoCo + // Test traversal methods (bfs, inOrder, preOrder, postOrder) @Test void test4() { BinaryTree t = new BinaryTree(); @@ -65,12 +78,28 @@ void test4() { t.put(9); t.put(12); - t.bfs(t.find(12)); - t.inOrder(t.getRoot()); - t.preOrder(t.getRoot()); - t.postOrder(t.getRoot()); + // Ensure root is not null before traversal + Assertions.assertNotNull(t.getRoot(), + "Root should not be null for traversal."); + + // Invoke traversal methods to increase test coverage + System.out.println("BFS Traversal:"); + t.bfs(); // No need to pass the root, just call the method + + System.out.print("In-Order Traversal: "); + t.inOrder(t.getRoot()); // In-Order + + System.out.print("Pre-Order Traversal: "); + t.preOrder(t.getRoot()); // Pre-Order + + System.out.print("Post-Order Traversal: "); + t.postOrder(t.getRoot()); // Post-Order + + System.out.println(); // For a new line after traversals - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); + // Additional assertions + Assertions.assertTrue(t.remove(9), "Node with value 9 should be removed."); + Assertions.assertFalse(t.remove(398745987), + "Removing a nonexistent node should return false."); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java index 515dac88ce09..ee928277d048 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -37,7 +38,7 @@ public void testSingleNodeTree() { */ @Test public void testCompleteBinaryTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); List expected = List.of(1, 2, 4, 5, 6, 7, 3); @@ -60,7 +61,7 @@ public void testCompleteBinaryTree() { */ @Test public void testBoundaryTraversal() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 7, 3, null, null, 8, null, 4, 9, null, 5, 6, 10, 11}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 7, 3, null, null, 8, null, 4, 9, null, 5, 6, 10, 11}); List expected = List.of(1, 2, 3, 4, 5, 6, 10, 11, 9, 8, 7); @@ -79,7 +80,7 @@ public void testBoundaryTraversal() { */ @Test public void testLeftSkewedTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3, null, 4, null}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, null, 3, null, 4, null}); List expected = List.of(1, 2, 3, 4); @@ -98,7 +99,7 @@ public void testLeftSkewedTree() { */ @Test public void testRightSkewedTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java index 779c68137e42..56a89ea0f5fb 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java @@ -15,37 +15,37 @@ public void testRootNull() { @Test public void testKeyPresentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 100).data); } @Test public void testKeyPresentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); assertEquals(10, CeilInBinarySearchTree.getCeil(root, 10).data); } @Test public void testKeyAbsentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 75).data); } @Test public void testKeyAbsentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); assertEquals(50, CeilInBinarySearchTree.getCeil(root, 40).data); } @Test public void testKeyAbsentLeftMostNodeIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); assertEquals(5, CeilInBinarySearchTree.getCeil(root, 1).data); } @Test public void testKeyAbsentCeilIsNull() { - final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); assertNull(CeilInBinarySearchTree.getCeil(root, 400)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java index bf7b946143f9..5be2ab4597ff 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java @@ -16,7 +16,7 @@ public void testRootNull() { @Test public void testOneNode() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{Integer.MIN_VALUE}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -29,7 +29,7 @@ public void testOneNode() { */ @Test public void testBinaryTreeIsBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 20}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -42,7 +42,7 @@ public void testBinaryTreeIsBST() { */ @Test public void testBinaryTreeWithDuplicatedNodesIsNotBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 13}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 13}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -55,7 +55,7 @@ public void testBinaryTreeWithDuplicatedNodesIsNotBST() { */ @Test public void testBinaryTreeIsNotBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 12}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 12}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java index 0eb234d618ed..8c9ef0e854d2 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java @@ -19,7 +19,7 @@ public void testRootNull() { @Test public void testOneNode() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{Integer.MIN_VALUE}); assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root)); assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root)); } @@ -33,7 +33,7 @@ public void testOneNode() { */ @Test public void testBinaryTreeIsBalancedEqualSubtreeHeights() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 20}); assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root)); assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root)); } @@ -47,7 +47,7 @@ public void testBinaryTreeIsBalancedEqualSubtreeHeights() { */ @Test public void testBinaryTreeIsBalancedWithDifferentHeights() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8}); assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root)); assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root)); } @@ -61,7 +61,7 @@ public void testBinaryTreeIsBalancedWithDifferentHeights() { */ @Test public void testBinaryTreeNotBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, null, 3, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, null, 3, 8}); assertFalse(CheckIfBinaryTreeBalanced.isBalancedRecursive(root)); assertFalse(CheckIfBinaryTreeBalanced.isBalancedIterative(root)); } @@ -77,7 +77,7 @@ public void testBinaryTreeNotBalanced() { */ @Test public void testBinaryTreeNotBalancedBecauseLeftTreeNotBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, null, null, 11}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, null, null, 11}); assertFalse(CheckIfBinaryTreeBalanced.isBalancedRecursive(root)); assertFalse(CheckIfBinaryTreeBalanced.isBalancedIterative(root)); } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java index a610a32aa91f..afe6c5c3c2d2 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java @@ -17,19 +17,19 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 4, 4, 3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 2, 3, 4, 4, 3}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testNonSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 5, 4, 3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 2, 3, 5, 4, 3}); assertFalse(CheckTreeIsSymmetric.isSymmetric(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java index 10f7aa667230..13abf2fba137 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.datastructures.trees; import java.util.Arrays; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java index e65beb891606..698cbe16f255 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -25,7 +26,7 @@ public void testNullRoot() { */ @Test public void testRecursiveInorder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); List expected = List.of(4, 2, 5, 1, 6, 3, 7); assertEquals(expected, InorderTraversal.recursiveInorder(root)); @@ -43,7 +44,7 @@ public void testRecursiveInorder() { */ @Test public void testRecursiveInorderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, InorderTraversal.recursiveInorder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java index 49babb033e81..e0111a2d3e53 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java @@ -7,18 +7,18 @@ 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); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java index ee807bccc5f1..5df7c73cfff3 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -17,7 +18,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); assertEquals(List.of(List.of(50)), LevelOrderTraversal.traverse(root)); } @@ -30,7 +31,7 @@ public void testSingleNodeTree() { */ @Test public void testLevelOrderTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), LevelOrderTraversal.traverse(root)); } @@ -45,7 +46,7 @@ public void testLevelOrderTraversalCompleteTree() { */ @Test public void testLevelOrderTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7), List.of(8, 9)), LevelOrderTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java index 3acc7f07c087..effb28b7f526 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -27,7 +28,7 @@ public void testNullRoot() { */ @Test public void testPostOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); List expected = List.of(4, 5, 2, 6, 7, 3, 1); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); @@ -45,7 +46,7 @@ public void testPostOrder() { */ @Test public void testPostOrderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); List expected = List.of(8, 7, 6, 5); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java index b194da01485b..c46f7a142639 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -25,7 +26,7 @@ public void testNullRoot() { */ @Test public void testRecursivePreOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); List expected = List.of(1, 2, 4, 5, 3, 6, 7); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); @@ -43,7 +44,7 @@ public void testRecursivePreOrder() { */ @Test public void testRecursivePreOrderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java index 62b86da214db..7ebe77a5f8d3 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.datastructures.trees; import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java index 440222880517..c6ab94304a93 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java @@ -16,14 +16,14 @@ public void testBothRootsAreNull() { @Test public void testOneRootIsNull() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); assertFalse(SameTreesCheck.check(root, null)); } @Test public void testSingleNodeTreesAreSame() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {100}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {100}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{100}); assertTrue(SameTreesCheck.check(p, q)); } @@ -36,8 +36,8 @@ public void testSingleNodeTreesAreSame() { */ @Test public void testSameTreesIsSuccessful() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); assertTrue(SameTreesCheck.check(p, q)); } @@ -50,8 +50,8 @@ public void testSameTreesIsSuccessful() { */ @Test public void testSameTreesFails() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6}); assertFalse(SameTreesCheck.check(p, q)); } @@ -62,8 +62,8 @@ public void testSameTreesFails() { */ @Test public void testTreesWithDifferentStructure() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, null, 2}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, null, 2}); assertFalse(SameTreesCheck.check(p, q)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java index d520be94e7f3..8a9ed5b70aaa 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java @@ -8,6 +8,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -74,8 +75,8 @@ public void testSearchInEmptyTree(int value) { } private static Stream traversalStrategies() { - return Stream.of(new Object[] {SplayTree.IN_ORDER, Arrays.asList(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90)}, new Object[] {SplayTree.PRE_ORDER, Arrays.asList(15, 5, 10, 80, 70, 45, 25, 20, 35, 30, 40, 55, 50, 65, 60, 75, 90, 85)}, - new Object[] {SplayTree.POST_ORDER, Arrays.asList(10, 5, 20, 30, 40, 35, 25, 50, 60, 65, 55, 45, 75, 70, 85, 90, 80, 15)}); + return Stream.of(new Object[]{SplayTree.IN_ORDER, Arrays.asList(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90)}, new Object[]{SplayTree.PRE_ORDER, Arrays.asList(15, 5, 10, 80, 70, 45, 25, 20, 35, 30, 40, 55, 50, 65, 60, 75, 90, 85)}, + new Object[]{SplayTree.POST_ORDER, Arrays.asList(10, 5, 20, 30, 40, 35, 25, 50, 60, 65, 55, 45, 75, 70, 85, 90, 80, 15)}); } private static Stream valuesToTest() { diff --git a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java index 9628e86b9bff..f2472a91f18a 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java @@ -1,6 +1,7 @@ package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; + import java.util.LinkedList; import java.util.Queue; diff --git a/src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java b/src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java index 9348118bb343..0898e131b1c0 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java index cc89c9813fa8..b5529283ad9f 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -17,7 +18,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); assertEquals(List.of(50), VerticalOrderTraversal.verticalTraversal(root)); } @@ -30,7 +31,7 @@ public void testSingleNodeTree() { */ @Test public void testVerticalTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); assertEquals(List.of(4, 2, 1, 5, 6, 3, 7), VerticalOrderTraversal.verticalTraversal(root)); } @@ -45,7 +46,7 @@ public void testVerticalTraversalCompleteTree() { */ @Test public void testVerticalTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); assertEquals(List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java index eb5c0e3ce4df..32ce124cf240 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.List; + import org.junit.jupiter.api.Test; /** @@ -17,7 +18,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); assertEquals(List.of(List.of(50)), ZigzagTraversal.traverse(root)); } @@ -30,7 +31,7 @@ public void testSingleNodeTree() { */ @Test public void testZigzagTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), ZigzagTraversal.traverse(root)); } @@ -45,7 +46,7 @@ public void testZigzagTraversalCompleteTree() { */ @Test public void testZigzagTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7), List.of(9, 8)), ZigzagTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java b/src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java index 38784228d68e..6ca0dd1b183e 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java @@ -68,7 +68,7 @@ public void testBruteForce() { ClosestPair.Location loc1 = cp.buildLocation(1.0, 2.0); ClosestPair.Location loc2 = cp.buildLocation(4.0, 6.0); - ClosestPair.Location[] locations = new ClosestPair.Location[] {loc1, loc2}; + ClosestPair.Location[] locations = new ClosestPair.Location[]{loc1, loc2}; double result = cp.bruteForce(locations); assertEquals(5.0, result, 0.01); } diff --git a/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java b/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java index 6cfbc2379600..e5b7d8dbb305 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,25 +18,25 @@ void testFindMedianSortedArrays(int[] nums1, int[] nums2, double expectedMedian) private static Stream provideTestCases() { return Stream.of( - // Test case 1: Arrays of equal length - Arguments.of(new int[] {1, 3}, new int[] {2, 4}, 2.5), + // Test case 1: Arrays of equal length + Arguments.of(new int[]{1, 3}, new int[]{2, 4}, 2.5), - // Test case 2: Arrays of different lengths - Arguments.of(new int[] {1, 3}, new int[] {2}, 2.0), + // Test case 2: Arrays of different lengths + Arguments.of(new int[]{1, 3}, new int[]{2}, 2.0), - // Test case 3: Arrays with even total length - Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5, 6, 7}, 4.5), + // Test case 3: Arrays with even total length + Arguments.of(new int[]{1, 2, 8}, new int[]{3, 4, 5, 6, 7}, 4.5), - // Test case 4: Arrays with odd total length - Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5}, 3.5), + // Test case 4: Arrays with odd total length + Arguments.of(new int[]{1, 2, 8}, new int[]{3, 4, 5}, 3.5), - // Test case 5: Single element arrays - Arguments.of(new int[] {1}, new int[] {3}, 2.0), + // Test case 5: Single element arrays + Arguments.of(new int[]{1}, new int[]{3}, 2.0), - // Test case 6: Empty arrays - Arguments.of(new int[] {}, new int[] {0}, 0.0), + // Test case 6: Empty arrays + Arguments.of(new int[]{}, new int[]{0}, 0.0), - // Test case 7: Same element arrays - Arguments.of(new int[] {2, 2, 2}, new int[] {2, 2, 2}, 2.0)); + // Test case 7: Same element arrays + Arguments.of(new int[]{2, 2, 2}, new int[]{2, 2, 2}, 2.0)); } } diff --git a/src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java b/src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java index f85515110b70..4d72c05185b3 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java index 1ec45a863e1a..62ac504331be 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java @@ -30,7 +30,6 @@ void strassenMatrixMultiplicationTest4x4() { } @Test - void strassenMatrixMultiplicationTestNegetiveNumber4x4() { int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] b = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}}; diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java index 4e36edbd7774..f02eac70eb48 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,28 +18,28 @@ public void testAbbreviation(String a, String b, boolean expected) { private static Stream provideTestCases() { return Stream.of( - // Example test case from problem description - Arguments.of("daBcd", "ABC", Boolean.TRUE), + // Example test case from problem description + Arguments.of("daBcd", "ABC", Boolean.TRUE), - // Test case where transformation is impossible - Arguments.of("dBcd", "ABC", Boolean.FALSE), + // Test case where transformation is impossible + Arguments.of("dBcd", "ABC", Boolean.FALSE), - // Test case with exact match (all uppercase) - Arguments.of("ABC", "ABC", Boolean.TRUE), + // Test case with exact match (all uppercase) + Arguments.of("ABC", "ABC", Boolean.TRUE), - // Test case where input string contains all required letters plus extra lowercase letters - Arguments.of("aAbBcC", "ABC", Boolean.TRUE), + // Test case where input string contains all required letters plus extra lowercase letters + Arguments.of("aAbBcC", "ABC", Boolean.TRUE), - // Test case with only lowercase letters in input - Arguments.of("abcd", "ABCD", Boolean.TRUE), + // Test case with only lowercase letters in input + Arguments.of("abcd", "ABCD", Boolean.TRUE), - // Test case with an empty second string (b) - Arguments.of("abc", "", Boolean.TRUE), + // Test case with an empty second string (b) + Arguments.of("abc", "", Boolean.TRUE), - // Test case with an empty first string (a) but non-empty second string (b) - Arguments.of("", "A", Boolean.FALSE), + // Test case with an empty first string (a) but non-empty second string (b) + Arguments.of("", "A", Boolean.FALSE), - // Complex case with interleaved letters - Arguments.of("daBcAbCd", "ABCD", Boolean.FALSE)); + // Complex case with interleaved letters + Arguments.of("daBcAbCd", "ABCD", Boolean.FALSE)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/AllConstructTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/AllConstructTest.java index 4979327fbf2c..82b23fadfbd9 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/AllConstructTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/AllConstructTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class AllConstructTest { diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java index 0258f3950510..bed7920b2b97 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public final class AssignmentUsingBitmaskTest { diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java index a704620e92da..1e9b84bede33 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java index 4aa412731a10..906322283253 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java @@ -12,7 +12,7 @@ public class BoundaryFillTest { @BeforeEach void setUp() { - image = new int[][] {{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}}; + image = new int[][]{{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}}; } @Test diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java index 166e20c3083f..01138d6c2a95 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java @@ -81,9 +81,17 @@ void testFibBinet() { @Test void testNegativeInput() { // Test negative input; Fibonacci is not defined for negative numbers - assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibMemo(-1); }); - assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibBotUp(-1); }); - assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibOptimized(-1); }); - assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibBinet(-1); }); + assertThrows(IllegalArgumentException.class, () -> { + Fibonacci.fibMemo(-1); + }); + assertThrows(IllegalArgumentException.class, () -> { + Fibonacci.fibBotUp(-1); + }); + assertThrows(IllegalArgumentException.class, () -> { + Fibonacci.fibOptimized(-1); + }); + assertThrows(IllegalArgumentException.class, () -> { + Fibonacci.fibBinet(-1); + }); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java index e26606ef98a9..c9a7c0d12e65 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java @@ -39,7 +39,7 @@ void testMaxSumWithSingleElement() { assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); // Test with a single negative element - input = new int[] {-10}; + input = new int[]{-10}; expectedMaxSum = -10; // max subarray is the single element assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); } @@ -56,6 +56,8 @@ void testMaxSumWithZero() { void testMaxSumWithEmptyArray() { // Test with an empty array; should ideally throw an exception or return false int[] input = {}; - assertThrows(ArrayIndexOutOfBoundsException.class, () -> { KadaneAlgorithm.maxSum(input, 0); }); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + KadaneAlgorithm.maxSum(input, 0); + }); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java index 3545eb2667ed..df5839bdaa32 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java @@ -39,6 +39,7 @@ void test4() { int capacity = 0; assertEquals(0, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } + @Test void test5() { int[] weight = {1, 2, 3, 8}; diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java index 3ff733db7e15..066ed773576a 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java @@ -51,7 +51,9 @@ public void testKnapSackThrowsForInputsOfDifferentLength() { int[] weights = {2, 3, 4}; int[] values = {3, 4, 5, 6}; // Different length values array. int weightCapacity = 5; - assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); }); + assertThrows(IllegalArgumentException.class, () -> { + Knapsack.knapSack(weightCapacity, weights, values); + }); } @Test @@ -59,8 +61,12 @@ public void testKnapSackThrowsForNullInputs() { int[] weights = {2, 3, 4}; int[] values = {3, 4, 6}; int weightCapacity = 5; - assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, null, values); }); - assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, null); }); + assertThrows(IllegalArgumentException.class, () -> { + Knapsack.knapSack(weightCapacity, null, values); + }); + assertThrows(IllegalArgumentException.class, () -> { + Knapsack.knapSack(weightCapacity, weights, null); + }); } @Test @@ -68,7 +74,9 @@ public void testKnapSackThrowsForNegativeCapacity() { int[] weights = {2, 3, 4, 5}; int[] values = {3, 4, 5, 6}; int weightCapacity = -5; - assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); }); + assertThrows(IllegalArgumentException.class, () -> { + Knapsack.knapSack(weightCapacity, weights, values); + }); } @Test @@ -76,6 +84,8 @@ public void testKnapSackThrowsForNegativeWeight() { int[] weights = {2, 0, 4}; int[] values = {3, 4, 6}; int weightCapacity = 5; - assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); }); + assertThrows(IllegalArgumentException.class, () -> { + Knapsack.knapSack(weightCapacity, weights, values); + }); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java index ad4c4c7c53e0..d48b279106cc 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.function.ToIntBiFunction; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -23,19 +24,19 @@ public void testLevenshteinDistance(final int expected, final String str1, final private static Stream testCases() { final Object[][] testData = { - {0, "", ""}, - {0, "Hello, World!", "Hello, World!"}, - {4, "", "Rust"}, - {3, "horse", "ros"}, - {6, "tan", "elephant"}, - {8, "execute", "intention"}, - {1, "a", "b"}, - {1, "a", "aa"}, - {1, "a", ""}, - {1, "a", "ab"}, - {1, "a", "ba"}, - {2, "a", "bc"}, - {2, "a", "cb"}, + {0, "", ""}, + {0, "Hello, World!", "Hello, World!"}, + {4, "", "Rust"}, + {3, "horse", "ros"}, + {6, "tan", "elephant"}, + {8, "execute", "intention"}, + {1, "a", "b"}, + {1, "a", "aa"}, + {1, "a", ""}, + {1, "a", "ab"}, + {1, "a", "ba"}, + {2, "a", "bc"}, + {2, "a", "cb"}, }; final List> methods = Arrays.asList(LevenshteinDistance::naiveLevenshteinDistance, LevenshteinDistance::optimizedLevenshteinDistance); diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java index 3de1114a0987..dc312a3eb12c 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,7 +17,7 @@ void testAlternatingLength(int[] arr, int expected) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {1}, 1), Arguments.of(new int[] {1, 2}, 2), Arguments.of(new int[] {2, 1}, 2), Arguments.of(new int[] {1, 3, 2, 4, 3, 5}, 6), Arguments.of(new int[] {1, 2, 3, 4, 5}, 2), Arguments.of(new int[] {5, 4, 3, 2, 1}, 2), - Arguments.of(new int[] {10, 22, 9, 33, 49, 50, 31, 60}, 6), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2)); + return Stream.of(Arguments.of(new int[]{1}, 1), Arguments.of(new int[]{1, 2}, 2), Arguments.of(new int[]{2, 1}, 2), Arguments.of(new int[]{1, 3, 2, 4, 3, 5}, 6), Arguments.of(new int[]{1, 2, 3, 4, 5}, 2), Arguments.of(new int[]{5, 4, 3, 2, 1}, 2), + Arguments.of(new int[]{10, 22, 9, 33, 49, 50, 31, 60}, 6), Arguments.of(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java index 6384fe2afebe..b3c7a8b481be 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.apache.commons.lang3.ArrayUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -16,6 +17,7 @@ public class LongestArithmeticSubsequenceTest { void testGetLongestArithmeticSubsequenceLength(int[] nums, int expected) { assertEquals(expected, LongestArithmeticSubsequence.getLongestArithmeticSubsequenceLength(nums)); } + @ParameterizedTest @MethodSource("provideTestCases") void testGetLongestArithmeticSubsequenceLengthReversedInput(int[] nums, int expected) { @@ -29,7 +31,7 @@ void testGetLongestArithmeticSubsequenceLengthThrowsForNullInput() { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {3, 6, 9, 12, 15}, 5), Arguments.of(new int[] {1, 7, 10, 13, 14, 19}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 4), Arguments.of(new int[] {}, 0), Arguments.of(new int[] {10}, 1), Arguments.of(new int[] {9, 4, 7, 2, 10}, 3), - Arguments.of(new int[] {1, 2, 2, 2, 2, 5}, 4)); + return Stream.of(Arguments.of(new int[]{3, 6, 9, 12, 15}, 5), Arguments.of(new int[]{1, 7, 10, 13, 14, 19}, 4), Arguments.of(new int[]{1, 2, 3, 4}, 4), Arguments.of(new int[]{}, 0), Arguments.of(new int[]{10}, 1), Arguments.of(new int[]{9, 4, 7, 2, 10}, 3), + Arguments.of(new int[]{1, 2, 2, 2, 2, 5}, 4)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java b/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java index 5135105592a5..2858466ea799 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -23,23 +24,23 @@ public void testLongestIncreasingSubsequence(final int expected, final int[] inp private static Stream testCases() { final Object[][] testData = { - {0, new int[] {}}, - {1, new int[] {1}}, - {1, new int[] {2, 2}}, - {1, new int[] {3, 3, 3}}, - {1, new int[] {4, 4, 4, 4}}, - {1, new int[] {5, 5, 5, 5, 5}}, - {2, new int[] {1, 2}}, - {2, new int[] {1, 2, 2, 2, 2}}, - {2, new int[] {1, 0, 2}}, - {3, new int[] {1, 10, 2, 30}}, - {3, new int[] {5, 8, 3, 7, 9, 1}}, - {6, new int[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}}, - {4, new int[] {10, 9, 2, 5, 3, 7, 101, 18}}, - {4, new int[] {10, 10, 9, 9, 2, 2, 5, 5, 3, 3, 7, 7, 101, 101, 18, 18}}, - {4, new int[] {0, 1, 0, 3, 2, 3}}, - {2, new int[] {1, 1, 2, 2, 2}}, - {3, new int[] {1, 1, 2, 2, 2, 3, 3, 3, 3}}, + {0, new int[]{}}, + {1, new int[]{1}}, + {1, new int[]{2, 2}}, + {1, new int[]{3, 3, 3}}, + {1, new int[]{4, 4, 4, 4}}, + {1, new int[]{5, 5, 5, 5, 5}}, + {2, new int[]{1, 2}}, + {2, new int[]{1, 2, 2, 2, 2}}, + {2, new int[]{1, 0, 2}}, + {3, new int[]{1, 10, 2, 30}}, + {3, new int[]{5, 8, 3, 7, 9, 1}}, + {6, new int[]{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}}, + {4, new int[]{10, 9, 2, 5, 3, 7, 101, 18}}, + {4, new int[]{10, 10, 9, 9, 2, 2, 5, 5, 3, 3, 7, 7, 101, 101, 18, 18}}, + {4, new int[]{0, 1, 0, 3, 2, 3}}, + {2, new int[]{1, 1, 2, 2, 2}}, + {3, new int[]{1, 1, 2, 2, 2, 3, 3, 3, 3}}, }; final List methods = Arrays.asList(LongestIncreasingSubsequence::lis, LongestIncreasingSubsequence::findLISLen); diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstringTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstringTest.java index 278de7e10e0a..500df41b670e 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstringTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstringTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -11,7 +12,7 @@ public class LongestPalindromicSubstringTest { private static Stream provideTestCases() { return Stream.of( - Arguments.of("babad", "aba"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("x", "x"), Arguments.of("", ""), Arguments.of("aaaa", "aaaa"), Arguments.of("mm", "mm"), Arguments.of("level", "level"), Arguments.of("bananas", "anana"), Arguments.of("abacabad", "abacaba")); + Arguments.of("babad", "aba"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("x", "x"), Arguments.of("", ""), Arguments.of("aaaa", "aaaa"), Arguments.of("mm", "mm"), Arguments.of("level", "level"), Arguments.of("bananas", "anana"), Arguments.of("abacabad", "abacaba")); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java index 77b7dda6a972..67f751791537 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -11,7 +12,7 @@ public class LongestValidParenthesesTest { private static Stream provideTestCases() { return Stream.of(Arguments.of("", 0), Arguments.of("(", 0), Arguments.of(")", 0), Arguments.of("()", 2), Arguments.of("(())", 4), Arguments.of("()()", 4), Arguments.of(")(", 0), Arguments.of("(()", 2), Arguments.of("())(", 2), Arguments.of("(()())", 6), Arguments.of("(((())))", 8), - Arguments.of("(()))(()", 4), Arguments.of("()()()(", 6), Arguments.of("(()())()(", 8), Arguments.of("((((((", 0), Arguments.of("))))))", 0), Arguments.of("(()())(", 6), Arguments.of("))()(", 2), Arguments.of("()((()))", 8), Arguments.of("((()((())))", 10)); + Arguments.of("(()))(()", 4), Arguments.of("()()()(", 6), Arguments.of("(()())()(", 8), Arguments.of("((((((", 0), Arguments.of("))))))", 0), Arguments.of("(()())(", 6), Arguments.of("))()(", 2), Arguments.of("()((()))", 8), Arguments.of("((()((())))", 10)); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplicationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplicationTest.java index 2bee0ca52918..75e94bc8b3e3 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplicationTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; + import org.junit.jupiter.api.Test; class MatrixChainMultiplicationTest { diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java index 3f312d86462e..404d4a109c8d 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java @@ -9,44 +9,44 @@ public class MaximumSumOfNonAdjacentElementsTest { // Tests for Approach1 @Test public void testGetMaxSumApproach1WithEmptyArray() { - assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {})); // Empty array + assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[]{})); // Empty array } @Test public void testGetMaxSumApproach1WithSingleElement() { - assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1})); // Single element + assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[]{1})); // Single element } @Test public void testGetMaxSumApproach1WithTwoElementsTakeMax() { - assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1, 2})); // Take max of both + assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[]{1, 2})); // Take max of both } @Test public void testGetMaxSumApproach1WithMultipleElements() { - assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5 - assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {5, 1, 1, 5})); // 5 + 5 + assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[]{3, 2, 5, 10, 7})); // 3 + 7 + 5 + assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[]{5, 1, 1, 5})); // 5 + 5 } // Tests for Approach2 @Test public void testGetMaxSumApproach2WithEmptyArray() { - assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {})); // Empty array + assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[]{})); // Empty array } @Test public void testGetMaxSumApproach2WithSingleElement() { - assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1})); // Single element + assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[]{1})); // Single element } @Test public void testGetMaxSumApproach2WithTwoElementsTakeMax() { - assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1, 2})); // Take max of both + assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[]{1, 2})); // Take max of both } @Test public void testGetMaxSumApproach2WithMultipleElements() { - assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5 - assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {5, 1, 1, 5})); // 5 + 5 + assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[]{3, 2, 5, 10, 7})); // 3 + 7 + 5 + assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[]{5, 1, 1, 5})); // 5 + 5 } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java index 1f14320244ea..0e9489621761 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java @@ -39,6 +39,8 @@ public void testMinimumSumPartitionWithEmptyArray() { @Test public void testMinimumSumPartitionThrowsForNegativeArray() { int[] array = {4, 1, -6, 7}; - assertThrows(IllegalArgumentException.class, () -> { MinimumSumPartition.minimumSumPartition(array); }); + assertThrows(IllegalArgumentException.class, () -> { + MinimumSumPartition.minimumSumPartition(array); + }); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java index 173ed00488d0..9ee0f9a1efb7 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java @@ -66,19 +66,19 @@ public void testOptimalJobScheduling3() { int numberMachines = 4; int[][] run = { - {5, 1, 3, 2}, - {4, 2, 1, 1}, - {1, 5, 2, 6}, - {1, 1, 2, 3}, - {2, 1, 4, 6}, - {3, 2, 2, 3}, + {5, 1, 3, 2}, + {4, 2, 1, 1}, + {1, 5, 2, 6}, + {1, 1, 2, 3}, + {2, 1, 4, 6}, + {3, 2, 2, 3}, }; int[][] transfer = { - {0, 1, 2, 1}, - {1, 0, 2, 3}, - {2, 2, 0, 2}, - {1, 3, 2, 0}, + {0, 1, 2, 1}, + {1, 0, 2, 3}, + {2, 2, 0, 2}, + {1, 3, 2, 0}, }; OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer); diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java index be503359e770..389b345e1052 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java index 098893f41771..c7cf145b1b18 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java @@ -8,18 +8,21 @@ class PartitionProblemTest { @Test public void testIfSumOfTheArrayIsOdd() { - assertFalse(PartitionProblem.partition(new int[] {1, 2, 2})); + assertFalse(PartitionProblem.partition(new int[]{1, 2, 2})); } + @Test public void testIfSizeOfTheArrayIsOne() { - assertFalse(PartitionProblem.partition(new int[] {2})); + assertFalse(PartitionProblem.partition(new int[]{2})); } + @Test public void testIfSumOfTheArrayIsEven1() { - assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6})); + assertTrue(PartitionProblem.partition(new int[]{1, 2, 3, 6})); } + @Test public void testIfSumOfTheArrayIsEven2() { - assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8})); + assertFalse(PartitionProblem.partition(new int[]{1, 2, 3, 8})); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java index e75482a68d8b..be8071b4b308 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -14,7 +15,7 @@ private record RegexTestCase(String s, String p, boolean expected) { private static Stream provideTestCases() { return Stream.of(Arguments.of(new RegexTestCase("aa", "*", true)), Arguments.of(new RegexTestCase("aa", "a*", true)), Arguments.of(new RegexTestCase("aa", "a", false)), Arguments.of(new RegexTestCase("cb", "?b", true)), Arguments.of(new RegexTestCase("cb", "?a", false)), - Arguments.of(new RegexTestCase("adceb", "*a*b", true)), Arguments.of(new RegexTestCase("acdcb", "a*c?b", false)), Arguments.of(new RegexTestCase("", "*", true)), Arguments.of(new RegexTestCase("", "", true))); + Arguments.of(new RegexTestCase("adceb", "*a*b", true)), Arguments.of(new RegexTestCase("acdcb", "a*c?b", false)), Arguments.of(new RegexTestCase("", "*", true)), Arguments.of(new RegexTestCase("", "", true))); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java index 9cf21fd836db..80bc966ecb4f 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java @@ -93,6 +93,7 @@ void testCutRodEmptyPrices() { int length = 5; assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "An empty prices array should throw an IllegalArgumentException."); } + @Test void testCutRodNegativeLength() { int[] prices = {1, 5, 8, 9, 10}; // Prices are irrelevant for negative length diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java index c76f89deb600..d49482eb770b 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java @@ -7,23 +7,25 @@ public class SubsetCountTest { @Test void hasMultipleSubset() { - int[] arr = new int[] {1, 2, 3, 3}; + int[] arr = new int[]{1, 2, 3, 3}; assertEquals(3, SubsetCount.getCount(arr, 6)); } + @Test void singleElementSubset() { - int[] arr = new int[] {1, 1, 1, 1}; + int[] arr = new int[]{1, 1, 1, 1}; assertEquals(4, SubsetCount.getCount(arr, 1)); } @Test void hasMultipleSubsetSO() { - int[] arr = new int[] {1, 2, 3, 3}; + int[] arr = new int[]{1, 2, 3, 3}; assertEquals(3, SubsetCount.getCountSO(arr, 6)); } + @Test void singleSubsetSO() { - int[] arr = new int[] {1, 1, 1, 1}; + int[] arr = new int[]{1, 1, 1, 1}; assertEquals(1, SubsetCount.getCountSO(arr, 4)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.java index 3a965f4e68b8..26a28396afe9 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.java @@ -9,10 +9,10 @@ public class SubsetSumSpaceOptimizedTest { @Test void basicCheck() { - assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {7, 3, 2, 5, 8}, 14)); - assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {4, 3, 2, 1}, 5)); - assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 7, 2, 9, 10}, 13)); - assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 2, 7, 10, 9}, 14)); - assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {2, 15, 1, 6, 7}, 4)); + assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[]{7, 3, 2, 5, 8}, 14)); + assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[]{4, 3, 2, 1}, 5)); + assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[]{1, 7, 2, 9, 10}, 13)); + assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[]{1, 2, 7, 10, 9}, 14)); + assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[]{2, 15, 1, 6, 7}, 4)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java index 1ae4e71232f0..396bb9586383 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -18,7 +19,7 @@ void testSubsetSum(TestCase testCase) { } private static Stream provideTestCases() { - return Stream.of(new TestCase(new int[] {50, 4, 10, 15, 34}, 64, true), new TestCase(new int[] {50, 4, 10, 15, 34}, 99, true), new TestCase(new int[] {50, 4, 10, 15, 34}, 5, false), new TestCase(new int[] {50, 4, 10, 15, 34}, 66, false), new TestCase(new int[] {}, 0, true), - new TestCase(new int[] {1, 2, 3}, 6, true), new TestCase(new int[] {1, 2, 3}, 7, false), new TestCase(new int[] {3, 34, 4, 12, 5, 2}, 9, true)); + return Stream.of(new TestCase(new int[]{50, 4, 10, 15, 34}, 64, true), new TestCase(new int[]{50, 4, 10, 15, 34}, 99, true), new TestCase(new int[]{50, 4, 10, 15, 34}, 5, false), new TestCase(new int[]{50, 4, 10, 15, 34}, 66, false), new TestCase(new int[]{}, 0, true), + new TestCase(new int[]{1, 2, 3}, 6, true), new TestCase(new int[]{1, 2, 3}, 7, false), new TestCase(new int[]{3, 34, 4, 12, 5, 2}, 9, true)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java index 9df35447eefa..2b18a7df35ce 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java @@ -9,10 +9,10 @@ class SumOfSubsetTest { @Test void basicCheck() { - assertFalse(SumOfSubset.subsetSum(new int[] {1, 2, 7, 10, 9}, 4, 14)); - assertFalse(SumOfSubset.subsetSum(new int[] {2, 15, 1, 6, 7}, 4, 4)); - assertTrue(SumOfSubset.subsetSum(new int[] {7, 3, 2, 5, 8}, 4, 14)); - assertTrue(SumOfSubset.subsetSum(new int[] {4, 3, 2, 1}, 3, 5)); - assertTrue(SumOfSubset.subsetSum(new int[] {1, 7, 2, 9, 10}, 4, 13)); + assertFalse(SumOfSubset.subsetSum(new int[]{1, 2, 7, 10, 9}, 4, 14)); + assertFalse(SumOfSubset.subsetSum(new int[]{2, 15, 1, 6, 7}, 4, 4)); + assertTrue(SumOfSubset.subsetSum(new int[]{7, 3, 2, 5, 8}, 4, 14)); + assertTrue(SumOfSubset.subsetSum(new int[]{4, 3, 2, 1}, 3, 5)); + assertTrue(SumOfSubset.subsetSum(new int[]{1, 7, 2, 9, 10}, 4, 13)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java index 56cd4ffe7d44..9292d9f04c5b 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java @@ -1,4 +1,5 @@ package com.thealgorithms.dynamicprogramming; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java b/src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java index 9df308497ddf..73dd8e50b7b9 100644 --- a/src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java +++ b/src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java @@ -4,6 +4,7 @@ import java.util.Collection; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -30,8 +31,8 @@ class BresenhamLineTest { */ static Stream linePointsProvider() { return Stream.of(Arguments.of(0, 0, 5, 5, List.of(new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4), new Point(5, 5))), Arguments.of(0, 0, 5, 0, List.of(new Point(0, 0), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(4, 0), new Point(5, 0))), - Arguments.of(0, 0, 0, 5, List.of(new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(0, 3), new Point(0, 4), new Point(0, 5))), Arguments.of(-2, -2, -5, -5, List.of(new Point(-2, -2), new Point(-3, -3), new Point(-4, -4), new Point(-5, -5))), - Arguments.of(-1, -1, 2, 2, List.of(new Point(-1, -1), new Point(0, 0), new Point(1, 1), new Point(2, 2))), Arguments.of(2, -1, -1, -4, List.of(new Point(2, -1), new Point(1, -2), new Point(0, -3), new Point(-1, -4)))); + Arguments.of(0, 0, 0, 5, List.of(new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(0, 3), new Point(0, 4), new Point(0, 5))), Arguments.of(-2, -2, -5, -5, List.of(new Point(-2, -2), new Point(-3, -3), new Point(-4, -4), new Point(-5, -5))), + Arguments.of(-1, -1, 2, 2, List.of(new Point(-1, -1), new Point(0, 0), new Point(1, 1), new Point(2, 2))), Arguments.of(2, -1, -1, -4, List.of(new Point(2, -1), new Point(1, -2), new Point(0, -3), new Point(-1, -4)))); } /** @@ -41,10 +42,10 @@ static Stream linePointsProvider() { * starting and ending coordinates to validate that the generated points * match the expected output.

    * - * @param x0 the x-coordinate of the starting point - * @param y0 the y-coordinate of the starting point - * @param x1 the x-coordinate of the ending point - * @param y1 the y-coordinate of the ending point + * @param x0 the x-coordinate of the starting point + * @param y0 the y-coordinate of the starting point + * @param x1 the x-coordinate of the ending point + * @param y1 the y-coordinate of the ending point * @param expected a collection of expected points that should form a line */ @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/geometry/ConvexHullTest.java b/src/test/java/com/thealgorithms/geometry/ConvexHullTest.java index e3e32e43c6de..da41767cb56a 100644 --- a/src/test/java/com/thealgorithms/geometry/ConvexHullTest.java +++ b/src/test/java/com/thealgorithms/geometry/ConvexHullTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class ConvexHullTest { diff --git a/src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java b/src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java index 24370cd43b25..ad88b1ad799e 100644 --- a/src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java +++ b/src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -22,8 +23,8 @@ class MidpointCircleTest { */ @ParameterizedTest @CsvSource({ - "0, 0, 3", // Circle centered at (0, 0) with radius 3 - "10, 10, 2" // Circle centered at (10, 10) with radius 2 + "0, 0, 3", // Circle centered at (0, 0) with radius 3 + "10, 10, 2" // Circle centered at (10, 10) with radius 2 }) void testGenerateCirclePoints(int centerX, int centerY, int radius) { diff --git a/src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java b/src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java index 9d03909c60ca..8e4352590034 100644 --- a/src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java +++ b/src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -28,59 +29,59 @@ class MidpointEllipseTest { */ static Stream ellipseTestProvider() { return Stream.of( - Arguments.of(0, 0, 5, 3, new int[][] {{0, 3}, {0, 3}, {0, -3}, {0, -3}, {1, 3}, {-1, 3}, {1, -3}, {-1, -3}, {2, 3}, {-2, 3}, {2, -3}, {-2, -3}, {3, 2}, {-3, 2}, {3, -2}, {-3, -2}, {4, 2}, {-4, 2}, {4, -2}, {-4, -2}, {5, 1}, {-5, 1}, {5, -1}, {-5, -1}, {5, 0}, {-5, 0}, {5, 0}, {-5, 0}}), - Arguments.of(0, 0, 0, 5, - new int[][] { - {0, -5}, {0, -4}, {0, -3}, {0, -2}, {0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5} // Only vertical line points and center - }), - Arguments.of(0, 0, 5, 0, - new int[][] { - {-5, 0}, {-4, 0}, {-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0} // Only horizontal line points and center - }), - Arguments.of(0, 0, 0, 0, - new int[][] { - {0, 0} // Only center point - }), - Arguments.of(0, 0, 4, 4, - new int[][] { - {0, 4}, - {0, 4}, - {0, -4}, - {0, -4}, - {1, 4}, - {-1, 4}, - {1, -4}, - {-1, -4}, - {2, 3}, - {-2, 3}, - {2, -3}, - {-2, -3}, - {3, 3}, - {-3, 3}, - {3, -3}, - {-3, -3}, - {3, 2}, - {-3, 2}, - {3, -2}, - {-3, -2}, - {4, 1}, - {-4, 1}, - {4, -1}, - {-4, -1}, - {4, 0}, - {-4, 0}, - {4, 0}, - {-4, 0}, - })); + Arguments.of(0, 0, 5, 3, new int[][]{{0, 3}, {0, 3}, {0, -3}, {0, -3}, {1, 3}, {-1, 3}, {1, -3}, {-1, -3}, {2, 3}, {-2, 3}, {2, -3}, {-2, -3}, {3, 2}, {-3, 2}, {3, -2}, {-3, -2}, {4, 2}, {-4, 2}, {4, -2}, {-4, -2}, {5, 1}, {-5, 1}, {5, -1}, {-5, -1}, {5, 0}, {-5, 0}, {5, 0}, {-5, 0}}), + Arguments.of(0, 0, 0, 5, + new int[][]{ + {0, -5}, {0, -4}, {0, -3}, {0, -2}, {0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5} // Only vertical line points and center + }), + Arguments.of(0, 0, 5, 0, + new int[][]{ + {-5, 0}, {-4, 0}, {-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0} // Only horizontal line points and center + }), + Arguments.of(0, 0, 0, 0, + new int[][]{ + {0, 0} // Only center point + }), + Arguments.of(0, 0, 4, 4, + new int[][]{ + {0, 4}, + {0, 4}, + {0, -4}, + {0, -4}, + {1, 4}, + {-1, 4}, + {1, -4}, + {-1, -4}, + {2, 3}, + {-2, 3}, + {2, -3}, + {-2, -3}, + {3, 3}, + {-3, 3}, + {3, -3}, + {-3, -3}, + {3, 2}, + {-3, 2}, + {3, -2}, + {-3, -2}, + {4, 1}, + {-4, 1}, + {4, -1}, + {-4, -1}, + {4, 0}, + {-4, 0}, + {4, 0}, + {-4, 0}, + })); } /** * Tests the drawEllipse method with various parameters. * - * @param centerX the x-coordinate of the center of the ellipse - * @param centerY the y-coordinate of the center of the ellipse - * @param a the length of the semi-major axis - * @param b the length of the semi-minor axis + * @param centerX the x-coordinate of the center of the ellipse + * @param centerY the y-coordinate of the center of the ellipse + * @param a the length of the semi-major axis + * @param b the length of the semi-minor axis * @param expectedPoints the expected points forming the ellipse */ @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java b/src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java index 6f1c8a9d53b2..57ad17c0fba0 100644 --- a/src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java +++ b/src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java index a997c198a39b..ecc0fa5f6562 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; public class ActivitySelectionTest { diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java index 452f7858c162..86797568c257 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,7 +17,7 @@ public void testMaxValue(int capacity, int[] bandwidths, int[] values, int expec } private static Stream bandwidthProvider() { - return Stream.of(Arguments.of(50, new int[] {20, 10, 30}, new int[] {40, 20, 30}, 80), Arguments.of(0, new int[] {5, 10}, new int[] {10, 20}, 0), Arguments.of(5, new int[] {5, 10}, new int[] {10, 20}, 10), Arguments.of(15, new int[] {10, 20}, new int[] {10, 25}, 18), - Arguments.of(25, new int[] {10, 15, 20}, new int[] {10, 30, 50}, 60)); + return Stream.of(Arguments.of(50, new int[]{20, 10, 30}, new int[]{40, 20, 30}, 80), Arguments.of(0, new int[]{5, 10}, new int[]{10, 20}, 0), Arguments.of(5, new int[]{5, 10}, new int[]{10, 20}, 10), Arguments.of(15, new int[]{10, 20}, new int[]{10, 25}, 18), + Arguments.of(25, new int[]{10, 15, 20}, new int[]{10, 30, 50}, 60)); } } diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java index e9d267712a05..5f7e8f82ae2f 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; public class CoinChangeTest { diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java index 1fe018ecce18..c3dcfdd36294 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java @@ -3,7 +3,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; + import org.junit.jupiter.api.Test; + public class DigitSeparationTest { @Test diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java index 1d34876de864..19fbce417e5e 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java index fcd173202469..6da8667988bb 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java @@ -6,6 +6,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; + import org.junit.jupiter.api.Test; public class GaleShapleyTest { diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java index b679121689a1..1b1e282a6e7e 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Collections; + import org.junit.jupiter.api.Test; public class JobSequencingTest { diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java index 64cb4b80f182..c75e068be8d4 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,6 +17,6 @@ public void testMinimumWaitingTime(int[] queries, int expected) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {3, 2, 1, 2, 6}, 17), Arguments.of(new int[] {3, 2, 1}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 10), Arguments.of(new int[] {5, 5, 5, 5}, 30), Arguments.of(new int[] {}, 0)); + return Stream.of(Arguments.of(new int[]{3, 2, 1, 2, 6}, 17), Arguments.of(new int[]{3, 2, 1}, 4), Arguments.of(new int[]{1, 2, 3, 4}, 10), Arguments.of(new int[]{5, 5, 5, 5}, 30), Arguments.of(new int[]{}, 0)); } } diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java index 9ff2b95ff2e5..a7a31e566162 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,7 +17,7 @@ public void testMinMergeCost(int[] files, int expected) { } private static Stream fileMergingProvider() { - return Stream.of(Arguments.of(new int[] {4, 3, 2, 6}, 29), Arguments.of(new int[] {5}, 0), Arguments.of(new int[] {2, 2, 2}, 10), Arguments.of(new int[] {10, 5, 3, 2}, 35), Arguments.of(new int[] {1, 1, 1, 1}, 8), Arguments.of(new int[] {1, 2, 3, 4, 5}, 33), - Arguments.of(new int[] {1, 2, 3, 4, 5, 6}, 51), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7}, 74), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8}, 102), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, 135)); + return Stream.of(Arguments.of(new int[]{4, 3, 2, 6}, 29), Arguments.of(new int[]{5}, 0), Arguments.of(new int[]{2, 2, 2}, 10), Arguments.of(new int[]{10, 5, 3, 2}, 35), Arguments.of(new int[]{1, 1, 1, 1}, 8), Arguments.of(new int[]{1, 2, 3, 4, 5}, 33), + Arguments.of(new int[]{1, 2, 3, 4, 5, 6}, 51), Arguments.of(new int[]{1, 2, 3, 4, 5, 6, 7}, 74), Arguments.of(new int[]{1, 2, 3, 4, 5, 6, 7, 8}, 102), Arguments.of(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 135)); } } diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java index afad76a34521..356f132a281b 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,6 +17,6 @@ public void testMaxProfit(int[] prices, int expected) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[] {7, 6, 4, 3, 1}, 0), Arguments.of(new int[] {5, 5, 5, 5, 5}, 0), Arguments.of(new int[] {10}, 0), Arguments.of(new int[] {1, 5}, 4), Arguments.of(new int[] {2, 4, 1, 3, 7, 5}, 6)); + return Stream.of(Arguments.of(new int[]{7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[]{7, 6, 4, 3, 1}, 0), Arguments.of(new int[]{5, 5, 5, 5, 5}, 0), Arguments.of(new int[]{10}, 0), Arguments.of(new int[]{1, 5}, 4), Arguments.of(new int[]{2, 4, 1, 3, 7, 5}, 6)); } } diff --git a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java index 891c3066058e..e58ac593e32e 100644 --- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java +++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java @@ -4,6 +4,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; + import org.junit.jupiter.api.Test; class BufferedReaderTest { diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java index f87652253641..ae118a1d896f 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -4,6 +4,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; public class AbsoluteValueTest { diff --git a/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java b/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java index 14679f22636a..f6e5843e0a2c 100644 --- a/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AmicableNumberTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; + import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/maths/AreaTest.java b/src/test/java/com/thealgorithms/maths/AreaTest.java index b28afb85fbc3..942c8e615300 100644 --- a/src/test/java/com/thealgorithms/maths/AreaTest.java +++ b/src/test/java/com/thealgorithms/maths/AreaTest.java @@ -69,35 +69,35 @@ void surfaceAreaCone() { @Test void testAllIllegalInput() { assertAll(() - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSquare(0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangle(0, 1)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangle(1, 0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCircle(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1))); + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSquare(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangle(0, 1)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangle(1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCircle(0)), + () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1))); } } diff --git a/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java b/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java index 2248ffd93732..1b9dea6f65fd 100644 --- a/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -19,7 +20,7 @@ class CatalanNumbersTest { * [input number, expected Catalan number for that input] */ static Stream catalanNumbersProvider() { - return Stream.of(new Object[] {0, 1}, new Object[] {1, 1}, new Object[] {2, 2}, new Object[] {3, 5}, new Object[] {4, 14}, new Object[] {5, 42}, new Object[] {6, 132}, new Object[] {7, 429}, new Object[] {8, 1430}, new Object[] {9, 4862}, new Object[] {10, 16796}); + return Stream.of(new Object[]{0, 1}, new Object[]{1, 1}, new Object[]{2, 2}, new Object[]{3, 5}, new Object[]{4, 14}, new Object[]{5, 42}, new Object[]{6, 132}, new Object[]{7, 429}, new Object[]{8, 1430}, new Object[]{9, 4862}, new Object[]{10, 16796}); } /** diff --git a/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java b/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java index 31c676d6e7b4..06139275751f 100644 --- a/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java +++ b/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class ChineseRemainderTheoremTest { diff --git a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java index 4e88d1e91bac..11d68c40cdcf 100644 --- a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java +++ b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; + import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/maths/ConvolutionFFTTest.java b/src/test/java/com/thealgorithms/maths/ConvolutionFFTTest.java index 4d627f939d42..e3673dd16e4e 100644 --- a/src/test/java/com/thealgorithms/maths/ConvolutionFFTTest.java +++ b/src/test/java/com/thealgorithms/maths/ConvolutionFFTTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -48,8 +49,8 @@ public void testConvolutionFFT(double[] a, double[] b, double[] expectedOutput, } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new double[] {1, 2, 3}, new double[] {4, 5, 6}, new double[] {4, 13, 28, 27, 18}, "Basic test"), Arguments.of(new double[] {0, 0, 0}, new double[] {1, 2, 3}, new double[] {0, 0, 0, 0, 0}, "Test with zero elements"), - Arguments.of(new double[] {1, 2}, new double[] {3, 4, 5}, new double[] {3, 10, 13, 10}, "Test with different sizes"), Arguments.of(new double[] {5}, new double[] {2}, new double[] {10}, "Test with single element"), - Arguments.of(new double[] {1, -2, 3}, new double[] {-1, 2, -3}, new double[] {-1, 4, -10, 12, -9}, "Test with negative values")); + return Stream.of(Arguments.of(new double[]{1, 2, 3}, new double[]{4, 5, 6}, new double[]{4, 13, 28, 27, 18}, "Basic test"), Arguments.of(new double[]{0, 0, 0}, new double[]{1, 2, 3}, new double[]{0, 0, 0, 0, 0}, "Test with zero elements"), + Arguments.of(new double[]{1, 2}, new double[]{3, 4, 5}, new double[]{3, 10, 13, 10}, "Test with different sizes"), Arguments.of(new double[]{5}, new double[]{2}, new double[]{10}, "Test with single element"), + Arguments.of(new double[]{1, -2, 3}, new double[]{-1, 2, -3}, new double[]{-1, 4, -10, 12, -9}, "Test with negative values")); } } diff --git a/src/test/java/com/thealgorithms/maths/ConvolutionTest.java b/src/test/java/com/thealgorithms/maths/ConvolutionTest.java index d57b3b3ca4e5..7c13d727b583 100644 --- a/src/test/java/com/thealgorithms/maths/ConvolutionTest.java +++ b/src/test/java/com/thealgorithms/maths/ConvolutionTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -19,9 +20,9 @@ void testConvolution(ConvolutionTestCase testCase) { } private static Stream provideTestCases() { - return Stream.of(new ConvolutionTestCase("Basic convolution", new double[] {1, 2, 3}, new double[] {4, 5, 6}, new double[] {4, 13, 28, 27, 18}), new ConvolutionTestCase("Convolution with zero elements", new double[] {0, 0, 0}, new double[] {1, 2, 3}, new double[] {0, 0, 0, 0, 0}), - new ConvolutionTestCase("Convolution with single element", new double[] {2}, new double[] {3}, new double[] {6}), new ConvolutionTestCase("Convolution with different sizes", new double[] {1, 2}, new double[] {3, 4, 5}, new double[] {3, 10, 13, 10}), - new ConvolutionTestCase("Convolution with negative values", new double[] {1, -2, 3}, new double[] {-1, 2, -3}, new double[] {-1, 4, -10, 12, -9}), - new ConvolutionTestCase("Convolution with large numbers", new double[] {1e6, 2e6}, new double[] {3e6, 4e6}, new double[] {3e12, 1e13, 8e12})); + return Stream.of(new ConvolutionTestCase("Basic convolution", new double[]{1, 2, 3}, new double[]{4, 5, 6}, new double[]{4, 13, 28, 27, 18}), new ConvolutionTestCase("Convolution with zero elements", new double[]{0, 0, 0}, new double[]{1, 2, 3}, new double[]{0, 0, 0, 0, 0}), + new ConvolutionTestCase("Convolution with single element", new double[]{2}, new double[]{3}, new double[]{6}), new ConvolutionTestCase("Convolution with different sizes", new double[]{1, 2}, new double[]{3, 4, 5}, new double[]{3, 10, 13, 10}), + new ConvolutionTestCase("Convolution with negative values", new double[]{1, -2, 3}, new double[]{-1, 2, -3}, new double[]{-1, 4, -10, 12, -9}), + new ConvolutionTestCase("Convolution with large numbers", new double[]{1e6, 2e6}, new double[]{3e6, 4e6}, new double[]{3e12, 1e13, 8e12})); } } diff --git a/src/test/java/com/thealgorithms/maths/EulerMethodTest.java b/src/test/java/com/thealgorithms/maths/EulerMethodTest.java index 5ae5ac70b1df..7eccd8b1c73e 100644 --- a/src/test/java/com/thealgorithms/maths/EulerMethodTest.java +++ b/src/test/java/com/thealgorithms/maths/EulerMethodTest.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.function.BiFunction; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -61,9 +62,9 @@ void testEulerFull(EulerFullTestCase testCase) { } static Stream eulerFullTestCases() { - return Stream.of(Arguments.of(new EulerFullTestCase(new double[] {0.0, 1.0, 0.5, 0.0}, (x, y) -> x, 3, new double[] {0.0, 0.0}, new double[] {1.0, 0.25})), - Arguments.of(new EulerFullTestCase(new double[] {0.0, 1.0, 0.1, 1.0}, (x, y) -> y, 12, new double[] {0.0, 1.0}, new double[] {1.0999999999999999, 2.8531167061100002})), - Arguments.of(new EulerFullTestCase(new double[] {0.0, 0.1, 0.1, 1.0}, (x, y) -> x + y, 2, new double[] {0.0, 1.0}, new double[] {0.1, 1.1}))); + return Stream.of(Arguments.of(new EulerFullTestCase(new double[]{0.0, 1.0, 0.5, 0.0}, (x, y) -> x, 3, new double[]{0.0, 0.0}, new double[]{1.0, 0.25})), + Arguments.of(new EulerFullTestCase(new double[]{0.0, 1.0, 0.1, 1.0}, (x, y) -> y, 12, new double[]{0.0, 1.0}, new double[]{1.0999999999999999, 2.8531167061100002})), + Arguments.of(new EulerFullTestCase(new double[]{0.0, 0.1, 0.1, 1.0}, (x, y) -> x + y, 2, new double[]{0.0, 1.0}, new double[]{0.1, 1.1}))); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/maths/EulersFunctionTest.java b/src/test/java/com/thealgorithms/maths/EulersFunctionTest.java index 9048a711d0d6..b14a2cf50df5 100644 --- a/src/test/java/com/thealgorithms/maths/EulersFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/EulersFunctionTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -24,7 +25,7 @@ void testGetEulerThrowsExceptionForNonPositiveInput(int input) { private static Stream provideNumbersForGetEuler() { return Stream.of(Arguments.of(1, 1), Arguments.of(2, 1), Arguments.of(3, 2), Arguments.of(4, 2), Arguments.of(5, 4), Arguments.of(6, 2), Arguments.of(10, 4), Arguments.of(21, 12), Arguments.of(69, 44), Arguments.of(47, 46), Arguments.of(46, 22), Arguments.of(55, 40), Arguments.of(34, 16), - Arguments.of(20, 8), Arguments.of(1024, 512)); + Arguments.of(20, 8), Arguments.of(1024, 512)); } private static Stream provideInvalidNumbersForGetEuler() { diff --git a/src/test/java/com/thealgorithms/maths/FFTTest.java b/src/test/java/com/thealgorithms/maths/FFTTest.java index 8d78fb0f2a16..ea9566f1533e 100644 --- a/src/test/java/com/thealgorithms/maths/FFTTest.java +++ b/src/test/java/com/thealgorithms/maths/FFTTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.ArrayList; + import org.junit.jupiter.api.Test; class FFTTest { diff --git a/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java b/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java index db18b46356b4..a94795347eb5 100644 --- a/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/maths/FastExponentiationTest.java b/src/test/java/com/thealgorithms/maths/FastExponentiationTest.java index f117f90233e3..15c7dc3dedb2 100644 --- a/src/test/java/com/thealgorithms/maths/FastExponentiationTest.java +++ b/src/test/java/com/thealgorithms/maths/FastExponentiationTest.java @@ -54,7 +54,9 @@ void testNegativeBase() { */ @Test void testNegativeExponent() { - assertThrows(ArithmeticException.class, () -> { FastExponentiation.fastExponentiation(2, -5, 1000); }); + assertThrows(ArithmeticException.class, () -> { + FastExponentiation.fastExponentiation(2, -5, 1000); + }); } /** @@ -62,6 +64,8 @@ void testNegativeExponent() { */ @Test void testInvalidModulus() { - assertThrows(IllegalArgumentException.class, () -> { FastExponentiation.fastExponentiation(2, 5, 0); }); + assertThrows(IllegalArgumentException.class, () -> { + FastExponentiation.fastExponentiation(2, 5, 0); + }); } } diff --git a/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java b/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java index 5cfb304ae471..4df9927d33ac 100644 --- a/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java +++ b/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.Optional; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java b/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java index 93aec39765d4..f5f19e19286f 100644 --- a/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java +++ b/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigInteger; + import org.junit.jupiter.api.Test; public class FibonacciLoopTest { @@ -31,6 +32,8 @@ public void checkRecurrenceRelation() { @Test public void checkNegativeInput() { - assertThrows(IllegalArgumentException.class, () -> { FibonacciLoop.compute(-1); }); + assertThrows(IllegalArgumentException.class, () -> { + FibonacciLoop.compute(-1); + }); } } diff --git a/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java b/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java index e3f7bf3e0fed..8de2da4619ba 100644 --- a/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java +++ b/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigInteger; + import org.junit.jupiter.api.Test; public class FibonacciNumberGoldenRationTest { @@ -19,11 +20,15 @@ public void returnsCorrectValues() { @Test public void throwsIllegalArgumentExceptionForNegativeInput() { - assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(-1); }); + assertThrows(IllegalArgumentException.class, () -> { + FibonacciNumberGoldenRation.compute(-1); + }); } @Test public void throwsIllegalArgumentExceptionForLargeInput() { - assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(FibonacciNumberGoldenRation.MAX_ARG + 1); }); + assertThrows(IllegalArgumentException.class, () -> { + FibonacciNumberGoldenRation.compute(FibonacciNumberGoldenRation.MAX_ARG + 1); + }); } } diff --git a/src/test/java/com/thealgorithms/maths/FindKthNumberTest.java b/src/test/java/com/thealgorithms/maths/FindKthNumberTest.java index ca69e66c9f6a..914e96479e64 100644 --- a/src/test/java/com/thealgorithms/maths/FindKthNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/FindKthNumberTest.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Random; + import org.junit.jupiter.api.Test; public class FindKthNumberTest { diff --git a/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java b/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java index d54cae67209f..7a80b890abfa 100644 --- a/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -18,11 +19,11 @@ void numberTests(int expected, int[] input) { } private static Stream inputStream() { - return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3})); + return Stream.of(Arguments.of(5, new int[]{5, 5, 5, 5, 5}), Arguments.of(0, new int[]{-1, 0}), Arguments.of(-1, new int[]{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[]{3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[]{3})); } @Test public void testFindMaxThrowsExceptionForEmptyInput() { - assertThrows(IllegalArgumentException.class, () -> FindMaxRecursion.max(new int[] {})); + assertThrows(IllegalArgumentException.class, () -> FindMaxRecursion.max(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java index a863a2c8586b..18f9b781cdba 100644 --- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -18,11 +19,11 @@ void numberTests(int expected, int[] input) { } private static Stream inputStream() { - return Stream.of(Arguments.of(10, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8})); + return Stream.of(Arguments.of(10, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[]{5, 5, 5, 5, 5}), Arguments.of(0, new int[]{-1, 0}), Arguments.of(-1, new int[]{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[]{3, -2, 3, 9, -4, -4, 8})); } @Test public void testFindMaxThrowsExceptionForEmptyInput() { - assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[] {})); + assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java b/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java index 3c36702b881d..38a78d24102b 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -18,11 +19,11 @@ void numberTests(int expected, int[] input) { } private static Stream inputStream() { - return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(-1, new int[] {-1, 0}), Arguments.of(-10, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(-4, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3})); + return Stream.of(Arguments.of(5, new int[]{5, 5, 5, 5, 5}), Arguments.of(-1, new int[]{-1, 0}), Arguments.of(-10, new int[]{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(-4, new int[]{3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[]{3})); } @Test public void testFindMaxThrowsExceptionForEmptyInput() { - assertThrows(IllegalArgumentException.class, () -> FindMinRecursion.min(new int[] {})); + assertThrows(IllegalArgumentException.class, () -> FindMinRecursion.min(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java index e713c0191ea1..896189d497fb 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -18,12 +19,12 @@ void numberTests(int expected, int[] input) { } private static Stream inputStream() { - return Stream.of(Arguments.of(1, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {0, 192, 384, 576}), Arguments.of(-1, new int[] {-1, 2, 5, 10}), Arguments.of(-10, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), - Arguments.of(-4, new int[] {4, -3, 8, 9, -4, -4, 10})); + return Stream.of(Arguments.of(1, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[]{5, 5, 5, 5, 5}), Arguments.of(0, new int[]{0, 192, 384, 576}), Arguments.of(-1, new int[]{-1, 2, 5, 10}), Arguments.of(-10, new int[]{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), + Arguments.of(-4, new int[]{4, -3, 8, 9, -4, -4, 10})); } @Test public void testFindMinThrowsExceptionForEmptyInput() { - assertThrows(IllegalArgumentException.class, () -> FindMin.findMin(new int[] {})); + assertThrows(IllegalArgumentException.class, () -> FindMin.findMin(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/maths/FloorTest.java b/src/test/java/com/thealgorithms/maths/FloorTest.java index 19aed70ccb71..e18b6fed48bb 100644 --- a/src/test/java/com/thealgorithms/maths/FloorTest.java +++ b/src/test/java/com/thealgorithms/maths/FloorTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; + public class FloorTest { @Test public void testFloorWholeNumber() { diff --git a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java index a5fd867e900e..9dee662a551d 100644 --- a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; + public class FrizzyNumberTest { @Test public void testFrizziesForBase2() { diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index bac3f8f7596c..0098769c5c85 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -47,16 +47,16 @@ void test8() { @Test void testArrayGcd1() { - Assertions.assertEquals(GCD.gcd(new int[] {9, 6}), 3); + Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3); } @Test void testArrayGcd2() { - Assertions.assertEquals(GCD.gcd(new int[] {2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}), 5); + Assertions.assertEquals(GCD.gcd(new int[]{2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}), 5); } @Test void testArrayGcdForEmptyInput() { - Assertions.assertEquals(GCD.gcd(new int[] {}), 0); + Assertions.assertEquals(GCD.gcd(new int[]{}), 0); } } diff --git a/src/test/java/com/thealgorithms/maths/GaussianTest.java b/src/test/java/com/thealgorithms/maths/GaussianTest.java index fe900fa22d26..7980c7f3850f 100644 --- a/src/test/java/com/thealgorithms/maths/GaussianTest.java +++ b/src/test/java/com/thealgorithms/maths/GaussianTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; + import org.junit.jupiter.api.Test; public class GaussianTest { diff --git a/src/test/java/com/thealgorithms/maths/GenericRootTest.java b/src/test/java/com/thealgorithms/maths/GenericRootTest.java index 2578cfe82305..ea33ebbe9776 100644 --- a/src/test/java/com/thealgorithms/maths/GenericRootTest.java +++ b/src/test/java/com/thealgorithms/maths/GenericRootTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java index 22cecf4dc960..245e821606dc 100644 --- a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java @@ -27,13 +27,27 @@ void test4() { @Test public void testCalculateAreaWithInvalidInput() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(1, 2, 3); }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(2, 1, 3); }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(3, 2, 1); }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(1, 3, 2); }); - - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(1, 1, 0); }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(1, 0, 1); }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { HeronsFormula.herons(0, 1, 1); }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(1, 2, 3); + }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(2, 1, 3); + }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(3, 2, 1); + }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(1, 3, 2); + }); + + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(1, 1, 0); + }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(1, 0, 1); + }); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + HeronsFormula.herons(0, 1, 1); + }); } } diff --git a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java index 05e58cf88e22..1c2536d74519 100644 --- a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.Test; public class KaprekarNumbersTest { @@ -53,27 +54,27 @@ void testForRangeOfNumber() { try { List 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, + 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); diff --git a/src/test/java/com/thealgorithms/maths/KaratsubaMultiplicationTest.java b/src/test/java/com/thealgorithms/maths/KaratsubaMultiplicationTest.java index e184d998724a..679e8e57f5f8 100644 --- a/src/test/java/com/thealgorithms/maths/KaratsubaMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/maths/KaratsubaMultiplicationTest.java @@ -4,6 +4,7 @@ import java.math.BigInteger; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -27,16 +28,16 @@ class KaratsubaMultiplicationTest { */ static Stream provideTestCases() { return Stream.of( - // Test case 1: Two small numbers - Arguments.of(new BigInteger("1234"), new BigInteger("5678"), new BigInteger("7006652")), - // Test case 2: Two large numbers - Arguments.of(new BigInteger("342364"), new BigInteger("393958"), new BigInteger("134877036712")), - // Test case 3: One number is zero - Arguments.of(BigInteger.ZERO, new BigInteger("5678"), BigInteger.ZERO), - // Test case 4: Both numbers are zero - Arguments.of(BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO), - // Test case 5: Single-digit numbers - Arguments.of(new BigInteger("9"), new BigInteger("8"), new BigInteger("72"))); + // Test case 1: Two small numbers + Arguments.of(new BigInteger("1234"), new BigInteger("5678"), new BigInteger("7006652")), + // Test case 2: Two large numbers + Arguments.of(new BigInteger("342364"), new BigInteger("393958"), new BigInteger("134877036712")), + // Test case 3: One number is zero + Arguments.of(BigInteger.ZERO, new BigInteger("5678"), BigInteger.ZERO), + // Test case 4: Both numbers are zero + Arguments.of(BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO), + // Test case 5: Single-digit numbers + Arguments.of(new BigInteger("9"), new BigInteger("8"), new BigInteger("72"))); } /** @@ -46,8 +47,8 @@ static Stream provideTestCases() { * This method runs the Karatsuba multiplication algorithm for multiple test cases. *

    * - * @param x the first number to multiply - * @param y the second number to multiply + * @param x the first number to multiply + * @param y the second number to multiply * @param expected the expected result of x * y */ @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java b/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java index 73da509723c5..a1b82e06e86f 100644 --- a/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java +++ b/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java index 705f1a1006fa..49dd7245d47d 100644 --- a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java @@ -10,18 +10,22 @@ public class LeonardoNumberTest { void leonardoNumberNegative() { assertThrows(ArithmeticException.class, () -> LeonardoNumber.leonardoNumber(-1)); } + @Test void leonardoNumberZero() { assertEquals(1, LeonardoNumber.leonardoNumber(0)); } + @Test void leonardoNumberOne() { assertEquals(1, LeonardoNumber.leonardoNumber(1)); } + @Test void leonardoNumberFive() { assertEquals(15, LeonardoNumber.leonardoNumber(5)); } + @Test void leonardoNumberTwenty() { assertEquals(21891, LeonardoNumber.leonardoNumber(20)); diff --git a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java index a2763047acf0..7ea726edf2d1 100644 --- a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java @@ -14,7 +14,9 @@ void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + LiouvilleLambdaFunction.liouvilleLambda(number); + }); String actualMessage = exception.getMessage(); // then @@ -28,7 +30,9 @@ void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + LiouvilleLambdaFunction.liouvilleLambda(number); + }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java index 3576268c5d0c..87666ea86885 100644 --- a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java +++ b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java @@ -10,16 +10,19 @@ void lucasSeriesTwo() { assertEquals(2, LucasSeries.lucasSeries(1)); assertEquals(2, LucasSeries.lucasSeriesIteration(1)); } + @Test void lucasSeriesOne() { assertEquals(1, LucasSeries.lucasSeries(2)); assertEquals(1, LucasSeries.lucasSeriesIteration(2)); } + @Test void lucasSeriesSeven() { assertEquals(7, LucasSeries.lucasSeries(5)); assertEquals(7, LucasSeries.lucasSeriesIteration(5)); } + @Test void lucasSeriesEleven() { assertEquals(123, LucasSeries.lucasSeries(11)); diff --git a/src/test/java/com/thealgorithms/maths/MatrixRankTest.java b/src/test/java/com/thealgorithms/maths/MatrixRankTest.java index 415b84ec43f8..a1169417a5eb 100644 --- a/src/test/java/com/thealgorithms/maths/MatrixRankTest.java +++ b/src/test/java/com/thealgorithms/maths/MatrixRankTest.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -12,17 +13,17 @@ class MatrixRankTest { private static Stream validInputStream() { - return Stream.of(Arguments.of(3, new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(0, new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}), Arguments.of(1, new double[][] {{1}}), Arguments.of(2, new double[][] {{1, 2}, {3, 4}}), - Arguments.of(2, new double[][] {{3, -1, 2}, {-3, 1, 2}, {-6, 2, 4}}), Arguments.of(3, new double[][] {{2, 3, 0, 1}, {1, 0, 1, 2}, {-1, 1, 1, -2}, {1, 5, 3, -1}}), Arguments.of(1, new double[][] {{1, 2, 3}, {3, 6, 9}}), - Arguments.of(2, new double[][] {{0.25, 0.5, 0.75, 2}, {1.5, 3, 4.5, 6}, {1, 2, 3, 4}})); + return Stream.of(Arguments.of(3, new double[][]{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(0, new double[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}), Arguments.of(1, new double[][]{{1}}), Arguments.of(2, new double[][]{{1, 2}, {3, 4}}), + Arguments.of(2, new double[][]{{3, -1, 2}, {-3, 1, 2}, {-6, 2, 4}}), Arguments.of(3, new double[][]{{2, 3, 0, 1}, {1, 0, 1, 2}, {-1, 1, 1, -2}, {1, 5, 3, -1}}), Arguments.of(1, new double[][]{{1, 2, 3}, {3, 6, 9}}), + Arguments.of(2, new double[][]{{0.25, 0.5, 0.75, 2}, {1.5, 3, 4.5, 6}, {1, 2, 3, 4}})); } private static Stream invalidInputStream() { - return Stream.of(Arguments.of((Object) new double[][] {{1, 2}, {10}, {100, 200, 300}}), // jagged array - Arguments.of((Object) new double[][] {}), // empty matrix - Arguments.of((Object) new double[][] {{}, {}}), // empty row - Arguments.of((Object) null), // null matrix - Arguments.of((Object) new double[][] {{1, 2}, null}) // null row + return Stream.of(Arguments.of((Object) new double[][]{{1, 2}, {10}, {100, 200, 300}}), // jagged array + Arguments.of((Object) new double[][]{}), // empty matrix + Arguments.of((Object) new double[][]{{}, {}}), // empty row + Arguments.of((Object) null), // null matrix + Arguments.of((Object) new double[][]{{1, 2}, null}) // null row ); } diff --git a/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java b/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java index b954e6ff7511..82aa1c621f44 100644 --- a/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java +++ b/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java @@ -4,6 +4,7 @@ import java.math.BigDecimal; import java.util.Objects; + import org.junit.jupiter.api.Test; class MatrixUtilTest { @@ -11,41 +12,42 @@ class MatrixUtilTest { @Test void add() { final BigDecimal[][] matrix1 = { - {new BigDecimal(3), BigDecimal.TWO}, - {BigDecimal.ZERO, BigDecimal.ONE}, + {new BigDecimal(3), BigDecimal.TWO}, + {BigDecimal.ZERO, BigDecimal.ONE}, }; final BigDecimal[][] matrix2 = { - {BigDecimal.ONE, new BigDecimal(3)}, - {BigDecimal.TWO, BigDecimal.ZERO}, + {BigDecimal.ONE, new BigDecimal(3)}, + {BigDecimal.TWO, BigDecimal.ZERO}, }; final BigDecimal[][] actual = MatrixUtil.add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { - {new BigDecimal(4), new BigDecimal(5)}, - {BigDecimal.TWO, BigDecimal.ONE}, + {new BigDecimal(4), new BigDecimal(5)}, + {BigDecimal.TWO, BigDecimal.ONE}, }; assertTrue(Objects.deepEquals(actual, expected)); } + @Test void subtract() { final BigDecimal[][] matrix1 = { - {BigDecimal.ONE, new BigDecimal(4)}, - {new BigDecimal(5), new BigDecimal(6)}, + {BigDecimal.ONE, new BigDecimal(4)}, + {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] matrix2 = { - {BigDecimal.TWO, BigDecimal.ZERO}, - {new BigDecimal(-2), new BigDecimal(-3)}, + {BigDecimal.TWO, BigDecimal.ZERO}, + {new BigDecimal(-2), new BigDecimal(-3)}, }; final BigDecimal[][] actual = MatrixUtil.subtract(matrix1, matrix2).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)}, }; assertTrue(Objects.deepEquals(actual, expected)); @@ -55,23 +57,23 @@ void subtract() { void multiply() { final BigDecimal[][] matrix1 = { - {BigDecimal.ONE, BigDecimal.TWO, new BigDecimal(3)}, - {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, - {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}, + {BigDecimal.ONE, BigDecimal.TWO, new BigDecimal(3)}, + {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, + {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}, }; final BigDecimal[][] matrix2 = { - {BigDecimal.ONE, BigDecimal.TWO}, - {new BigDecimal(3), new BigDecimal(4)}, - {new BigDecimal(5), new BigDecimal(6)}, + {BigDecimal.ONE, BigDecimal.TWO}, + {new BigDecimal(3), new BigDecimal(4)}, + {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] actual = MatrixUtil.multiply(matrix1, matrix2).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)}, }; assertTrue(Objects.deepEquals(actual, expected)); diff --git a/src/test/java/com/thealgorithms/maths/MeansTest.java b/src/test/java/com/thealgorithms/maths/MeansTest.java index bb2b4b6d1c50..a07fdc2b2e1f 100644 --- a/src/test/java/com/thealgorithms/maths/MeansTest.java +++ b/src/test/java/com/thealgorithms/maths/MeansTest.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Set; import java.util.Vector; + import org.assertj.core.util.Lists; import org.assertj.core.util.Sets; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/maths/MillerRabinPrimalityCheckTest.java b/src/test/java/com/thealgorithms/maths/MillerRabinPrimalityCheckTest.java index d547cecf24cd..f472aae8b2d6 100644 --- a/src/test/java/com/thealgorithms/maths/MillerRabinPrimalityCheckTest.java +++ b/src/test/java/com/thealgorithms/maths/MillerRabinPrimalityCheckTest.java @@ -13,6 +13,7 @@ void testDeterministicMillerRabinForPrimes() { assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(123457)); assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(6472601713L)); } + @Test void testDeterministicMillerRabinForNotPrimes() { assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(1)); @@ -20,6 +21,7 @@ void testDeterministicMillerRabinForNotPrimes() { assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(123453)); assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(647260175)); } + @Test void testMillerRabinForPrimes() { assertTrue(MillerRabinPrimalityCheck.millerRabin(11, 5)); diff --git a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java index f3a6514ce633..e380a8287a31 100644 --- a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java @@ -14,7 +14,9 @@ void testMobiusForZero() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + MobiusFunction.mobius(number); + }); String actualMessage = exception.getMessage(); // then @@ -28,7 +30,9 @@ void testMobiusForNegativeNumber() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + MobiusFunction.mobius(number); + }); String actualMessage = exception.getMessage(); // then @@ -38,106 +42,106 @@ void testMobiusForNegativeNumber() { @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, + 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++) { diff --git a/src/test/java/com/thealgorithms/maths/ModeTest.java b/src/test/java/com/thealgorithms/maths/ModeTest.java index 629fd8bd580a..300275943b16 100644 --- a/src/test/java/com/thealgorithms/maths/ModeTest.java +++ b/src/test/java/com/thealgorithms/maths/ModeTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -15,7 +16,7 @@ void basicTest(final int[] expected, final int[] numbers) { } private static Stream tcStream() { - return Stream.of(Arguments.of(null, new int[] {}), Arguments.of(new int[] {5}, new int[] {5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {5, 4, 3, 2, 1}), - Arguments.of(new int[] {7}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), Arguments.of(new int[] {7, 9}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9})); + return Stream.of(Arguments.of(null, new int[]{}), Arguments.of(new int[]{5}, new int[]{5}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{5, 4, 3, 2, 1}), + Arguments.of(new int[]{7}, new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), Arguments.of(new int[]{7, 9}, new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9})); } } diff --git a/src/test/java/com/thealgorithms/maths/NonRepeatingElementTest.java b/src/test/java/com/thealgorithms/maths/NonRepeatingElementTest.java index 5f35cfe68a7a..b1b73352b19a 100644 --- a/src/test/java/com/thealgorithms/maths/NonRepeatingElementTest.java +++ b/src/test/java/com/thealgorithms/maths/NonRepeatingElementTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -13,7 +14,7 @@ private record TestData(int[] input, int[] expected) { } private static Stream provideTestCases() { - return Stream.of(new TestData(new int[] {1, 2, 1, 3, 2, 4}, new int[] {3, 4}), new TestData(new int[] {-1, -2, -1, -3, -2, -4}, new int[] {-3, -4}), new TestData(new int[] {-1, 2, 2, -3, -1, 4}, new int[] {-3, 4})); + return Stream.of(new TestData(new int[]{1, 2, 1, 3, 2, 4}, new int[]{3, 4}), new TestData(new int[]{-1, -2, -1, -3, -2, -4}, new int[]{-3, -4}), new TestData(new int[]{-1, 2, 2, -3, -1, 4}, new int[]{-3, 4})); } @ParameterizedTest @@ -25,6 +26,6 @@ void testFindNonRepeatingElements(TestData testData) { @Test public void testFindNonRepeatingElementsWithLargeNumbers() { - assertArrayEquals(new int[] {200000, 400000}, NonRepeatingElement.findNonRepeatingElements(new int[] {100000, 200000, 100000, 300000, 400000, 300000})); + assertArrayEquals(new int[]{200000, 400000}, NonRepeatingElement.findNonRepeatingElements(new int[]{100000, 200000, 100000, 300000, 400000, 300000})); } } diff --git a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java index 3fe58dadf8a5..af5fb8fd047e 100644 --- a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; + import org.junit.jupiter.api.Test; public class NthUglyNumberTest { @@ -23,10 +24,10 @@ public void testGetWithNewObject() { testCases.put(1963, 6973568802L); for (final var tc : testCases.entrySet()) { - var uglyNumbers = new NthUglyNumber(new int[] {2, 3, 5}); + var uglyNumbers = new NthUglyNumber(new int[]{2, 3, 5}); assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue()); - var otherUglyNumbers = new NthUglyNumber(new int[] {5, 25, 6, 2, 3, 5}); + var otherUglyNumbers = new NthUglyNumber(new int[]{5, 25, 6, 2, 3, 5}); assertEquals(otherUglyNumbers.get(tc.getKey()), tc.getValue()); } } @@ -46,7 +47,7 @@ public void testGetWithSameObject() { testCases.put(1658, 3072000L); testCases.put(6625, 4300800000L); - var uglyNumbers = new NthUglyNumber(new int[] {7, 2, 5, 3}); + var uglyNumbers = new NthUglyNumber(new int[]{7, 2, 5, 3}); for (final var tc : testCases.entrySet()) { assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue()); } @@ -56,24 +57,24 @@ public void testGetWithSameObject() { @Test public void testGetWithBase1() { - var uglyNumbers = new NthUglyNumber(new int[] {1}); + var uglyNumbers = new NthUglyNumber(new int[]{1}); assertEquals(uglyNumbers.get(10), 1); } @Test public void testGetWithBase2() { - var uglyNumbers = new NthUglyNumber(new int[] {2}); + var uglyNumbers = new NthUglyNumber(new int[]{2}); assertEquals(uglyNumbers.get(5), 32); } @Test public void testGetThrowsAnErrorForNegativeInput() { - var uglyNumbers = new NthUglyNumber(new int[] {1, 2}); + var uglyNumbers = new NthUglyNumber(new int[]{1, 2}); assertThrows(IllegalArgumentException.class, () -> uglyNumbers.get(-1)); } @Test public void testConstructorThrowsAnErrorForEmptyInput() { - assertThrows(IllegalArgumentException.class, () -> new NthUglyNumber(new int[] {})); + assertThrows(IllegalArgumentException.class, () -> new NthUglyNumber(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java b/src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java index 799052b22d83..059130da1063 100644 --- a/src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java +++ b/src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java @@ -4,6 +4,7 @@ import java.util.function.IntFunction; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -18,21 +19,21 @@ void testNumberOfDigits(final int expected, final int number, final IntFunction< } private static Stream testCases() { - final Integer[][] inputs = new Integer[][] { - {3, 100}, - {1, 0}, - {2, 12}, - {3, 123}, - {4, 1234}, - {5, 12345}, - {6, 123456}, - {7, 1234567}, - {8, 12345678}, - {9, 123456789}, - {9, 987654321}, + final Integer[][] inputs = new Integer[][]{ + {3, 100}, + {1, 0}, + {2, 12}, + {3, 123}, + {4, 1234}, + {5, 12345}, + {6, 123456}, + {7, 1234567}, + {8, 12345678}, + {9, 123456789}, + {9, 987654321}, }; - final IntFunction[] methods = new IntFunction[] {NumberOfDigits::numberOfDigits, NumberOfDigits::numberOfDigitsFast, NumberOfDigits::numberOfDigitsFaster, NumberOfDigits::numberOfDigitsRecursion}; + final IntFunction[] methods = new IntFunction[]{NumberOfDigits::numberOfDigits, NumberOfDigits::numberOfDigitsFast, NumberOfDigits::numberOfDigitsFaster, NumberOfDigits::numberOfDigitsRecursion}; return Stream.of(inputs).flatMap(input -> Stream.of(methods).map(method -> Arguments.of(input[0], input[1], method))); } diff --git a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java index a1512aacb30d..52934f0cf1bf 100644 --- a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java +++ b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java @@ -24,11 +24,11 @@ void testForTwo() { 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}, + {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); } @@ -37,14 +37,14 @@ void testForFive() { 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}, + {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/PollardRhoTest.java b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java index 3e2270a66a98..e9817398ecaa 100644 --- a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java +++ b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java @@ -40,7 +40,9 @@ void testPollardRhoForNumber239MustThrowException() { String expectedMessage = "GCD cannot be found."; // when - Exception exception = assertThrows(RuntimeException.class, () -> { PollardRho.pollardRho(number); }); + Exception exception = assertThrows(RuntimeException.class, () -> { + PollardRho.pollardRho(number); + }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java b/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java index ac8d2be17d7c..378c8db6f459 100644 --- a/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java +++ b/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java @@ -8,7 +8,7 @@ public class PowerOfTwoOrNotTest { @Test public void testPowerOfTwoOrNotForPowersOfTwo() { - final var powersOfTwo = new int[] {1, 2, 4, 8, 16, 32, 64}; + final var powersOfTwo = new int[]{1, 2, 4, 8, 16, 32, 64}; for (final var n : powersOfTwo) { assertTrue(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n)); } @@ -16,7 +16,7 @@ public void testPowerOfTwoOrNotForPowersOfTwo() { @Test public void testPowerOfTwoOrNotForNotPowersOfTwo() { - final var notPowersOfTwo = new int[] {-16, -8, -6, -5, -4, -3, -2, -1, 0, 3, 5, 6, 7, 9, 10, 11, 33, 63, 65, 1000, 9999}; + final var notPowersOfTwo = new int[]{-16, -8, -6, -5, -4, -3, -2, -1, 0, 3, 5, 6, 7, 9, 10, 11, 33, 63, 65, 1000, 9999}; for (final var n : notPowersOfTwo) { assertFalse(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n)); } diff --git a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java index 705cc6672818..76700b6a0a24 100644 --- a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java @@ -6,6 +6,7 @@ /** * Test case for Power using Recursion + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ diff --git a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java index 6994379d736a..0877118cb866 100644 --- a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java +++ b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/maths/SecondMinMaxTest.java b/src/test/java/com/thealgorithms/maths/SecondMinMaxTest.java index c744614e5cfa..8b592c230798 100644 --- a/src/test/java/com/thealgorithms/maths/SecondMinMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/SecondMinMaxTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -21,6 +22,7 @@ public TestCase(final int[] inInputArray, final int inSecondMin, final int inSec secondMin = inSecondMin; secondMax = inSecondMax; } + final int[] inputArray; final int secondMin; final int secondMax; @@ -28,19 +30,19 @@ public TestCase(final int[] inInputArray, final int inSecondMin, final int inSec @Test public void testForEmptyInputArray() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMin(new int[] {})); + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMin(new int[]{})); assertEquals(exception.getMessage(), EXP_MSG_ARR_LEN_LESS_2); } @Test public void testForArrayWithSingleElement() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMax(new int[] {1})); + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMax(new int[]{1})); assertEquals(exception.getMessage(), EXP_MSG_ARR_LEN_LESS_2); } @Test public void testForArrayWithSameElements() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMin(new int[] {1, 1, 1, 1})); + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> SecondMinMax.findSecondMin(new int[]{1, 1, 1, 1})); assertEquals(exception.getMessage(), EXP_MSG_ARR_SAME_ELE); } @@ -52,7 +54,7 @@ void numberTests(final TestCase tc) { } private static Stream inputStream() { - return Stream.of(Arguments.of(new TestCase(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2, 9)), Arguments.of(new TestCase(new int[] {5, 4, 5, 5, 5}, 5, 4)), Arguments.of(new TestCase(new int[] {-1, 0}, 0, -1)), - Arguments.of(new TestCase(new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}, -9, -2)), Arguments.of(new TestCase(new int[] {3, -2, 3, 9, -4, -4, 8}, -2, 8))); + return Stream.of(Arguments.of(new TestCase(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2, 9)), Arguments.of(new TestCase(new int[]{5, 4, 5, 5, 5}, 5, 4)), Arguments.of(new TestCase(new int[]{-1, 0}, 0, -1)), + Arguments.of(new TestCase(new int[]{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}, -9, -2)), Arguments.of(new TestCase(new int[]{3, -2, 3, 9, -4, -4, 8}, -2, 8))); } } diff --git a/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java b/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java index ebbd5df712fc..19189421c8a5 100644 --- a/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java +++ b/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java @@ -8,24 +8,24 @@ class SieveOfEratosthenesTest { @Test public void testfFindPrimesTill1() { - assertArrayEquals(new int[] {}, SieveOfEratosthenes.findPrimesTill(1)); + assertArrayEquals(new int[]{}, SieveOfEratosthenes.findPrimesTill(1)); } @Test public void testfFindPrimesTill2() { - assertArrayEquals(new int[] {2}, SieveOfEratosthenes.findPrimesTill(2)); + assertArrayEquals(new int[]{2}, SieveOfEratosthenes.findPrimesTill(2)); } @Test public void testfFindPrimesTill4() { - var primesTill4 = new int[] {2, 3}; + var primesTill4 = new int[]{2, 3}; assertArrayEquals(primesTill4, SieveOfEratosthenes.findPrimesTill(3)); assertArrayEquals(primesTill4, SieveOfEratosthenes.findPrimesTill(4)); } @Test public void testfFindPrimesTill40() { - var primesTill40 = new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}; + var primesTill40 = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}; assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(37)); assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(38)); assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(39)); @@ -34,7 +34,7 @@ public void testfFindPrimesTill40() { @Test public void testfFindPrimesTill240() { - var primesTill240 = new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239}; + var primesTill240 = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239}; assertArrayEquals(primesTill240, SieveOfEratosthenes.findPrimesTill(239)); assertArrayEquals(primesTill240, SieveOfEratosthenes.findPrimesTill(240)); } diff --git a/src/test/java/com/thealgorithms/maths/SolovayStrassenPrimalityTestTest.java b/src/test/java/com/thealgorithms/maths/SolovayStrassenPrimalityTestTest.java index 18cc35266c8c..1d1c874d173f 100644 --- a/src/test/java/com/thealgorithms/maths/SolovayStrassenPrimalityTestTest.java +++ b/src/test/java/com/thealgorithms/maths/SolovayStrassenPrimalityTestTest.java @@ -33,7 +33,7 @@ void setUp() { * @return an array of objects containing pairs of n and k values */ static Object[][] primeNumbers() { - return new Object[][] {{2, 1}, {3, 1}, {5, 5}, {7, 10}, {11, 20}, {13, 10}, {17, 5}, {19, 1}}; + return new Object[][]{{2, 1}, {3, 1}, {5, 5}, {7, 10}, {11, 20}, {13, 10}, {17, 5}, {19, 1}}; } /** @@ -54,7 +54,7 @@ void testPrimeNumbersWithDifferentNAndK(int n, int k) { * @return an array of objects containing pairs of n and k values */ static Object[][] compositeNumbers() { - return new Object[][] {{4, 1}, {6, 5}, {8, 10}, {9, 20}, {10, 1}, {12, 5}, {15, 10}}; + return new Object[][]{{4, 1}, {6, 5}, {8, 10}, {9, 20}, {10, 1}, {12, 5}, {15, 10}}; } /** diff --git a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java index d7e16e02602b..683ef9b9e34d 100644 --- a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; + import org.junit.jupiter.api.Test; class SquareFreeIntegerTest { @@ -13,35 +14,35 @@ void testIsSquareFreeInteger() { // given List listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, - 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, - 195, 197, 199, 201, 202, 203, 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, - 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, 377, 379, 381, 382, 383, 385, - 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, - 473, 474, 478, 479, 481, 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, 569, - 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, 653, 654, 655, 658, 659, 661, 662, - 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, - 758, 759, 761, 762, 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, 851, 853, - 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, 934, 935, 937, 938, 939, 941, 942, 943, - 946, 947, 949, 951, 953, 955, 957, 958, 959, 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, - 1034, 1037, 1038, 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, 1110, 1111, 1113, - 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, - 1191, 1193, 1194, 1195, 1198, 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, 1266, - 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, 1335, 1337, 1338, 1339, 1342, 1343, 1345, - 1346, 1347, 1349, 1351, 1353, 1354, 1355, 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, - 1423, 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, 1495, 1497, 1498, 1499, 1501, - 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, - 1581, 1582, 1583, 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, 1654, 1655, 1657, - 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, - 1743, 1745, 1747, 1749, 1751, 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, 1822, - 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, 1894, 1895, 1897, 1898, 1901, 1902, 1903, - 1905, 1906, 1907, 1909, 1910, 1913, 1914, 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, - 1983, 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, 2053, 2054, 2055, 2059, 2062, - 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, - 2139, 2141, 2143, 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, 2215, 2217, 2218, - 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, - 2297, 2298, 2301, 2302, 2305, 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, 2374, - 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, 2442, 2443, 2445, 2446, 2447, 2449, 2451, - 2453, 2454, 2455, 2458, 2459, 2461, 2462, 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); + 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, + 195, 197, 199, 201, 202, 203, 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, + 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, 377, 379, 381, 382, 383, 385, + 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, + 473, 474, 478, 479, 481, 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, 569, + 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, 653, 654, 655, 658, 659, 661, 662, + 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, + 758, 759, 761, 762, 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, 851, 853, + 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, 934, 935, 937, 938, 939, 941, 942, 943, + 946, 947, 949, 951, 953, 955, 957, 958, 959, 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, + 1034, 1037, 1038, 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, 1110, 1111, 1113, + 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, + 1191, 1193, 1194, 1195, 1198, 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, 1266, + 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, 1335, 1337, 1338, 1339, 1342, 1343, 1345, + 1346, 1347, 1349, 1351, 1353, 1354, 1355, 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, + 1423, 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, 1495, 1497, 1498, 1499, 1501, + 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, + 1581, 1582, 1583, 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, 1654, 1655, 1657, + 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, + 1743, 1745, 1747, 1749, 1751, 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, 1822, + 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, 1894, 1895, 1897, 1898, 1901, 1902, 1903, + 1905, 1906, 1907, 1909, 1910, 1913, 1914, 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, + 1983, 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, 2053, 2054, 2055, 2059, 2062, + 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, + 2139, 2141, 2143, 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, 2215, 2217, 2218, + 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, + 2297, 2298, 2301, 2302, 2305, 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, 2374, + 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, 2442, 2443, 2445, 2446, 2447, 2449, 2451, + 2453, 2454, 2455, 2458, 2459, 2461, 2462, 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); for (int i = 1; i <= 2500; i++) { // when @@ -60,7 +61,9 @@ void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + SquareFreeInteger.isSquareFreeInteger(number); + }); String actualMessage = exception.getMessage(); // then @@ -74,7 +77,9 @@ void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + SquareFreeInteger.isSquareFreeInteger(number); + }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java index 2c10d2d14f3e..566f065be208 100644 --- a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java @@ -7,30 +7,30 @@ public class StandardDeviationTest { @Test void test1() { - double[] t1 = new double[] {1, 1, 1, 1, 1}; + 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}; + 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}; + 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, + 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/SumOfDigitsTest.java b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java index 76aca44a2220..168ee44d2de0 100644 --- a/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java +++ b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.maths; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/maths/SumOfOddNumbersTest.java b/src/test/java/com/thealgorithms/maths/SumOfOddNumbersTest.java index 6470d7983888..6b52c4093f06 100644 --- a/src/test/java/com/thealgorithms/maths/SumOfOddNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/SumOfOddNumbersTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; diff --git a/src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java b/src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java index 6b80edf4b14c..d8a42084121f 100644 --- a/src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java +++ b/src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java @@ -4,6 +4,7 @@ import java.awt.Color; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/misc/InverseOfMatrixTest.java b/src/test/java/com/thealgorithms/misc/InverseOfMatrixTest.java index 2f20de444315..2ccc7a18ca02 100644 --- a/src/test/java/com/thealgorithms/misc/InverseOfMatrixTest.java +++ b/src/test/java/com/thealgorithms/misc/InverseOfMatrixTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,7 +18,7 @@ void testInvert(double[][] matrix, double[][] expectedInverse) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(new double[][] {{4, 7}, {2, 6}}, new double[][] {{0.6, -0.7}, {-0.2, 0.4}})); + return Stream.of(Arguments.of(new double[][]{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, new double[][]{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(new double[][]{{4, 7}, {2, 6}}, new double[][]{{0.6, -0.7}, {-0.2, 0.4}})); } private void assertMatrixEquals(double[][] expected, double[][] actual) { diff --git a/src/test/java/com/thealgorithms/misc/MatrixTransposeTest.java b/src/test/java/com/thealgorithms/misc/MatrixTransposeTest.java index cf668807b819..035624da5f6f 100644 --- a/src/test/java/com/thealgorithms/misc/MatrixTransposeTest.java +++ b/src/test/java/com/thealgorithms/misc/MatrixTransposeTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -11,8 +12,8 @@ public class MatrixTransposeTest { private static Stream provideValidMatrixTestCases() { - return Stream.of(Arguments.of(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, new int[][] {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}, "Transpose of square matrix"), Arguments.of(new int[][] {{1, 2}, {3, 4}, {5, 6}}, new int[][] {{1, 3, 5}, {2, 4, 6}}, "Transpose of rectangular matrix"), - Arguments.of(new int[][] {{1, 2, 3}}, new int[][] {{1}, {2}, {3}}, "Transpose of single-row matrix"), Arguments.of(new int[][] {{1}, {2}, {3}}, new int[][] {{1, 2, 3}}, "Transpose of single-column matrix")); + return Stream.of(Arguments.of(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, new int[][]{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}, "Transpose of square matrix"), Arguments.of(new int[][]{{1, 2}, {3, 4}, {5, 6}}, new int[][]{{1, 3, 5}, {2, 4, 6}}, "Transpose of rectangular matrix"), + Arguments.of(new int[][]{{1, 2, 3}}, new int[][]{{1}, {2}, {3}}, "Transpose of single-row matrix"), Arguments.of(new int[][]{{1}, {2}, {3}}, new int[][]{{1, 2, 3}}, "Transpose of single-column matrix")); } private static Stream provideInvalidMatrixTestCases() { diff --git a/src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java b/src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java index ec3a84b86c5b..87dfacd1a9cd 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class MedianOfMatrixtest { diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java index e64ae1b741b6..50dfc326e885 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -7,6 +7,7 @@ /** * Test case for Median Of Running Array Problem. + * * @author Ansh Shah (https://github.com/govardhanshah456) */ diff --git a/src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java b/src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java index 0da0cf0f804a..814924cdaae2 100644 --- a/src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java +++ b/src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java @@ -48,6 +48,6 @@ void testMirrorMatrixNullInput() { @Test void testMirrotMarixThrows() { - assertThrows(IllegalArgumentException.class, () -> MirrorOfMatrix.mirrorMatrix(new int[][] {{1}, {2, 3}})); + assertThrows(IllegalArgumentException.class, () -> MirrorOfMatrix.mirrorMatrix(new int[][]{{1}, {2, 3}})); } } diff --git a/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java b/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java index 130cd19b47b1..b4fee62fe9ff 100644 --- a/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java +++ b/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.Test; public class PalindromePrimeTest { diff --git a/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java b/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java index 7630d3e78dc7..a40a472555d2 100644 --- a/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,9 +18,9 @@ void testSortedRange(int[] nums, int key, int[] expectedRange, String descriptio } private static Stream provideSortedRangeTestCases() { - return Stream.of(Arguments.of(new int[] {1, 2, 3, 3, 3, 4, 5}, 3, new int[] {2, 4}, "Range for key 3 with multiple occurrences"), Arguments.of(new int[] {1, 2, 3, 3, 3, 4, 5}, 4, new int[] {5, 5}, "Range for key 4 with single occurrence"), - Arguments.of(new int[] {0, 1, 2}, 3, new int[] {-1, -1}, "Range for non-existent key"), Arguments.of(new int[] {}, 1, new int[] {-1, -1}, "Range in empty array"), Arguments.of(new int[] {1, 1, 1, 2, 3, 4, 5, 5, 5}, 1, new int[] {0, 2}, "Range for key at start"), - Arguments.of(new int[] {1, 1, 1, 2, 3, 4, 5, 5, 5}, 5, new int[] {6, 8}, "Range for key at end")); + return Stream.of(Arguments.of(new int[]{1, 2, 3, 3, 3, 4, 5}, 3, new int[]{2, 4}, "Range for key 3 with multiple occurrences"), Arguments.of(new int[]{1, 2, 3, 3, 3, 4, 5}, 4, new int[]{5, 5}, "Range for key 4 with single occurrence"), + Arguments.of(new int[]{0, 1, 2}, 3, new int[]{-1, -1}, "Range for non-existent key"), Arguments.of(new int[]{}, 1, new int[]{-1, -1}, "Range in empty array"), Arguments.of(new int[]{1, 1, 1, 2, 3, 4, 5, 5, 5}, 1, new int[]{0, 2}, "Range for key at start"), + Arguments.of(new int[]{1, 1, 1, 2, 3, 4, 5, 5, 5}, 5, new int[]{6, 8}, "Range for key at end")); } @ParameterizedTest(name = "Test case {index}: {3}") @@ -29,7 +30,7 @@ void testGetCountLessThan(int[] nums, int key, int expectedCount, String descrip } private static Stream provideGetCountLessThanTestCases() { - return Stream.of(Arguments.of(new int[] {1, 2, 3, 3, 4, 5}, 3, 4, "Count of elements less than existing key"), Arguments.of(new int[] {1, 2, 3, 3, 4, 5}, 4, 5, "Count of elements less than non-existing key"), Arguments.of(new int[] {1, 2, 2, 3}, 5, 4, "Count with all smaller elements"), - Arguments.of(new int[] {2, 3, 4, 5}, 1, 0, "Count with no smaller elements"), Arguments.of(new int[] {}, 1, 0, "Count in empty array")); + return Stream.of(Arguments.of(new int[]{1, 2, 3, 3, 4, 5}, 3, 4, "Count of elements less than existing key"), Arguments.of(new int[]{1, 2, 3, 3, 4, 5}, 4, 5, "Count of elements less than non-existing key"), Arguments.of(new int[]{1, 2, 2, 3}, 5, 4, "Count with all smaller elements"), + Arguments.of(new int[]{2, 3, 4, 5}, 1, 0, "Count with no smaller elements"), Arguments.of(new int[]{}, 1, 0, "Count in empty array")); } } diff --git a/src/test/java/com/thealgorithms/misc/SparsityTest.java b/src/test/java/com/thealgorithms/misc/SparsityTest.java index b93e4f44937d..0389373e9e78 100644 --- a/src/test/java/com/thealgorithms/misc/SparsityTest.java +++ b/src/test/java/com/thealgorithms/misc/SparsityTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -19,9 +20,9 @@ public void testSparsity(double[][] matrix, double expectedSparsity, String desc } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, 1.0, "Matrix with all zero elements"), Arguments.of(new double[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 0.0, "Matrix with no zero elements"), - Arguments.of(new double[][] {{0, 2, 0}, {4, 0, 6}, {0, 8, 0}}, 5.0 / 9.0, "Matrix with mixed elements"), Arguments.of(new double[][] {{0, 1, 0, 2, 0}}, 3.0 / 5.0, "Single-row matrix"), Arguments.of(new double[][] {{1}, {0}, {0}, {2}}, 2.0 / 4.0, "Single-column matrix"), - Arguments.of(new double[][] {{0}}, 1.0, "Matrix with a single zero element"), Arguments.of(new double[][] {{5}}, 0.0, "Matrix with a single non-zero element")); + return Stream.of(Arguments.of(new double[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, 1.0, "Matrix with all zero elements"), Arguments.of(new double[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 0.0, "Matrix with no zero elements"), + Arguments.of(new double[][]{{0, 2, 0}, {4, 0, 6}, {0, 8, 0}}, 5.0 / 9.0, "Matrix with mixed elements"), Arguments.of(new double[][]{{0, 1, 0, 2, 0}}, 3.0 / 5.0, "Single-row matrix"), Arguments.of(new double[][]{{1}, {0}, {0}, {2}}, 2.0 / 4.0, "Single-column matrix"), + Arguments.of(new double[][]{{0}}, 1.0, "Matrix with a single zero element"), Arguments.of(new double[][]{{5}}, 0.0, "Matrix with a single non-zero element")); } @ParameterizedTest(name = "Test case {index}: {1}") @@ -31,6 +32,6 @@ public void testSparsityExceptions(double[][] matrix, String description) { } private static Stream provideExceptionTestCases() { - return Stream.of(Arguments.of(new double[][] {}, "Empty matrix should throw IllegalArgumentException")); + return Stream.of(Arguments.of(new double[][]{}, "Empty matrix should throw IllegalArgumentException")); } } diff --git a/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java b/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java index 5353168216ec..79492f9c5b0e 100644 --- a/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java +++ b/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -39,14 +40,14 @@ public void testHashMap(int[] nums, int target, List> expected) { } private static Stream bruteForceTestProvider() { - return Stream.of(Arguments.of(new int[] {1, 2, -3, 4, -2, -1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-3, -1, 4))), Arguments.of(new int[] {1, 2, 3, 4, 5}, 50, new ArrayList<>())); + return Stream.of(Arguments.of(new int[]{1, 2, -3, 4, -2, -1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-3, -1, 4))), Arguments.of(new int[]{1, 2, 3, 4, 5}, 50, new ArrayList<>())); } private static Stream twoPointerTestProvider() { - return Stream.of(Arguments.of(new int[] {0, -1, 2, -3, 1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-1, 0, 1))), Arguments.of(new int[] {-5, -4, -3, -2, -1}, -10, Arrays.asList(Arrays.asList(-5, -4, -1), Arrays.asList(-5, -3, -2)))); + return Stream.of(Arguments.of(new int[]{0, -1, 2, -3, 1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-1, 0, 1))), Arguments.of(new int[]{-5, -4, -3, -2, -1}, -10, Arrays.asList(Arrays.asList(-5, -4, -1), Arrays.asList(-5, -3, -2)))); } private static Stream hashMapTestProvider() { - return Stream.of(Arguments.of(new int[] {1, 2, -1, -4, 3, 0}, 2, Arrays.asList(Arrays.asList(-1, 0, 3), Arrays.asList(-1, 1, 2))), Arguments.of(new int[] {5, 7, 9, 11}, 10, new ArrayList<>()), Arguments.of(new int[] {}, 0, new ArrayList<>())); + return Stream.of(Arguments.of(new int[]{1, 2, -1, -4, 3, 0}, 2, Arrays.asList(Arrays.asList(-1, 0, 3), Arrays.asList(-1, 1, 2))), Arguments.of(new int[]{5, 7, 9, 11}, 10, new ArrayList<>()), Arguments.of(new int[]{}, 0, new ArrayList<>())); } } diff --git a/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java b/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java index 86e73ac0547c..a3d3966e7e00 100644 --- a/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java +++ b/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java @@ -8,6 +8,7 @@ /** * Test case for Two sum Problem. + * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ @@ -15,7 +16,7 @@ public class TwoSumProblemTest { @Test void testTwoSumExists() { - final int[] values = new int[] {2, 7, 11, 15}; + final int[] values = new int[]{2, 7, 11, 15}; final int target = 9; final var expected = Pair.of(0, 1); // values[0] + values[1] = 2 + 7 = 9 assertEquals(expected, TwoSumProblem.twoSum(values, target).get()); @@ -23,7 +24,7 @@ void testTwoSumExists() { @Test void testTwoSumNoSolution() { - final int[] values = new int[] {2, 7, 11, 15}; + final int[] values = new int[]{2, 7, 11, 15}; final int target = 3; assertFalse(TwoSumProblem.twoSum(values, target).isPresent()); } diff --git a/src/test/java/com/thealgorithms/misc/WordBoggleTest.java b/src/test/java/com/thealgorithms/misc/WordBoggleTest.java index 1d4ed7c5e737..cf27c9a0f84d 100644 --- a/src/test/java/com/thealgorithms/misc/WordBoggleTest.java +++ b/src/test/java/com/thealgorithms/misc/WordBoggleTest.java @@ -7,6 +7,7 @@ import java.util.Collection; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -17,16 +18,16 @@ class WordBoggleTest { @BeforeEach void setup() { - board = 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'}, + board = 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'}, }; } @@ -39,8 +40,8 @@ void testBoggleBoard(String[] words, List expectedWords, String testDesc } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new String[] {"this", "is", "not", "a", "simple", "test", "boggle", "board", "REPEATED", "NOTRE_PEATED"}, Arrays.asList("this", "is", "a", "simple", "board", "boggle", "NOTRE_PEATED"), "All words"), - Arguments.of(new String[] {"xyz", "hello", "world"}, List.of(), "No matching words"), Arguments.of(new String[] {}, List.of(), "Empty words array"), Arguments.of(new String[] {"this", "this", "board", "board"}, Arrays.asList("this", "board"), "Duplicate words in input")); + return Stream.of(Arguments.of(new String[]{"this", "is", "not", "a", "simple", "test", "boggle", "board", "REPEATED", "NOTRE_PEATED"}, Arrays.asList("this", "is", "a", "simple", "board", "boggle", "NOTRE_PEATED"), "All words"), + Arguments.of(new String[]{"xyz", "hello", "world"}, List.of(), "No matching words"), Arguments.of(new String[]{}, List.of(), "Empty words array"), Arguments.of(new String[]{"this", "this", "board", "board"}, Arrays.asList("this", "board"), "Duplicate words in input")); } @ParameterizedTest @@ -52,6 +53,6 @@ void testBoggleBoardSpecialCases(char[][] specialBoard, String[] words, Collecti } private static Stream provideSpecialCases() { - return Stream.of(Arguments.of(new char[0][0], new String[] {"this", "is", "a", "test"}, List.of(), "Empty board")); + return Stream.of(Arguments.of(new char[0][0], new String[]{"this", "is", "a", "test"}, List.of(), "Empty board")); } } diff --git a/src/test/java/com/thealgorithms/others/BFPRTTest.java b/src/test/java/com/thealgorithms/others/BFPRTTest.java index bb7c8f074864..6ea655518988 100644 --- a/src/test/java/com/thealgorithms/others/BFPRTTest.java +++ b/src/test/java/com/thealgorithms/others/BFPRTTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -18,7 +19,7 @@ void testGetMinKNumsByBFPRT(int[] arr, int k, int[] expected) { } private static Stream minKNumsTestData() { - return Stream.of(Arguments.of(new int[] {11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9}, 5, new int[] {1, 1, 2, 2, 2}), Arguments.of(new int[] {3, 2, 1}, 2, new int[] {1, 2}), Arguments.of(new int[] {7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, new int[] {1, 2, 3})); + return Stream.of(Arguments.of(new int[]{11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9}, 5, new int[]{1, 1, 2, 2, 2}), Arguments.of(new int[]{3, 2, 1}, 2, new int[]{1, 2}), Arguments.of(new int[]{7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, new int[]{1, 2, 3})); } @ParameterizedTest @@ -29,6 +30,6 @@ void testGetMinKthByBFPRT(int[] arr, int k, int expected) { } private static Stream minKthTestData() { - return Stream.of(Arguments.of(new int[] {3, 2, 1}, 2, 2), Arguments.of(new int[] {7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, 3), Arguments.of(new int[] {5, 8, 6, 3, 2, 7, 1, 4}, 4, 4)); + return Stream.of(Arguments.of(new int[]{3, 2, 1}, 2, 2), Arguments.of(new int[]{7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, 3), Arguments.of(new int[]{5, 8, 6, 3, 2, 7, 1, 4}, 4, 4)); } } diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java index 296cf1ca1c04..77a1fab6b86d 100644 --- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; /** @@ -20,8 +21,8 @@ class BestFitCPUTest { @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)); assertEquals(testMemAllocation, memAllocation); @@ -30,8 +31,8 @@ void testFitForUseOfOneBlock() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -40,8 +41,8 @@ void testFitForEqualProcecesses() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -50,8 +51,8 @@ void testFitForNoEmptyBlockCell() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -60,8 +61,8 @@ void testFitForSameInputDifferentQuery() { @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)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/BoyerMooreTest.java b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java index 8416535b2111..efbfc2a30a55 100644 --- a/src/test/java/com/thealgorithms/others/BoyerMooreTest.java +++ b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.others; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -15,7 +16,7 @@ void checkWhenMajorityExists(int expected, int[] input) { } private static Stream inputStreamWithExistingMajority() { - return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 2}), Arguments.of(10, new int[] {10, 10, 20}), Arguments.of(10, new int[] {10, 20, 10}), Arguments.of(10, new int[] {20, 10, 10}), Arguments.of(4, new int[] {1, 4, 2, 4, 4, 5, 4}), Arguments.of(-1, new int[] {-1})); + return Stream.of(Arguments.of(5, new int[]{5, 5, 5, 2}), Arguments.of(10, new int[]{10, 10, 20}), Arguments.of(10, new int[]{10, 20, 10}), Arguments.of(10, new int[]{20, 10, 10}), Arguments.of(4, new int[]{1, 4, 2, 4, 4, 5, 4}), Arguments.of(-1, new int[]{-1})); } @ParameterizedTest @@ -25,6 +26,6 @@ void checkWhenMajorityExists(int[] input) { } private static Stream inputStreamWithoutMajority() { - return Stream.of(Arguments.of(new int[] {10, 10, 20, 20, 30, 30}), Arguments.of(new int[] {10, 20, 30, 40, 50}), Arguments.of(new int[] {1, 2}), Arguments.of(new int[] {})); + return Stream.of(Arguments.of(new int[]{10, 10, 20, 20, 30, 30}), Arguments.of(new int[]{10, 20, 30, 40, 50}), Arguments.of(new int[]{1, 2}), Arguments.of(new int[]{})); } } diff --git a/src/test/java/com/thealgorithms/others/ConwayTest.java b/src/test/java/com/thealgorithms/others/ConwayTest.java index f4c3051a1fe2..6740ae2fb1cd 100644 --- a/src/test/java/com/thealgorithms/others/ConwayTest.java +++ b/src/test/java/com/thealgorithms/others/ConwayTest.java @@ -13,15 +13,15 @@ public void testGenerateWith1() { @Test public void testGenerateWith123456() { assertEquals( - "13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", - Conway.generateList("123456", 20).get(11)); + "13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", + Conway.generateList("123456", 20).get(11)); } @Test public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C() { assertEquals( - "311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", - Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); + "311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", + Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); } @Test diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java index 57b6e189b116..297e344f47a9 100644 --- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; /** @@ -20,8 +21,8 @@ class FirstFitCPUTest { @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)); assertEquals(testMemAllocation, memAllocation); @@ -30,8 +31,8 @@ void testFitForUseOfOneBlock() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -40,8 +41,8 @@ void testFitForEqualProcecesses() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -50,8 +51,8 @@ void testFitForNoEmptyBlockCell() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -60,8 +61,8 @@ void testFitForSameInputDifferentQuery() { @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)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/FloydTriangleTest.java b/src/test/java/com/thealgorithms/others/FloydTriangleTest.java index afa280c09838..68e616dcb7b4 100644 --- a/src/test/java/com/thealgorithms/others/FloydTriangleTest.java +++ b/src/test/java/com/thealgorithms/others/FloydTriangleTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class FloydTriangleTest { diff --git a/src/test/java/com/thealgorithms/others/LineSweepTest.java b/src/test/java/com/thealgorithms/others/LineSweepTest.java index 59fd0fafb068..f27a20331b8c 100644 --- a/src/test/java/com/thealgorithms/others/LineSweepTest.java +++ b/src/test/java/com/thealgorithms/others/LineSweepTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -21,8 +22,8 @@ void testIsOverlap(OverlapTestCase testCase) { } private static Stream provideOverlapTestData() { - return Stream.of(Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {7, 20}, {15, 24}}, true)), Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {11, 20}, {21, 24}}, false)), Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {10, 20}, {21, 24}}, true)), - Arguments.of(new OverlapTestCase(new int[][] {{5, 10}}, false)), Arguments.of(new OverlapTestCase(new int[][] {{1, 5}, {1, 5}, {1, 5}}, true)), Arguments.of(new OverlapTestCase(new int[][] {{1, 1}, {2, 2}, {3, 3}}, false)), Arguments.of(new OverlapTestCase(new int[][] {}, false))); + return Stream.of(Arguments.of(new OverlapTestCase(new int[][]{{0, 10}, {7, 20}, {15, 24}}, true)), Arguments.of(new OverlapTestCase(new int[][]{{0, 10}, {11, 20}, {21, 24}}, false)), Arguments.of(new OverlapTestCase(new int[][]{{0, 10}, {10, 20}, {21, 24}}, true)), + Arguments.of(new OverlapTestCase(new int[][]{{5, 10}}, false)), Arguments.of(new OverlapTestCase(new int[][]{{1, 5}, {1, 5}, {1, 5}}, true)), Arguments.of(new OverlapTestCase(new int[][]{{1, 1}, {2, 2}, {3, 3}}, false)), Arguments.of(new OverlapTestCase(new int[][]{}, false))); } @ParameterizedTest @@ -32,6 +33,6 @@ void testFindMaximumEndPoint(MaximumEndPointTestCase testCase) { } private static Stream provideMaximumEndPointTestData() { - return Stream.of(Arguments.of(new MaximumEndPointTestCase(new int[][] {{10, 20}, {1, 100}, {14, 16}, {1, 8}}, 100))); + return Stream.of(Arguments.of(new MaximumEndPointTestCase(new int[][]{{10, 20}, {1, 100}, {14, 16}, {1, 8}}, 100))); } } diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java index 1014f39a26bc..94b8be8ff5e1 100644 --- a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java +++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java @@ -8,6 +8,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -72,6 +73,6 @@ private static Stream provideNumbersAndBasesForExceptions() { private static Stream provideNumbersForLowestBasePalindrome() { return Stream.of(Arguments.of(0, 2), Arguments.of(1, 2), Arguments.of(2, 3), Arguments.of(3, 2), Arguments.of(10, 3), Arguments.of(11, 10), Arguments.of(15, 2), Arguments.of(39, 12), Arguments.of(44, 10), Arguments.of(58, 28), Arguments.of(69, 22), Arguments.of(79, 78), Arguments.of(87, 28), - Arguments.of(90, 14), Arguments.of(5591, 37), Arguments.of(5895, 130), Arguments.of(9950, 198), Arguments.of(9974, 4986)); + Arguments.of(90, 14), Arguments.of(5591, 37), Arguments.of(5895, 130), Arguments.of(9950, 198), Arguments.of(9974, 4986)); } } diff --git a/src/test/java/com/thealgorithms/others/MaximumSlidingWindowTest.java b/src/test/java/com/thealgorithms/others/MaximumSlidingWindowTest.java index 9209136a5af3..456bb9fdc371 100644 --- a/src/test/java/com/thealgorithms/others/MaximumSlidingWindowTest.java +++ b/src/test/java/com/thealgorithms/others/MaximumSlidingWindowTest.java @@ -19,7 +19,7 @@ void setUp() { // Test for a simple sliding window case @Test void testMaxSlidingWindowSimpleCase() { - nums = new int[] {1, 3, -1, -3, 5, 3, 6, 7}; + nums = new int[]{1, 3, -1, -3, 5, 3, 6, 7}; k = 3; int[] expected = {3, 3, 5, 5, 6, 7}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); @@ -28,7 +28,7 @@ void testMaxSlidingWindowSimpleCase() { // Test when window size is 1 (output should be the array itself) @Test void testMaxSlidingWindowWindowSizeOne() { - nums = new int[] {4, 2, 12, 11, -5}; + nums = new int[]{4, 2, 12, 11, -5}; k = 1; int[] expected = {4, 2, 12, 11, -5}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); @@ -37,7 +37,7 @@ void testMaxSlidingWindowWindowSizeOne() { // Test when the window size is equal to the array length (output should be a single max element) @Test void testMaxSlidingWindowWindowSizeEqualsArrayLength() { - nums = new int[] {4, 2, 12, 11, -5}; + nums = new int[]{4, 2, 12, 11, -5}; k = nums.length; int[] expected = {12}; // Maximum of the entire array assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); @@ -46,7 +46,7 @@ void testMaxSlidingWindowWindowSizeEqualsArrayLength() { // Test when the input array is empty @Test void testMaxSlidingWindowEmptyArray() { - nums = new int[] {}; + nums = new int[]{}; k = 3; int[] expected = {}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); @@ -55,7 +55,7 @@ void testMaxSlidingWindowEmptyArray() { // Test when the window size is larger than the array (should return empty) @Test void testMaxSlidingWindowWindowSizeLargerThanArray() { - nums = new int[] {1, 2, 3}; + nums = new int[]{1, 2, 3}; k = 5; int[] expected = {}; // Window size is too large, so no result assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); diff --git a/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java b/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java index f360e3f53546..0c29c1b58763 100644 --- a/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java +++ b/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -16,7 +17,7 @@ void testMaximumSubarraySum(int expected, int k, int[] arr) { } private static Stream inputStream() { - return Stream.of(Arguments.of(15, 3, new int[] {1, 5, 4, 2, 9, 9, 9}), Arguments.of(0, 3, new int[] {4, 4, 4}), Arguments.of(12, 3, new int[] {9, 9, 9, 1, 2, 3}), Arguments.of(0, 0, new int[] {9, 9, 9}), Arguments.of(0, 5, new int[] {9, 9, 9}), Arguments.of(9, 1, new int[] {9, 2, 3, 7}), - Arguments.of(15, 5, new int[] {1, 2, 3, 4, 5}), Arguments.of(6, 3, new int[] {-1, 2, 3, 1, -2, 4}), Arguments.of(10, 1, new int[] {10}), Arguments.of(0, 2, new int[] {7, 7, 7, 7}), Arguments.of(0, 3, new int[] {}), Arguments.of(0, 10, new int[] {1, 2, 3})); + return Stream.of(Arguments.of(15, 3, new int[]{1, 5, 4, 2, 9, 9, 9}), Arguments.of(0, 3, new int[]{4, 4, 4}), Arguments.of(12, 3, new int[]{9, 9, 9, 1, 2, 3}), Arguments.of(0, 0, new int[]{9, 9, 9}), Arguments.of(0, 5, new int[]{9, 9, 9}), Arguments.of(9, 1, new int[]{9, 2, 3, 7}), + Arguments.of(15, 5, new int[]{1, 2, 3, 4, 5}), Arguments.of(6, 3, new int[]{-1, 2, 3, 1, -2, 4}), Arguments.of(10, 1, new int[]{10}), Arguments.of(0, 2, new int[]{7, 7, 7, 7}), Arguments.of(0, 3, new int[]{}), Arguments.of(0, 10, new int[]{1, 2, 3})); } } diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java index 75fb3ab7c261..2dde719938e5 100644 --- a/src/test/java/com/thealgorithms/others/NextFitTest.java +++ b/src/test/java/com/thealgorithms/others/NextFitTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; /** @@ -20,8 +21,8 @@ class NextFitCPUTest { @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)); assertEquals(testMemAllocation, memAllocation); @@ -30,8 +31,8 @@ void testFitForUseOfOneBlock() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -40,8 +41,8 @@ void testFitForEqualProcecesses() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -50,8 +51,8 @@ void testFitForNoEmptyBlockCell() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -60,8 +61,8 @@ void testFitForSameInputDifferentQuery() { @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)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java b/src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java index 4901b9c0d3a1..ad76bda5a300 100644 --- a/src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java +++ b/src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.EmptyStackException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java b/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java index 23b99ae87d35..a384f0aef2dd 100644 --- a/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java +++ b/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Stack; + import org.junit.jupiter.api.Test; public class ReverseStackUsingRecursionTest { diff --git a/src/test/java/com/thealgorithms/others/SkylineProblemTest.java b/src/test/java/com/thealgorithms/others/SkylineProblemTest.java index 1ed5ced709c1..523505fb16d7 100644 --- a/src/test/java/com/thealgorithms/others/SkylineProblemTest.java +++ b/src/test/java/com/thealgorithms/others/SkylineProblemTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; + import org.junit.jupiter.api.Test; public class SkylineProblemTest { diff --git a/src/test/java/com/thealgorithms/others/SudokuTest.java b/src/test/java/com/thealgorithms/others/SudokuTest.java index 5018b2768302..aa28ed1efee2 100644 --- a/src/test/java/com/thealgorithms/others/SudokuTest.java +++ b/src/test/java/com/thealgorithms/others/SudokuTest.java @@ -15,8 +15,12 @@ void testIsSafe2() { assertFalse(Sudoku.isSafe(board, 0, 1, 3)); assertTrue(Sudoku.isSafe(board, 1, 2, 1)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> { Sudoku.isSafe(board, 10, 10, 5); }); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> { Sudoku.isSafe(board, -1, 0, 5); }); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + Sudoku.isSafe(board, 10, 10, 5); + }); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + Sudoku.isSafe(board, -1, 0, 5); + }); } @Test @@ -25,7 +29,9 @@ void testSolveSudoku() { assertTrue(Sudoku.solveSudoku(board, board.length)); assertEquals(1, board[0][1]); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> { Sudoku.solveSudoku(board, 10); }); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + Sudoku.solveSudoku(board, 10); + }); assertTrue(Sudoku.solveSudoku(board, -1)); } diff --git a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java index 986e72ea45b5..b331ef935174 100644 --- a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java +++ b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertIterableEquals; import java.util.List; + import org.junit.jupiter.api.Test; public class TestPrintMatrixInSpiralOrder { diff --git a/src/test/java/com/thealgorithms/others/TowerOfHanoiTest.java b/src/test/java/com/thealgorithms/others/TowerOfHanoiTest.java index ca9376dd48eb..8758ee1ffbc4 100644 --- a/src/test/java/com/thealgorithms/others/TowerOfHanoiTest.java +++ b/src/test/java/com/thealgorithms/others/TowerOfHanoiTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.Test; public class TowerOfHanoiTest { diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java index eb69f6056132..e343da9e08a1 100644 --- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; + import org.junit.jupiter.api.Test; /** @@ -20,8 +21,8 @@ class WorstFitCPUTest { @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)); assertEquals(testMemAllocation, memAllocation); @@ -30,8 +31,8 @@ void testFitForUseOfOneBlock() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -40,8 +41,8 @@ void testFitForEqualProcecesses() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -50,8 +51,8 @@ void testFitForNoEmptyBlockCell() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -60,8 +61,8 @@ void testFitForSameInputDifferentQuery() { @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)); assertEquals(testMemAllocation, memAllocation); @@ -70,8 +71,8 @@ void testFitForMoreBlocksNoFit() { @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)); 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 669f928cd247..45f076f211a3 100644 --- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java @@ -40,14 +40,18 @@ public void checkForLongDataBits() { @Test public void mismatchDataBits() { - Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("100010", "00011"); }); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { + HammingDistance.compute("100010", "00011"); + }); Assertions.assertThat(ex.getMessage()).contains("must have the same length"); } @Test public void mismatchDataBits2() { - Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("1", "11"); }); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { + HammingDistance.compute("1", "11"); + }); Assertions.assertThat(ex.getMessage()).contains("must have the same length"); } @@ -75,7 +79,9 @@ public void checkForInputOfLength1() { @Test public void computeThrowsExceptionWhenInputsAreNotBitStrs() { - Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("1A", "11"); }); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { + HammingDistance.compute("1A", "11"); + }); Assertions.assertThat(ex.getMessage()).contains("must be a binary string"); } diff --git a/src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java index 8ce290cb246f..fc2961ae04d8 100644 --- a/src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java index 87b3d12c8dcf..b3c7e039b605 100644 --- a/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java @@ -3,8 +3,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; + import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.Test; public class FCFSSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/FairShareSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/FairShareSchedulingTest.java index 7aa6e061c497..3c7fb0d440e9 100644 --- a/src/test/java/com/thealgorithms/scheduling/FairShareSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/FairShareSchedulingTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java index 2e1bb4cd0e20..bc9be351e27c 100644 --- a/src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java b/src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java index 538db92a1f26..1d2c9761d166 100644 --- a/src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java +++ b/src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java @@ -10,34 +10,34 @@ class JobSchedulingWithDeadlineTest { void testJobSequencingWithDeadlines1() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 4, 20), new JobSchedulingWithDeadline.Job(2, 1, 1, 10), new JobSchedulingWithDeadline.Job(3, 1, 1, 40), new JobSchedulingWithDeadline.Job(4, 1, 1, 30)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); - assertArrayEquals(new int[] {2, 60}, result); // Expected output: 2 jobs, 60 profit + assertArrayEquals(new int[]{2, 60}, result); // Expected output: 2 jobs, 60 profit } @Test void testJobSequencingWithDeadlines2() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 2, 100), new JobSchedulingWithDeadline.Job(2, 1, 1, 19), new JobSchedulingWithDeadline.Job(3, 1, 2, 27), new JobSchedulingWithDeadline.Job(4, 1, 1, 25), new JobSchedulingWithDeadline.Job(5, 1, 1, 15)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); - assertArrayEquals(new int[] {2, 127}, result); // Expected output: 2 jobs, 127 profit + assertArrayEquals(new int[]{2, 127}, result); // Expected output: 2 jobs, 127 profit } @Test void testJobSequencingWithDeadlinesWithArrivalTimes() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 2, 5, 50), new JobSchedulingWithDeadline.Job(2, 3, 4, 60), new JobSchedulingWithDeadline.Job(3, 1, 3, 20)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); - assertArrayEquals(new int[] {3, 130}, result); // All 3 jobs fit within their deadlines + assertArrayEquals(new int[]{3, 130}, result); // All 3 jobs fit within their deadlines } @Test void testJobSequencingWithDeadlinesNoJobs() { JobSchedulingWithDeadline.Job[] jobs = {}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); - assertArrayEquals(new int[] {0, 0}, result); // No jobs, 0 profit + assertArrayEquals(new int[]{0, 0}, result); // No jobs, 0 profit } @Test void testJobSequencingWithDeadlinesSingleJob() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 1, 50)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); - assertArrayEquals(new int[] {1, 50}, result); // 1 job scheduled, 50 profit + assertArrayEquals(new int[]{1, 50}, result); // 1 job scheduled, 50 profit } } diff --git a/src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java index 00fd8adcde27..07c57f9f82b1 100644 --- a/src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java index 16067fa8c22a..9f1e2a528286 100644 --- a/src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java index d28dcfeaaea3..470513672bf6 100644 --- a/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java @@ -9,7 +9,7 @@ public class NonPreemptivePrioritySchedulingTest { @Test public void testCalculateAverageWaitingTime() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority - new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; + new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); double expectedAvgWaitingTime = (0 + 5 + 15) / 3.0; // Waiting times: 0 for P2, 5 for P1, 15 for P3 @@ -21,7 +21,7 @@ public void testCalculateAverageWaitingTime() { @Test public void testCalculateAverageTurnaroundTime() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority - new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; + new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); @@ -34,7 +34,7 @@ public void testCalculateAverageTurnaroundTime() { @Test public void testStartTimeIsCorrect() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority - new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; + new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); // Check that the start time for each process is correctly set @@ -46,7 +46,7 @@ public void testStartTimeIsCorrect() { @Test public void testWithDelayedArrivalTimes() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 4, 1), // id, arrivalTime, burstTime, priority - new NonPreemptivePriorityScheduling.Process(2, 2, 3, 2), new NonPreemptivePriorityScheduling.Process(3, 4, 2, 3)}; + new NonPreemptivePriorityScheduling.Process(2, 2, 3, 2), new NonPreemptivePriorityScheduling.Process(3, 4, 2, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); // Test the start times considering delayed arrivals @@ -58,7 +58,7 @@ public void testWithDelayedArrivalTimes() { @Test public void testWithGapsInArrivals() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 6, 2), // id, arrivalTime, burstTime, priority - new NonPreemptivePriorityScheduling.Process(2, 8, 4, 1), new NonPreemptivePriorityScheduling.Process(3, 12, 5, 3)}; + new NonPreemptivePriorityScheduling.Process(2, 8, 4, 1), new NonPreemptivePriorityScheduling.Process(3, 12, 5, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); diff --git a/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java index ea692686afd2..360c544b44e3 100644 --- a/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java @@ -3,9 +3,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; + import java.util.Collection; import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -26,6 +28,6 @@ void testPreemptivePriorityScheduling(Collection processes, List static Stream provideProcessesAndExpectedSchedules() { return Stream.of(Arguments.of(List.of(new ProcessDetails("P1", 0, 5, 2), new ProcessDetails("P2", 1, 4, 4), new ProcessDetails("P3", 2, 2, 6), new ProcessDetails("P4", 4, 1, 8)), List.of("P1", "P2", "P3", "P3", "P4", "P2", "P2", "P2", "P1", "P1", "P1", "P1")), - Arguments.of(List.of(new ProcessDetails("P1", 2, 5, 3), new ProcessDetails("P2", 5, 3, 5), new ProcessDetails("P3", 7, 1, 9)), List.of("Idle", "Idle", "P1", "P1", "P1", "P2", "P2", "P3", "P2", "P1", "P1"))); + Arguments.of(List.of(new ProcessDetails("P1", 2, 5, 3), new ProcessDetails("P2", 5, 3, 5), new ProcessDetails("P3", 7, 1, 9)), List.of("Idle", "Idle", "P1", "P1", "P1", "P2", "P2", "P3", "P2", "P1", "P1"))); } } diff --git a/src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java index 0d379ee90b0e..3c0a28df6826 100644 --- a/src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java index 3da526601f5f..a41dd3b81a56 100644 --- a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java @@ -3,8 +3,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; + import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.Test; class RRSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java index aab5c64c847f..2837bd860a8e 100644 --- a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java @@ -4,17 +4,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.devutils.entities.ProcessDetails; + import java.util.ArrayList; + import org.junit.jupiter.api.Test; class SJFSchedulingTest { private ArrayList process; + void initialisation0() { process = new ArrayList<>(); process.add(new ProcessDetails("1", 0, 6)); process.add(new ProcessDetails("2", 1, 2)); } + void initialisation1() { process = new ArrayList<>(); @@ -33,12 +37,14 @@ void initialisation2() { process.add(new ProcessDetails("2", 1, 2)); process.add(new ProcessDetails("3", 2, 1)); } + void initialisation3() { process = new ArrayList<>(); process.add(new ProcessDetails("1", 0, 3)); process.add(new ProcessDetails("2", 5, 2)); process.add(new ProcessDetails("3", 9, 1)); } + @Test void constructor() { initialisation0(); @@ -91,6 +97,7 @@ void schedulingOfAShortestJobArrivingLast() { assertEquals("3", a.schedule.get(1)); assertEquals("2", a.schedule.get(2)); } + @Test void schedulingWithProcessesNotComingBackToBack() { initialisation3(); @@ -100,6 +107,7 @@ void schedulingWithProcessesNotComingBackToBack() { assertEquals("2", a.schedule.get(1)); assertEquals("3", a.schedule.get(2)); } + @Test void schedulingOfNothing() { process = new ArrayList<>(); diff --git a/src/test/java/com/thealgorithms/scheduling/SRTFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/SRTFSchedulingTest.java index 9cec31130164..3ef7dbe3ab5b 100644 --- a/src/test/java/com/thealgorithms/scheduling/SRTFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/SRTFSchedulingTest.java @@ -3,7 +3,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; + import java.util.ArrayList; + import org.junit.jupiter.api.Test; class SRTFSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java index 555a0941e7f5..5e6554e1590e 100644 --- a/src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java index ae04e725cde5..f75873d0ba0f 100644 --- a/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class CircularLookSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java index 06bd53c0b392..2d2af5aa155c 100644 --- a/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class CircularScanSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/diskscheduling/LookSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/diskscheduling/LookSchedulingTest.java index 91acc4837243..783b57999cd9 100644 --- a/src/test/java/com/thealgorithms/scheduling/diskscheduling/LookSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/diskscheduling/LookSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class LookSchedulingTest { diff --git a/src/test/java/com/thealgorithms/scheduling/diskscheduling/SSFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/diskscheduling/SSFSchedulingTest.java index 0239b0117f1b..cb9a2f778a20 100644 --- a/src/test/java/com/thealgorithms/scheduling/diskscheduling/SSFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/diskscheduling/SSFSchedulingTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/scheduling/diskscheduling/ScanSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/diskscheduling/ScanSchedulingTest.java index 1dbcd4893cb9..db172b83b231 100644 --- a/src/test/java/com/thealgorithms/scheduling/diskscheduling/ScanSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/diskscheduling/ScanSchedulingTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class ScanSchedulingTest { diff --git a/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java b/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java index 2017c11dfb3c..b170fe5e2c58 100644 --- a/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java +++ b/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java @@ -5,11 +5,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; + import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * Test Cases for Inverted Index with BM25 + * * @author Prayas Kumar (https://github.com/prayas7102) */ diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index 18f0afc6a0a6..b2d530a000c7 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; + import org.junit.jupiter.api.Test; public class BinarySearch2dArrayTest { diff --git a/src/test/java/com/thealgorithms/searches/BinarySearchTest.java b/src/test/java/com/thealgorithms/searches/BinarySearchTest.java index bd4620a7fa7d..d72a1087f94c 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearchTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.searches; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; import java.util.stream.IntStream; -import org.junit.jupiter.api.Test; /** * Unit tests for the BinarySearch class. @@ -19,7 +19,7 @@ void testBinarySearchFound() { Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int key = 7; int expectedIndex = 6; // Index of the key in the array - assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the found element should be 6."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the found element should be 6."); } /** @@ -31,7 +31,7 @@ void testBinarySearchNotFound() { Integer[] array = {1, 2, 3, 4, 5}; int key = 6; // Element not present in the array int expectedIndex = -1; // Key not found - assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array."); } /** @@ -43,7 +43,7 @@ void testBinarySearchFirstElement() { Integer[] array = {1, 2, 3, 4, 5}; int key = 1; // First element int expectedIndex = 0; // Index of the key in the array - assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the first element should be 0."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the first element should be 0."); } /** @@ -55,7 +55,7 @@ void testBinarySearchLastElement() { Integer[] array = {1, 2, 3, 4, 5}; int key = 5; // Last element int expectedIndex = 4; // Index of the key in the array - assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 4."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 4."); } /** @@ -67,7 +67,7 @@ void testBinarySearchSingleElementFound() { Integer[] array = {1}; int key = 1; // Only element present int expectedIndex = 0; // Index of the key in the array - assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the single element should be 0."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the single element should be 0."); } /** @@ -79,7 +79,7 @@ void testBinarySearchSingleElementNotFound() { Integer[] array = {1}; int key = 2; // Key not present int expectedIndex = -1; // Key not found - assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array."); } /** @@ -91,7 +91,7 @@ void testBinarySearchEmptyArray() { Integer[] array = {}; // Empty array int key = 1; // Key not present int expectedIndex = -1; // Key not found - assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in an empty array."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in an empty array."); } /** @@ -100,9 +100,10 @@ void testBinarySearchEmptyArray() { @Test void testBinarySearchLargeArray() { BinarySearch binarySearch = new BinarySearch(); - Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999 + Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[]::new); // Array from 0 to 9999 int key = 9999; // Last element int expectedIndex = 9999; // Index of the last element - assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 9999."); + Assertions.assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 9999."); } } + diff --git a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java index d05856dd29ad..5620e79fa56f 100644 --- a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java @@ -5,8 +5,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.Node; + import java.util.List; import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java b/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java index 2785d48b70cf..fb2f3c5a0c3c 100644 --- a/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java @@ -5,8 +5,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.Node; + import java.util.List; import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java b/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java index c84da531e8a4..5099b5ab34e0 100644 --- a/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.IntStream; + import org.junit.jupiter.api.Test; /** @@ -76,7 +77,7 @@ void testExponentialSearchEmptyArray() { @Test void testExponentialSearchLargeArray() { ExponentialSearch exponentialSearch = new ExponentialSearch(); - Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999 + Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[]::new); // Array from 0 to 9999 int key = 9999; int expectedIndex = 9999; assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the last element should be 9999."); diff --git a/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java b/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java index 801c33b1d09a..7f68ebcf4d19 100644 --- a/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.IntStream; + import org.junit.jupiter.api.Test; /** @@ -116,7 +117,7 @@ void testFibonacciSearchNullKey() { @Test void testFibonacciSearchLargeArray() { FibonacciSearch fibonacciSearch = new FibonacciSearch(); - Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999 + Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[]::new); // Array from 0 to 9999 int key = 9999; int expectedIndex = 9999; assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the last element should be 9999."); diff --git a/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java b/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java index b3b7e7ef129c..f064dcda1007 100644 --- a/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.IntStream; + import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/thealgorithms/searches/LinearSearchTest.java b/src/test/java/com/thealgorithms/searches/LinearSearchTest.java index 5c09dec6d578..9c6721a1cb61 100644 --- a/src/test/java/com/thealgorithms/searches/LinearSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/LinearSearchTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Random; + import org.junit.jupiter.api.Test; /** @@ -111,7 +112,7 @@ void testLinearSearchMultipleOccurrences() { void testLinearSearchRandomArray() { LinearSearch linearSearch = new LinearSearch(); Random random = new Random(); - Integer[] array = random.ints(0, 1000).distinct().limit(1000).boxed().toArray(Integer[] ::new); + Integer[] array = random.ints(0, 1000).distinct().limit(1000).boxed().toArray(Integer[]::new); Integer key = array[random.nextInt(array.length)]; // Key should be in the array assertEquals(java.util.Arrays.asList(array).indexOf(key), linearSearch.find(array, key), "The index of the found element should match."); } diff --git a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java index cf160b0ff4b5..60413ccd1870 100644 --- a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java +++ b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.Random; import java.util.stream.Collectors; + import org.junit.jupiter.api.Test; class QuickSelectTest { diff --git a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java index 39ac5bf037ea..2922e67bcf90 100644 --- a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java @@ -9,10 +9,10 @@ public class RowColumnWiseSorted2dArrayBinarySearchTest { @Test public void rowColumnSorted2dArrayBinarySearchTestMiddle() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 35; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -24,10 +24,10 @@ public void rowColumnSorted2dArrayBinarySearchTestMiddle() { @Test public void rowColumnSorted2dArrayBinarySearchTestSide() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 48; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -39,10 +39,10 @@ public void rowColumnSorted2dArrayBinarySearchTestSide() { @Test public void rowColumnSorted2dArrayBinarySearchTestUpper() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 20; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -54,10 +54,10 @@ public void rowColumnSorted2dArrayBinarySearchTestUpper() { @Test public void rowColumnSorted2dArrayBinarySearchTestUpperSide() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 40; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -69,10 +69,10 @@ public void rowColumnSorted2dArrayBinarySearchTestUpperSide() { @Test public void rowColumnSorted2dArrayBinarySearchTestLower() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 31; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -84,10 +84,10 @@ public void rowColumnSorted2dArrayBinarySearchTestLower() { @Test public void rowColumnSorted2dArrayBinarySearchTestLowerSide() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 51; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); @@ -99,10 +99,10 @@ public void rowColumnSorted2dArrayBinarySearchTestLowerSide() { @Test public void rowColumnSorted2dArrayBinarySearchTestNotFound() { Integer[][] arr = { - {10, 20, 30, 40}, - {15, 25, 35, 45}, - {18, 28, 38, 48}, - {21, 31, 41, 51}, + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, }; Integer target = 101; int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); diff --git a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java index ec22cbf38152..a8c373068f00 100644 --- a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java @@ -15,7 +15,7 @@ void testFindElementExists() { int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 4); - assertArrayEquals(new int[] {0, 3}, result, "Element 4 should be found at (0, 3)"); + assertArrayEquals(new int[]{0, 3}, result, "Element 4 should be found at (0, 3)"); } /** @@ -26,7 +26,7 @@ void testFindElementNotExists() { int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 1000); - assertArrayEquals(new int[] {-1, -1}, result, "Element 1000 should not be found"); + assertArrayEquals(new int[]{-1, -1}, result, "Element 1000 should not be found"); } /** @@ -37,7 +37,7 @@ void testFindSmallestElement() { int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, -10); - assertArrayEquals(new int[] {0, 0}, result, "Element -10 should be found at (0, 0)"); + assertArrayEquals(new int[]{0, 0}, result, "Element -10 should be found at (0, 0)"); } /** @@ -48,7 +48,7 @@ void testFindLargestElement() { int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 150); - assertArrayEquals(new int[] {4, 4}, result, "Element 150 should be found at (4, 4)"); + assertArrayEquals(new int[]{4, 4}, result, "Element 150 should be found at (4, 4)"); } /** @@ -58,7 +58,9 @@ void testFindLargestElement() { void testFindInEmptyArray() { int[][] arr = {}; - assertThrows(IllegalArgumentException.class, () -> { SaddlebackSearch.find(arr, 0, 0, 4); }); + assertThrows(IllegalArgumentException.class, () -> { + SaddlebackSearch.find(arr, 0, 0, 4); + }); } /** @@ -69,7 +71,7 @@ void testFindSingleElementExists() { int[][] arr = {{5}}; int[] result = SaddlebackSearch.find(arr, 0, 0, 5); - assertArrayEquals(new int[] {0, 0}, result, "Element 5 should be found at (0, 0)"); + assertArrayEquals(new int[]{0, 0}, result, "Element 5 should be found at (0, 0)"); } /** @@ -80,6 +82,6 @@ void testFindSingleElementNotExists() { int[][] arr = {{5}}; int[] result = SaddlebackSearch.find(arr, 0, 0, 10); - assertArrayEquals(new int[] {-1, -1}, result, "Element 10 should not be found in single element array"); + assertArrayEquals(new int[]{-1, -1}, result, "Element 10 should not be found in single element array"); } } diff --git a/src/test/java/com/thealgorithms/searches/UpperBoundTest.java b/src/test/java/com/thealgorithms/searches/UpperBoundTest.java index dc0cbdd97e19..baa8d47c9654 100644 --- a/src/test/java/com/thealgorithms/searches/UpperBoundTest.java +++ b/src/test/java/com/thealgorithms/searches/UpperBoundTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,10 +22,10 @@ void setUp() { int size = 100; int maxElement = 100; sortedArray = random.ints(size, 1, maxElement) - .distinct() // Ensure all elements are unique - .sorted() - .boxed() - .toArray(Integer[] ::new); + .distinct() // Ensure all elements are unique + .sorted() + .boxed() + .toArray(Integer[]::new); } @Test @@ -48,7 +49,7 @@ void testUpperBoundExactMatch() { @Test void testUpperBoundMultipleValues() { - Integer[] arrayWithDuplicates = new Integer[] {1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9}; // Test array with duplicates + Integer[] arrayWithDuplicates = new Integer[]{1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9}; // Test array with duplicates int key = 4; int index = upperBound.find(arrayWithDuplicates, key); diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/ConstrainedShuffleTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/ConstrainedShuffleTest.java new file mode 100644 index 000000000000..b1041b6d163e --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/ConstrainedShuffleTest.java @@ -0,0 +1,113 @@ +package com.thealgorithms.shufflealgorithm; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.thealgorithms.shufflealogrithm.ConstrainedShuffle; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ConstrainedShuffleTest { + + private int[] originalArray; + + @BeforeEach + void setUp() { + originalArray = new int[]{1, 2, 3, 4, 5}; + } + + // Test that shuffling preserves the length and original elements + @Test + void testPreserveArrayLengthAndElements() { + int[] arrayCopy = Arrays.copyOf(originalArray, originalArray.length); + ConstrainedShuffle.constrainedShuffle(arrayCopy); + + assertEquals(originalArray.length, arrayCopy.length, + "Array length should remain the same"); + + Set originalElements = new HashSet<>(); + for (int num : originalArray) { + originalElements.add(num); + } + + for (int num : arrayCopy) { + assertTrue(originalElements.contains(num), + "Array elements should be preserved"); + } + } + + // Test that the first and last elements remain unchanged after shuffle + @Test + void testFirstAndLastElementsFixed() { + int[] arrayCopy = Arrays.copyOf(originalArray, originalArray.length); + ConstrainedShuffle.constrainedShuffle(arrayCopy); + + assertEquals(originalArray[0], arrayCopy[0], + "First element should remain fixed"); + assertEquals(originalArray[originalArray.length - 1], + arrayCopy[arrayCopy.length - 1], + "Last element should remain fixed"); + } + + // Test that the function handles arrays with fewer than 3 elements without + // changes + @Test + void testArrayTooSmall() { + int[] smallArray = {1, 2}; + int[] expectedArray = {1, 2}; + + ConstrainedShuffle.constrainedShuffle(smallArray); + + assertArrayEquals( + expectedArray, smallArray, + "Array with fewer than 3 elements should remain unchanged"); + } + + // Test with null input (should handle gracefully without error) + @Test + void testNullArray() { + int[] nullArray = null; + ConstrainedShuffle.constrainedShuffle(nullArray); + + assertEquals(null, nullArray, "Null input should remain null"); + } + + // Test that elements between the first and last positions change order in + // larger arrays + @Test + void testInternalElementsShuffled() { + int[] arrayCopy = Arrays.copyOf(originalArray, originalArray.length); + boolean hasShuffled = false; + + for (int i = 0; i < 10; i++) { // Repeat shuffle to ensure randomness + ConstrainedShuffle.constrainedShuffle(arrayCopy); + + if (!Arrays.equals(arrayCopy, originalArray)) { + hasShuffled = true; + break; + } + } + + assertTrue(hasShuffled, + "Internal elements should shuffle between first and last positions"); + } + + // Test with an array that has all identical elements + @Test + void testArrayWithIdenticalElements() { + int[] identicalArray = {1, 1, 1, 1, 1}; + int[] expectedArray = {1, 1, 1, 1, 1}; + + ConstrainedShuffle.constrainedShuffle(identicalArray); + + assertArrayEquals( + expectedArray, identicalArray, + "Array with all identical elements should remain unchanged"); + } +} diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/GroupShuffleTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/GroupShuffleTest.java new file mode 100644 index 000000000000..ffa172476c02 --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/GroupShuffleTest.java @@ -0,0 +1,97 @@ +package com.thealgorithms.shufflealgorithm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.thealgorithms.shufflealogrithm.GroupShuffle; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class GroupShuffleTest { + + // Test case to check basic functionality + @Test + void testGroupShuffleBasic() { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + List> shuffledGroups = GroupShuffle.groupShuffle(array, 3); + + assertEquals(3, shuffledGroups.size()); // Expect 3 groups + assertTrue(shuffledGroups.stream().allMatch( + group -> group.size() <= 3)); // All groups should have size <= 3 + System.out.println("Shuffled Groups (Basic Test): " + + shuffledGroups); + } + + // Test case to check when group size is larger than array length + @Test + void testGroupShuffleLargeGroupSize() { + int[] array = {1, 2, 3}; + List> shuffledGroups = GroupShuffle.groupShuffle(array, 5); + + assertEquals(1, shuffledGroups.size()); // Expect 1 group with all elements + assertEquals( + Arrays.asList(1, 2, 3), + shuffledGroups.get(0)); // The group should contain all elements + System.out.println("Shuffled Groups (Large Group Size Test): " + + shuffledGroups); + } + + // Test case to check when the array is null + @Test + void testGroupShuffleNullArray() { + List> shuffledGroups = GroupShuffle.groupShuffle(null, 3); + + assertTrue(shuffledGroups.isEmpty()); // Expect empty list + System.out.println("Shuffled Groups (Null Array Test): " + + shuffledGroups); + } + + // Test case to check when group size is less than or equal to zero + @Test + void testGroupShuffleZeroOrNegativeGroupSize() { + int[] array = {1, 2, 3}; + List> shuffledGroups = GroupShuffle.groupShuffle(array, 0); + + assertTrue( + shuffledGroups.isEmpty()); // Expect empty list for group size zero + shuffledGroups = GroupShuffle.groupShuffle(array, -1); + assertTrue( + shuffledGroups.isEmpty()); // Expect empty list for negative group size + System.out.println("Shuffled Groups (Zero or Negative Group Size Test): " + + shuffledGroups); + } + + // Test case to check when the array has fewer than 3 elements + @Test + void testGroupShuffleSmallArray() { + int[] array = {1, 2}; + List> shuffledGroups = GroupShuffle.groupShuffle(array, 2); + + assertEquals(1, shuffledGroups.size()); // Expect 1 group with all elements + assertEquals( + Arrays.asList(1, 2), + shuffledGroups.get(0)); // The group should contain all elements + System.out.println("Shuffled Groups (Small Array Test): " + + shuffledGroups); + } + + // Test case to check the behavior when the group size is 1 + @Test + void testGroupShuffleGroupSizeOne() { + int[] array = {1, 2, 3, 4, 5}; + List> shuffledGroups = GroupShuffle.groupShuffle(array, 1); + + assertEquals(5, shuffledGroups.size()); // Expect 5 groups + for (int i = 0; i < 5; i++) { + assertEquals( + Arrays.asList(i + 1), + shuffledGroups.get(i)); // Each group should contain one element + } + System.out.println("Shuffled Groups (Group Size One Test): " + + shuffledGroups); + } +} + diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/ShuffleByRangeTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/ShuffleByRangeTest.java new file mode 100644 index 000000000000..b6b1d7473d3e --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/ShuffleByRangeTest.java @@ -0,0 +1,90 @@ +package com.thealgorithms.shufflealgorithm; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; + +import com.thealgorithms.shufflealogrithm.ShuffleByRange; + +public class ShuffleByRangeTest { + + // Test case for a basic shuffle within a valid range + @Test + void testShuffleByRangeBasic() { + int[] array = {1, 2, 3, 4, 5, 6}; + ShuffleByRange.shuffleByRange(array, 1, 5); + + // Verify that elements outside the specified range remain unchanged + Assertions.assertEquals(1, array[0], "First element should be unchanged"); + Assertions.assertEquals(6, array[5], "Last element should be unchanged"); + } + + // Test case for an empty array + @Test + void testShuffleByRangeEmptyArray() { + int[] array = {}; + ShuffleByRange.shuffleByRange(array, 0, 1); + Assertions.assertArrayEquals(new int[]{}, array); + } + + // Test case for a single element array + @Test + void testShuffleByRangeSingleElementArray() { + int[] array = {1}; + ShuffleByRange.shuffleByRange(array, 0, 1); + Assertions.assertArrayEquals(new int[]{1}, array); + } + + // Test case for invalid range: start index equal to end index + @Test + void testShuffleByRangeStartEqualsEnd() { + int[] array = {1, 2, 3, 4, 5}; + ShuffleByRange.shuffleByRange(array, 2, 2); + Assertions.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, array); + } + + // Test case for invalid range: start index out of bounds + @Test + void testShuffleByRangeStartOutOfBounds() { + int[] array = {1, 2, 3, 4, 5}; + ShuffleByRange.shuffleByRange(array, -1, 5); + Assertions.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, array); + } + + // Test case for invalid range: end index out of bounds + @Test + void testShuffleByRangeEndOutOfBounds() { + int[] array = {1, 2, 3, 4, 5}; + ShuffleByRange.shuffleByRange(array, 1, 6); + Assertions.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, array); + } + + // Test case for invalid range: start index greater than end index + @Test + void testShuffleByRangeStartGreaterThanEnd() { + int[] array = {1, 2, 3, 4, 5}; + ShuffleByRange.shuffleByRange(array, 3, 2); + Assertions.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, array); + } + + // Test case for shuffling a large array + @Test + void testShuffleByRangeLargeArray() { + int[] array = new int[1000]; + for (int i = 0; i < array.length; i++) { + array[i] = i + 1; // Filling array with values 1 to 1000 + } + ShuffleByRange.shuffleByRange(array, 250, 750); + + // Verify that the first 250 and last 250 elements remain unchanged + for (int i = 0; i < 250; i++) { + Assertions.assertEquals(i + 1, array[i], + "Elements at index " + i + " should be unchanged"); + } + for (int i = 750; i < 1000; i++) { + Assertions.assertEquals(i + 1, array[i], + "Elements at index " + i + " should be unchanged"); + } + } +} + + diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/UnderstandingShuffleAlgoTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/UnderstandingShuffleAlgoTest.java new file mode 100644 index 000000000000..9407fa6da61f --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/UnderstandingShuffleAlgoTest.java @@ -0,0 +1,97 @@ +package com.thealgorithms.shufflealgorithm; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.thealgorithms.shufflealogrithm.UnderstandingShuffleAlgo; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +public class UnderstandingShuffleAlgoTest { + + // Test case for basic functionality with a standard array + @Test + void testShuffleStandardArray() { + int[] array = {1, 2, 3, 4, 5}; + int[] originalArray = Arrays.copyOf(array, array.length); + + UnderstandingShuffleAlgo.shuffle(array); + + // Check that the shuffled array contains the same elements + Arrays.sort(originalArray); + Arrays.sort(array); + assertArrayEquals(originalArray, array); + } + + // Test case for an empty array + @Test + void testShuffleEmptyArray() { + int[] array = {}; + UnderstandingShuffleAlgo.shuffle(array); + assertArrayEquals(new int[]{}, array); // Should remain empty + } + + // Test case for a single element array + @Test + void testShuffleSingleElementArray() { + int[] array = {1}; + UnderstandingShuffleAlgo.shuffle(array); + assertArrayEquals(new int[]{1}, array); // Should remain unchanged + } + + // Test case for a null array + @Test + void testShuffleNullArray() { + int[] array = null; + assertThrows(NullPointerException.class, () -> { + UnderstandingShuffleAlgo.shuffle(array); // Expect a NullPointerException + }); + } + + // Test case for an array with duplicate elements + @Test + void testShuffleArrayWithDuplicates() { + int[] array = {1, 1, 2, 2, 3, 3}; + int[] originalArray = Arrays.copyOf(array, array.length); + + UnderstandingShuffleAlgo.shuffle(array); + + // Check that the shuffled array contains the same elements + Arrays.sort(originalArray); + Arrays.sort(array); + assertArrayEquals(originalArray, array); + } + + // Test case for large array + @Test + void testShuffleLargeArray() { + int[] array = new int[1000]; + for (int i = 0; i < array.length; i++) { + array[i] = i + 1; // Fill with numbers 1 to 1000 + } + + int[] originalArray = Arrays.copyOf(array, array.length); + UnderstandingShuffleAlgo.shuffle(array); + + // Check that the shuffled array contains the same elements + Arrays.sort(originalArray); + Arrays.sort(array); + assertArrayEquals(originalArray, array); + } + + // Test case for an already sorted array + @Test + void testShuffleSortedArray() { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int[] originalArray = Arrays.copyOf(array, array.length); + + UnderstandingShuffleAlgo.shuffle(array); + + // Check that the shuffled array contains the same elements + Arrays.sort(originalArray); + Arrays.sort(array); + assertArrayEquals(originalArray, array); + } +} diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/UniquePairShuffleTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/UniquePairShuffleTest.java new file mode 100644 index 000000000000..2f80d4bc22e6 --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/UniquePairShuffleTest.java @@ -0,0 +1,137 @@ +package com.thealgorithms.shufflealgorithm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.thealgorithms.shufflealogrithm.UniquePairShuffle; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +public class UniquePairShuffleTest { + + // Test case for standard even-length array + @Test + void testPairShuffleEvenArray() { + int[] array = {1, 2, 3, 4}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // There should be 2 pairs in the result + assertEquals(2, pairs.size()); + + // Check that all pairs are unique + Set uniquePairs = new HashSet<>(); + for (int[] pair : pairs) { + String pairString = + Math.min(pair[0], pair[1]) + "-" + Math.max(pair[0], pair[1]); + uniquePairs.add(pairString); + } + + assertEquals(2, uniquePairs.size()); // Should have 2 unique pairs + } + + // Test case for standard odd-length array + @Test + void testPairShuffleOddArray() { + int[] array = {1, 2, 3}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // Result should be empty for odd-length array + assertTrue(pairs.isEmpty()); + } + + // Test case for empty array + @Test + void testPairShuffleEmptyArray() { + int[] array = {}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // Result should be empty + assertTrue(pairs.isEmpty()); + } + + // Test case for single element array + @Test + void testPairShuffleSingleElementArray() { + int[] array = {1}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // Result should be empty for single-element array + assertTrue(pairs.isEmpty()); + } + + // Test case for two elements, adjusted to not expect a specific order + @Test + void testPairShuffleTwoElements() { + int[] array = {1, 2}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // There should be 1 pair in the result + assertEquals(1, pairs.size()); + int[] pair = pairs.get(0); + + // Check that the pair contains both elements, without specifying order + assertTrue((pair[0] == 1 && pair[1] == 2) || (pair[0] == 2 && pair[1] == 1)); + + // Alternatively, for clarity and to directly address the error, + // you could assert the pair's elements without considering order: + int min = Math.min(pair[0], pair[1]); + int max = Math.max(pair[0], pair[1]); + assertEquals(1, min, "First element of the pair should be 1 when ordered"); + assertEquals(2, max, "Second element of the pair should be 2 when ordered"); + } + + // Test case for larger even-length array + @Test + void testPairShuffleLargeEvenArray() { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // There should be 4 pairs in the result + assertEquals(4, pairs.size()); + + // Check that all pairs are unique + Set uniquePairs = new HashSet<>(); + for (int[] pair : pairs) { + String pairString = + Math.min(pair[0], pair[1]) + "-" + Math.max(pair[0], pair[1]); + uniquePairs.add(pairString); + } + + assertEquals(4, uniquePairs.size()); // Should have 4 unique pairs + } + + // Test case for larger odd-length array + @Test + void testPairShuffleLargeOddArray() { + int[] array = {1, 2, 3, 4, 5}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // Result should be empty for odd-length array + assertTrue(pairs.isEmpty()); + } + + // Test case for negative numbers in array + @Test + void testPairShuffleNegativeNumbers() { + int[] array = {-1, -2, -3, -4}; + List pairs = UniquePairShuffle.pairShuffle(array); + + // There should be 2 pairs in the result + assertEquals(2, pairs.size()); + + // Check that all pairs are unique + Set uniquePairs = new HashSet<>(); + for (int[] pair : pairs) { + String pairString = + Math.min(pair[0], pair[1]) + "-" + Math.max(pair[0], pair[1]); + uniquePairs.add(pairString); + } + + assertEquals(2, uniquePairs.size()); // Should have 2 unique pairs + } +} + diff --git a/src/test/java/com/thealgorithms/shufflealgorithm/WeightedShuffleTest.java b/src/test/java/com/thealgorithms/shufflealgorithm/WeightedShuffleTest.java new file mode 100644 index 000000000000..125d752c60ac --- /dev/null +++ b/src/test/java/com/thealgorithms/shufflealgorithm/WeightedShuffleTest.java @@ -0,0 +1,108 @@ +package com.thealgorithms.shufflealgorithm; + +import com.thealgorithms.shufflealogrithm.WeightedShuffle; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; + +import java.util.Arrays; + +public class WeightedShuffleTest { + + @Test + void testWeightedShuffleBasic() { + int[] array = {10, 20, 30}; + int[] weights = {1, 3, 2}; + WeightedShuffle.weightedShuffle(array, weights); + + // Check the array is not in its original order (a simple shuffle check) + Assertions.assertNotEquals(array[0], 10, "Array should be shuffled"); + Assertions.assertNotEquals(Arrays.toString(array), + Arrays.toString(new int[]{10, 20, 30}), + "Array should be shuffled"); + } + + + // Test case for empty array + @Test + void testWeightedShuffleEmptyArray() { + int[] array = {}; + int[] weights = {}; + WeightedShuffle.weightedShuffle(array, weights); + Assertions.assertArrayEquals(new int[]{}, array); + } + + // Test case for single element array + @Test + void testWeightedShuffleSingleElementArray() { + int[] array = {5}; + int[] weights = {10}; + WeightedShuffle.weightedShuffle(array, weights); + Assertions.assertArrayEquals(new int[]{5}, array); + } + + // Test case for multiple elements with same weight + @Test + void testWeightedShuffleSameWeights() { + int[] array = {1, 2, 3, 4}; + int[] weights = {1, 1, 1, 1}; // All elements have the same weight + WeightedShuffle.weightedShuffle(array, weights); + // The order should remain the same or be any permutation since weights are + // equal + boolean firstElementMatches = + array[0] == 1 + || + array[0] == 2 + || + array[0] == 3 + || + array[0] == 4; + Assertions.assertTrue(firstElementMatches); + } + + // Test case for null array + @Test + void testWeightedShuffleNullArray() { + int[] weights = {1, 2, 3}; + WeightedShuffle.weightedShuffle(null, weights); + // Should not throw any exception, but we can't assert anything since input + // is null + } + + // Test case for null weights + @Test + void testWeightedShuffleNullWeights() { + int[] array = {1, 2, 3}; + WeightedShuffle.weightedShuffle(array, null); + // Should not throw any exception and array should remain unchanged + Assertions.assertArrayEquals(new int[]{1, 2, 3}, array); + } + + // Test case for different lengths of array and weights + @Test + void testWeightedShuffleDifferentLengths() { + int[] array = {1, 2, 3}; + int[] weights = {1, 2}; // One less weight + WeightedShuffle.weightedShuffle(array, weights); + // Should not throw any exception, but we can't assert anything since input + // is invalid + Assertions.assertArrayEquals(new int[]{1, 2, 3}, + array); // Original array should remain unchanged + } + + // Test case for all elements with zero weight + @Test + void testWeightedShuffleZeroWeights() { + int[] array = {5, 10, 15}; + int[] weights = {0, 0, 0}; // All weights are zero + WeightedShuffle.weightedShuffle(array, weights); + // The order should remain the same or be any permutation since all weights + // are equal + boolean firstElementMatches = + array[0] == 5 + || + array[0] == 10 + || + array[0] == 15; + Assertions.assertTrue(firstElementMatches); + } +} diff --git a/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java b/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java index 8638a707a3e2..23feec23ff76 100644 --- a/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java +++ b/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java @@ -7,7 +7,7 @@ /** * Unit tests for the LongestSubstringWithoutRepeatingCharacters class. * - * @author (https://github.com/Chiefpatwal) + * @author (https : / / github.com / Chiefpatwal) */ public class LongestSubstringWithoutRepeatingCharactersTest { diff --git a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java index d8519147bc2e..360fa65d8cb3 100644 --- a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -18,12 +19,12 @@ public void testBeadSort(int[] inputArray, int[] expectedArray) { } private static Stream provideArraysForBeadSort() { - return Stream.of(Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {4}, new int[] {4}), Arguments.of(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}), - Arguments.of(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5})); + return Stream.of(Arguments.of(new int[]{}, new int[]{}), Arguments.of(new int[]{4}, new int[]{4}), Arguments.of(new int[]{6, 1, 99, 27, 15, 23, 36}, new int[]{1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[]{6, 1, 27, 15, 23, 27, 36, 23}, new int[]{1, 6, 15, 23, 23, 27, 27, 36}), + Arguments.of(new int[]{5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}), Arguments.of(new int[]{5, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 5})); } @Test public void testWithNegativeNumbers() { - assertThrows(IllegalArgumentException.class, () -> new BeadSort().sort(new int[] {3, 1, 4, 1, 5, -9})); + assertThrows(IllegalArgumentException.class, () -> new BeadSort().sort(new int[]{3, 1, 4, 1, 5, -9})); } } diff --git a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java index 8690a3f5435c..0252df0a8558 100644 --- a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java @@ -41,17 +41,17 @@ public void bubbleSortIntegerArray() { 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, + -231, + -6, + -6, + 1, + 4, + 9, + 12, + 23, + 23, + 54, + 78, }; assertArrayEquals(outputArray, expectedOutput); } @@ -59,35 +59,35 @@ public void bubbleSortIntegerArray() { @Test public void bubbleSortStringArray() { String[] inputArray = { - "cbf", - "auk", - "ó", - "(b", - "a", - ")", - "au", - "á", - "cba", - "auk", - "(a", - "bhy", - "cba", + "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", - "á", - "ó", + "(a", + "(b", + ")", + "a", + "au", + "auk", + "auk", + "bhy", + "cba", + "cba", + "cbf", + "á", + "ó", }; assertArrayEquals(outputArray, expectedOutput); } diff --git a/src/test/java/com/thealgorithms/sorts/CountingSortTest.java b/src/test/java/com/thealgorithms/sorts/CountingSortTest.java index 2426de6f2807..bf60a161aa9b 100644 --- a/src/test/java/com/thealgorithms/sorts/CountingSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CountingSortTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -12,10 +13,10 @@ record TestCase(int[] inputArray, int[] expectedArray) { } static Stream provideTestCases() { - return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {4}, new int[] {4}), new TestCase(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), new TestCase(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}), - new TestCase(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {3, -1, 4, 1, 5, -9}, new int[] {-9, -1, 1, 3, 4, 5}), - new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}), new TestCase(new int[] {3, 3, -1, -1, 2, 2, 0, 0}, new int[] {-1, -1, 0, 0, 2, 2, 3, 3}), new TestCase(new int[] {-3, -2, -1, -5, -4}, new int[] {-5, -4, -3, -2, -1}), - new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {4, -5, 10, 0}, new int[] {-5, 0, 4, 10})); + return Stream.of(new TestCase(new int[]{}, new int[]{}), new TestCase(new int[]{4}, new int[]{4}), new TestCase(new int[]{6, 1, 99, 27, 15, 23, 36}, new int[]{1, 6, 15, 23, 27, 36, 99}), new TestCase(new int[]{6, 1, 27, 15, 23, 27, 36, 23}, new int[]{1, 6, 15, 23, 23, 27, 27, 36}), + new TestCase(new int[]{5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5}), new TestCase(new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}), new TestCase(new int[]{5, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 5}), new TestCase(new int[]{3, -1, 4, 1, 5, -9}, new int[]{-9, -1, 1, 3, 4, 5}), + new TestCase(new int[]{0, 0, 0, 0}, new int[]{0, 0, 0, 0}), new TestCase(new int[]{3, 3, -1, -1, 2, 2, 0, 0}, new int[]{-1, -1, 0, 0, 2, 2, 3, 3}), new TestCase(new int[]{-3, -2, -1, -5, -4}, new int[]{-5, -4, -3, -2, -1}), + new TestCase(new int[]{1000, 500, 100, 50, 10, 5, 1}, new int[]{1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[]{4, -5, 10, 0}, new int[]{-5, 0, 4, 10})); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/sorts/FlashSortTest.java b/src/test/java/com/thealgorithms/sorts/FlashSortTest.java index 6b1a74403a59..b4cb9fc977f9 100644 --- a/src/test/java/com/thealgorithms/sorts/FlashSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/FlashSortTest.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; + import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; diff --git a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java index 78744973355d..61ba758b1ef7 100644 --- a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.Function; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java b/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java index 5677a7c95e09..fcc862f9d578 100644 --- a/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java +++ b/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -13,10 +14,10 @@ record TestCase(int[] inputArray, int[] expectedArray) { } static Stream provideTestCases() { - return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {1}, new int[] {1}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}), - new TestCase(new int[] {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}, new int[] {1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9}), new TestCase(new int[] {4, 2, 4, 3, 2, 1, 5}, new int[] {1, 2, 2, 3, 4, 4, 5}), new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}), - new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {1, 2, 3, 1, 2, 3, 1, 2, 3}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 3}), - new TestCase(new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), new TestCase(new int[] {2, 1}, new int[] {1, 2}), new TestCase(new int[] {1, 3, 2}, new int[] {1, 2, 3})); + return Stream.of(new TestCase(new int[]{}, new int[]{}), new TestCase(new int[]{1}, new int[]{1}), new TestCase(new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}), new TestCase(new int[]{5, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 5}), + new TestCase(new int[]{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}, new int[]{1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9}), new TestCase(new int[]{4, 2, 4, 3, 2, 1, 5}, new int[]{1, 2, 2, 3, 4, 4, 5}), new TestCase(new int[]{0, 0, 0, 0}, new int[]{0, 0, 0, 0}), + new TestCase(new int[]{1000, 500, 100, 50, 10, 5, 1}, new int[]{1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[]{1, 2, 3, 1, 2, 3, 1, 2, 3}, new int[]{1, 1, 1, 2, 2, 2, 3, 3, 3}), + new TestCase(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), new TestCase(new int[]{2, 1}, new int[]{1, 2}), new TestCase(new int[]{1, 3, 2}, new int[]{1, 2, 3})); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java index 0e7874584c3f..a0882d68ac27 100644 --- a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java +++ b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; public class MergeSortRecursiveTest { diff --git a/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java b/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java index d1772de83701..543f5d9b9b0f 100644 --- a/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -19,13 +20,13 @@ public void testPigeonholeSort(int[] inputArray, int[] expectedArray) { } private static Stream provideArraysForPigeonholeSort() { - return Stream.of(Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {4}, new int[] {4}), Arguments.of(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}), - Arguments.of(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5})); + return Stream.of(Arguments.of(new int[]{}, new int[]{}), Arguments.of(new int[]{4}, new int[]{4}), Arguments.of(new int[]{6, 1, 99, 27, 15, 23, 36}, new int[]{1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[]{6, 1, 27, 15, 23, 27, 36, 23}, new int[]{1, 6, 15, 23, 23, 27, 27, 36}), + Arguments.of(new int[]{5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}), Arguments.of(new int[]{5, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 5})); } @Test public void testWithNegativeNumbers() { - assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {3, 1, 4, 1, 5, -9})); - assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {-1})); + assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[]{3, 1, 4, 1, 5, -9})); + assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[]{-1})); } } diff --git a/src/test/java/com/thealgorithms/sorts/RadixSortTest.java b/src/test/java/com/thealgorithms/sorts/RadixSortTest.java index 24ab52b199aa..bb140eb36b3b 100644 --- a/src/test/java/com/thealgorithms/sorts/RadixSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/RadixSortTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -17,14 +18,14 @@ public void test(int[] inputArray, int[] expectedArray) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {170, 45, 75, 90, 802, 24, 2, 66}, new int[] {2, 24, 45, 66, 75, 90, 170, 802}), Arguments.of(new int[] {3, 3, 3, 3}, new int[] {3, 3, 3, 3}), Arguments.of(new int[] {9, 4, 6, 8, 14, 3}, new int[] {3, 4, 6, 8, 9, 14}), - Arguments.of(new int[] {10, 90, 49, 2, 1, 5, 23}, new int[] {1, 2, 5, 10, 23, 49, 90}), Arguments.of(new int[] {1, 3, 4, 2, 7, 8}, new int[] {1, 2, 3, 4, 7, 8}), Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {1}, new int[] {1}), - Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), Arguments.of(new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), - Arguments.of(new int[] {1000000000, 999999999, 888888888, 777777777}, new int[] {777777777, 888888888, 999999999, 1000000000}), Arguments.of(new int[] {123, 9, 54321, 123456789, 0}, new int[] {0, 9, 123, 54321, 123456789})); + return Stream.of(Arguments.of(new int[]{170, 45, 75, 90, 802, 24, 2, 66}, new int[]{2, 24, 45, 66, 75, 90, 170, 802}), Arguments.of(new int[]{3, 3, 3, 3}, new int[]{3, 3, 3, 3}), Arguments.of(new int[]{9, 4, 6, 8, 14, 3}, new int[]{3, 4, 6, 8, 9, 14}), + Arguments.of(new int[]{10, 90, 49, 2, 1, 5, 23}, new int[]{1, 2, 5, 10, 23, 49, 90}), Arguments.of(new int[]{1, 3, 4, 2, 7, 8}, new int[]{1, 2, 3, 4, 7, 8}), Arguments.of(new int[]{}, new int[]{}), Arguments.of(new int[]{1}, new int[]{1}), + Arguments.of(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}), Arguments.of(new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}), + Arguments.of(new int[]{1000000000, 999999999, 888888888, 777777777}, new int[]{777777777, 888888888, 999999999, 1000000000}), Arguments.of(new int[]{123, 9, 54321, 123456789, 0}, new int[]{0, 9, 123, 54321, 123456789})); } @Test public void testWithNegativeNumbers() { - assertThrows(IllegalArgumentException.class, () -> RadixSort.sort(new int[] {3, 1, 4, 1, 5, -9})); + assertThrows(IllegalArgumentException.class, () -> RadixSort.sort(new int[]{3, 1, 4, 1, 5, -9})); } } diff --git a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java index ac654148c967..8a6502ed52a8 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -88,7 +89,7 @@ public void testSwapFlippedIndices(T[] array, int i, int j, T[] expected) { } private static Stream provideArraysForSwap() { - return Stream.of(Arguments.of(new Integer[] {1, 2, 3, 4}, 1, 2, new Integer[] {1, 3, 2, 4}), Arguments.of(new Integer[] {1, 2, 3, 4}, 0, 3, new Integer[] {4, 2, 3, 1}), Arguments.of(new Integer[] {1, 2, 3, 4}, 2, 2, new Integer[] {1, 2, 3, 4}), - Arguments.of(new String[] {"a", "b", "c", "d"}, 0, 3, new String[] {"d", "b", "c", "a"}), Arguments.of(new String[] {null, "b", "c", null}, 0, 3, new String[] {null, "b", "c", null})); + return Stream.of(Arguments.of(new Integer[]{1, 2, 3, 4}, 1, 2, new Integer[]{1, 3, 2, 4}), Arguments.of(new Integer[]{1, 2, 3, 4}, 0, 3, new Integer[]{4, 2, 3, 1}), Arguments.of(new Integer[]{1, 2, 3, 4}, 2, 2, new Integer[]{1, 2, 3, 4}), + Arguments.of(new String[]{"a", "b", "c", "d"}, 0, 3, new String[]{"d", "b", "c", "a"}), Arguments.of(new String[]{null, "b", "c", null}, 0, 3, new String[]{null, "b", "c", null})); } } diff --git a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java index 43de55018071..a60f2613a998 100644 --- a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java @@ -9,6 +9,7 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; + import org.junit.jupiter.api.Test; public abstract class SortingAlgorithmTest { @@ -20,8 +21,8 @@ protected int getGeneratedArraySize() { @Test void shouldAcceptWhenEmptyArrayIsPassed() { - Integer[] array = new Integer[] {}; - Integer[] expected = new Integer[] {}; + Integer[] array = new Integer[]{}; + Integer[] expected = new Integer[]{}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -40,8 +41,8 @@ void shouldAcceptWhenEmptyListIsPassed() { @Test void shouldAcceptWhenSingleValuedArrayIsPassed() { - Integer[] array = new Integer[] {2}; - Integer[] expected = new Integer[] {2}; + Integer[] array = new Integer[]{2}; + Integer[] expected = new Integer[]{2}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -60,8 +61,8 @@ void shouldAcceptWhenSingleValuedListIsPassed() { @Test void shouldAcceptWhenListWithAllPositiveValuesIsPassed() { - Integer[] array = new Integer[] {60, 7, 55, 9, 999, 3}; - Integer[] expected = new Integer[] {3, 7, 9, 55, 60, 999}; + Integer[] array = new Integer[]{60, 7, 55, 9, 999, 3}; + Integer[] expected = new Integer[]{3, 7, 9, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -80,8 +81,8 @@ void shouldAcceptWhenArrayWithAllPositiveValuesIsPassed() { @Test void shouldAcceptWhenArrayWithAllNegativeValuesIsPassed() { - Integer[] array = new Integer[] {-60, -7, -55, -9, -999, -3}; - Integer[] expected = new Integer[] {-999, -60, -55, -9, -7, -3}; + Integer[] array = new Integer[]{-60, -7, -55, -9, -999, -3}; + Integer[] expected = new Integer[]{-999, -60, -55, -9, -7, -3}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -100,8 +101,8 @@ void shouldAcceptWhenListWithAllNegativeValuesIsPassed() { @Test void shouldAcceptWhenArrayWithRealNumberValuesIsPassed() { - Integer[] array = new Integer[] {60, -7, 55, 9, -999, -3}; - Integer[] expected = new Integer[] {-999, -7, -3, 9, 55, 60}; + Integer[] array = new Integer[]{60, -7, 55, 9, -999, -3}; + Integer[] expected = new Integer[]{-999, -7, -3, 9, 55, 60}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -120,8 +121,8 @@ void shouldAcceptWhenListWithRealNumberValuesIsPassed() { @Test void shouldAcceptWhenArrayWithDuplicateValueIsPassed() { - Integer[] array = new Integer[] {60, 7, 55, 55, 999, 3}; - Integer[] expected = new Integer[] {3, 7, 55, 55, 60, 999}; + Integer[] array = new Integer[]{60, 7, 55, 55, 999, 3}; + Integer[] expected = new Integer[]{3, 7, 55, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -179,7 +180,7 @@ void shouldAcceptWhenRandomListIsPassed() { public void shouldAcceptWhenArrayWithAllIdenticalValuesIsPassed() { Integer[] array = {1, 1, 1, 1}; Integer[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Integer[] {1, 1, 1, 1}, sortedArray); + assertArrayEquals(new Integer[]{1, 1, 1, 1}, sortedArray); } @Test @@ -193,7 +194,7 @@ public void shouldAcceptWhenListWithAllIdenticalValuesIsPassed() { public void shouldAcceptWhenArrayWithMixedPositiveAndNegativeValuesIsPassed() { Integer[] array = {-1, 3, -2, 5, 0}; Integer[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Integer[] {-2, -1, 0, 3, 5}, sortedArray); + assertArrayEquals(new Integer[]{-2, -1, 0, 3, 5}, sortedArray); } @Test @@ -207,7 +208,7 @@ public void shouldAcceptWhenListWithMixedPositiveAndNegativeValuesIsPassed() { public void shouldAcceptWhenArrayWithLargeNumbersIsPassed() { Long[] array = {10000000000L, 9999999999L, 10000000001L}; Long[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Long[] {9999999999L, 10000000000L, 10000000001L}, sortedArray); + assertArrayEquals(new Long[]{9999999999L, 10000000000L, 10000000001L}, sortedArray); } @Test @@ -221,7 +222,7 @@ public void shouldAcceptWhenListWithLargeNumbersIsPassed() { public void shouldAcceptWhenArrayWithMaxIntegerValuesIsPassed() { Integer[] array = {Integer.MAX_VALUE, Integer.MIN_VALUE, 0}; Integer[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Integer[] {Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray); + assertArrayEquals(new Integer[]{Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray); } @Test @@ -235,7 +236,7 @@ public void shouldAcceptWhenListWithMaxIntegerValuesIsPassed() { public void shouldAcceptWhenArrayWithMinIntegerValuesIsPassed() { Integer[] array = {Integer.MIN_VALUE, Integer.MAX_VALUE, 0}; Integer[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Integer[] {Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray); + assertArrayEquals(new Integer[]{Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray); } @Test @@ -249,7 +250,7 @@ public void shouldAcceptWhenListWithMinIntegerValuesIsPassed() { public void shouldAcceptWhenArrayWithSpecialCharactersIsPassed() { String[] array = {"!", "@", "#", "$"}; String[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new String[] {"!", "#", "$", "@"}, sortedArray); + assertArrayEquals(new String[]{"!", "#", "$", "@"}, sortedArray); } @Test @@ -263,7 +264,7 @@ public void shouldAcceptWhenListWithSpecialCharactersIsPassed() { public void shouldAcceptWhenArrayWithMixedCaseStringsIsPassed() { String[] array = {"apple", "Banana", "cherry", "Date"}; String[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new String[] {"Banana", "Date", "apple", "cherry"}, sortedArray); + assertArrayEquals(new String[]{"Banana", "Date", "apple", "cherry"}, sortedArray); } @Test @@ -300,7 +301,7 @@ public int compareTo(CustomObject o) { @Override public String toString() { return "CustomObject{" - + "value=" + value + '}'; + + "value=" + value + '}'; } @Override @@ -325,7 +326,7 @@ public int hashCode() { public void shouldHandleArrayOfCustomObjects() { CustomObject[] array = {new CustomObject(3), new CustomObject(1), new CustomObject(2)}; CustomObject[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new CustomObject[] {new CustomObject(1), new CustomObject(2), new CustomObject(3)}, sortedArray); + assertArrayEquals(new CustomObject[]{new CustomObject(1), new CustomObject(2), new CustomObject(3)}, sortedArray); } @Test @@ -339,7 +340,7 @@ public void shouldHandleListOfCustomObjects() { public void shouldHandleArrayOfFloatingPointNumbers() { Double[] array = {3.3, 2.2, 1.1, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; Double[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new Double[] {Double.NEGATIVE_INFINITY, 1.1, 2.2, 3.3, Double.POSITIVE_INFINITY, Double.NaN}, sortedArray); + assertArrayEquals(new Double[]{Double.NEGATIVE_INFINITY, 1.1, 2.2, 3.3, Double.POSITIVE_INFINITY, Double.NaN}, sortedArray); } @Test @@ -353,7 +354,7 @@ public void shouldHandleListOfFloatingPointNumbers() { public void shouldHandleArrayWithEmptyStrings() { String[] array = {"apple", "", "banana", ""}; String[] sortedArray = getSortAlgorithm().sort(array); - assertArrayEquals(new String[] {"", "", "apple", "banana"}, sortedArray); + assertArrayEquals(new String[]{"", "", "apple", "banana"}, sortedArray); } @Test diff --git a/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java b/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java index a4992a02abfa..b5b0eb51dcf5 100644 --- a/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -24,7 +25,7 @@ static class ConstructorArgumentsProvider implements ArgumentsProvider { @Override public Stream provideArguments(org.junit.jupiter.api.extension.ExtensionContext context) { return Stream.of(Arguments.of(0, 16, 2, IllegalArgumentException.class), Arguments.of(16, 0, 2, IllegalArgumentException.class), Arguments.of(16, 16, 0, IllegalArgumentException.class), Arguments.of(1001, 16, 2, IllegalArgumentException.class), - Arguments.of(16, 1001, 2, IllegalArgumentException.class), Arguments.of(16, 16, 101, IllegalArgumentException.class)); + Arguments.of(16, 1001, 2, IllegalArgumentException.class), Arguments.of(16, 16, 101, IllegalArgumentException.class)); } } diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java index de115b458fe7..7b33438cbc70 100644 --- a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java @@ -5,7 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.thealgorithms.sorts.TopologicalSort.Graph; + import java.util.LinkedList; + import org.junit.jupiter.api.Test; class TopologicalSortTest { @@ -56,7 +58,7 @@ public void failureTest() { graph.addEdge("8", ""); Exception exception = assertThrows(RuntimeException.class, () -> TopologicalSort.sort(graph)); String expected = "This graph contains a cycle. No linear ordering is possible. " - + "Back edge: 6 -> 2"; + + "Back edge: 6 -> 2"; assertEquals(exception.getMessage(), expected); } } diff --git a/src/test/java/com/thealgorithms/sorts/WaveSortTest.java b/src/test/java/com/thealgorithms/sorts/WaveSortTest.java index 3bc6fa63c01d..56a1229243b8 100644 --- a/src/test/java/com/thealgorithms/sorts/WaveSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/WaveSortTest.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -30,8 +31,8 @@ private Map getHistogram(Integer[] array) { } private static Stream arraysToWaveSort() { - return Stream.of(new Object[] {new Integer[] {7, 7, 11, 3, 4, 5, 15}}, new Object[] {new Integer[] {1, 2, 3, 4, 5, 6, 7, 8}}, new Object[] {new Integer[] {8, 7, 6, 5, 4, 3, 2, 1}}, new Object[] {new Integer[] {3, 3, 3, 3}}, new Object[] {new Integer[] {-1, -3, -2, -4, -6, -5}}, - new Object[] {new Integer[] {5, 3, 1, 2, 9, 7, 6, 8, 4, 0}}, new Object[] {new Integer[] {1}}, new Object[] {new Integer[] {2, 1}}, new Object[] {new Integer[] {1, 2}}, new Object[] {new Integer[] {}}, new Object[] {new Integer[] {0, 5, -3, 2, -1, 4, -2, 1, 3}}); + return Stream.of(new Object[]{new Integer[]{7, 7, 11, 3, 4, 5, 15}}, new Object[]{new Integer[]{1, 2, 3, 4, 5, 6, 7, 8}}, new Object[]{new Integer[]{8, 7, 6, 5, 4, 3, 2, 1}}, new Object[]{new Integer[]{3, 3, 3, 3}}, new Object[]{new Integer[]{-1, -3, -2, -4, -6, -5}}, + new Object[]{new Integer[]{5, 3, 1, 2, 9, 7, 6, 8, 4, 0}}, new Object[]{new Integer[]{1}}, new Object[]{new Integer[]{2, 1}}, new Object[]{new Integer[]{1, 2}}, new Object[]{new Integer[]{}}, new Object[]{new Integer[]{0, 5, -3, 2, -1, 4, -2, 1, 3}}); } @ParameterizedTest @@ -40,9 +41,10 @@ public > void testIsWaveSorted(T[] array, boolean expect final WaveSort waveSort = new WaveSort(); assertEquals(expected, waveSort.isWaveSorted(array)); } + public static Stream waveSortedArrays() { - return Stream.of(new Object[] {new Integer[] {3, 1, 4, 2, 5}, Boolean.TRUE}, new Object[] {new Integer[] {3, 1, 4, 2}, Boolean.TRUE}, new Object[] {new Integer[] {1, 3, 2, 4, 5}, Boolean.FALSE}, new Object[] {new Integer[] {4, 3, 5, 2, 3, 1, 2}, Boolean.TRUE}, - new Object[] {new Integer[] {10, 90, 49, 2, 1, 5, 23}, Boolean.FALSE}, new Object[] {new Integer[] {}, Boolean.TRUE}, new Object[] {new Integer[] {1}, Boolean.TRUE}, new Object[] {new Integer[] {2, 1}, Boolean.TRUE}, new Object[] {new Integer[] {4, 3, 2, 5}, Boolean.FALSE}, - new Object[] {new Double[] {4.0, 3.0, 5.1, 2.1, 3.3, 1.1, 2.2}, Boolean.TRUE}, new Object[] {new Double[] {10.1, 2.0, 2.0}, Boolean.TRUE}, new Object[] {new String[] {"a", "b", "c", "d"}, Boolean.FALSE}, new Object[] {new String[] {"b", "a", "b", "a", "b"}, Boolean.TRUE}); + return Stream.of(new Object[]{new Integer[]{3, 1, 4, 2, 5}, Boolean.TRUE}, new Object[]{new Integer[]{3, 1, 4, 2}, Boolean.TRUE}, new Object[]{new Integer[]{1, 3, 2, 4, 5}, Boolean.FALSE}, new Object[]{new Integer[]{4, 3, 5, 2, 3, 1, 2}, Boolean.TRUE}, + new Object[]{new Integer[]{10, 90, 49, 2, 1, 5, 23}, Boolean.FALSE}, new Object[]{new Integer[]{}, Boolean.TRUE}, new Object[]{new Integer[]{1}, Boolean.TRUE}, new Object[]{new Integer[]{2, 1}, Boolean.TRUE}, new Object[]{new Integer[]{4, 3, 2, 5}, Boolean.FALSE}, + new Object[]{new Double[]{4.0, 3.0, 5.1, 2.1, 3.3, 1.1, 2.2}, Boolean.TRUE}, new Object[]{new Double[]{10.1, 2.0, 2.0}, Boolean.TRUE}, new Object[]{new String[]{"a", "b", "c", "d"}, Boolean.FALSE}, new Object[]{new String[]{"b", "a", "b", "a", "b"}, Boolean.TRUE}); } } diff --git a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java index c5d57d63cf38..51027686f50f 100644 --- a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.Arrays; + import org.junit.jupiter.api.Test; public class WiggleSortTest { diff --git a/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java b/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java index da0217940c2c..6f96a91274da 100644 --- a/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java +++ b/src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,25 +18,25 @@ public void testCelebrityFinder(int[][] party, int expected) { private static Stream providePartyMatrices() { return Stream.of( - // Test case 1: Celebrity exists - Arguments.of(new int[][] {{0, 1, 1}, {0, 0, 1}, {0, 0, 0}}, 2), + // Test case 1: Celebrity exists + Arguments.of(new int[][]{{0, 1, 1}, {0, 0, 1}, {0, 0, 0}}, 2), - // Test case 2: No celebrity - Arguments.of(new int[][] {{0, 1, 0}, {1, 0, 1}, {1, 1, 0}}, -1), + // Test case 2: No celebrity + Arguments.of(new int[][]{{0, 1, 0}, {1, 0, 1}, {1, 1, 0}}, -1), - // Test case 3: Everyone knows each other, no celebrity - Arguments.of(new int[][] {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}, -1), + // Test case 3: Everyone knows each other, no celebrity + Arguments.of(new int[][]{{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}, -1), - // Test case 4: Single person, they are trivially a celebrity - Arguments.of(new int[][] {{0}}, 0), + // Test case 4: Single person, they are trivially a celebrity + Arguments.of(new int[][]{{0}}, 0), - // Test case 5: All know the last person, and they know no one - Arguments.of(new int[][] {{0, 1, 1, 1}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}}, 3), + // Test case 5: All know the last person, and they know no one + Arguments.of(new int[][]{{0, 1, 1, 1}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}}, 3), - // Test case 6: Larger party with no celebrity - Arguments.of(new int[][] {{0, 1, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 1, 0}}, -1), + // Test case 6: Larger party with no celebrity + Arguments.of(new int[][]{{0, 1, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 1, 0}}, -1), - // Test case 7: Celebrity at the start of the matrix - Arguments.of(new int[][] {{0, 0, 0}, {1, 0, 1}, {1, 1, 0}}, 0)); + // Test case 7: Celebrity at the start of the matrix + Arguments.of(new int[][]{{0, 0, 0}, {1, 0, 1}, {1, 1, 0}}, 0)); } } diff --git a/src/test/java/com/thealgorithms/stacks/GreatestElementConstantTimeTest.java b/src/test/java/com/thealgorithms/stacks/GreatestElementConstantTimeTest.java index 080592dc68e8..5a57b940a127 100644 --- a/src/test/java/com/thealgorithms/stacks/GreatestElementConstantTimeTest.java +++ b/src/test/java/com/thealgorithms/stacks/GreatestElementConstantTimeTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.NoSuchElementException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java b/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java index 02a08e393a00..c12ccf414aa3 100644 --- a/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java +++ b/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java b/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java index 91be8a63da62..54a035e2aed9 100644 --- a/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java +++ b/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -31,14 +32,14 @@ void testNullValue() { private static Stream provideValidExpressions() { return Stream.of(Arguments.of("3+2", "+32"), // Simple addition - Arguments.of("1+(2+3)", "+1+23"), // Parentheses - Arguments.of("(3+4)*5-6", "-*+3456"), // Nested operations - Arguments.of("a+b*c", "+a*bc"), // Multiplication precedence - Arguments.of("a+b*c/d", "+a/*bcd"), // Division precedence - Arguments.of("a+b*c-d", "-+a*bcd"), // Subtraction precedence - Arguments.of("a+b*c/d-e", "-+a/*bcde"), // Mixed precedence - Arguments.of("a+b*(c-d)", "+a*b-cd"), // Parentheses precedence - Arguments.of("a+b*(c-d)/e", "+a/*b-cde") // Mixed precedence with parentheses + Arguments.of("1+(2+3)", "+1+23"), // Parentheses + Arguments.of("(3+4)*5-6", "-*+3456"), // Nested operations + Arguments.of("a+b*c", "+a*bc"), // Multiplication precedence + Arguments.of("a+b*c/d", "+a/*bcd"), // Division precedence + Arguments.of("a+b*c-d", "-+a*bcd"), // Subtraction precedence + Arguments.of("a+b*c/d-e", "-+a/*bcde"), // Mixed precedence + Arguments.of("a+b*(c-d)", "+a*b-cd"), // Parentheses precedence + Arguments.of("a+b*(c-d)/e", "+a/*b-cde") // Mixed precedence with parentheses ); } } diff --git a/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java b/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java index a54372adda0e..33bff06d236f 100644 --- a/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java +++ b/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java @@ -15,13 +15,13 @@ void testLargestRectangleHistogramWithTypicalCases() { assertEquals(expected, result); // Another typical case with increasing heights - heights = new int[] {2, 4}; + heights = new int[]{2, 4}; expected = "4"; result = LargestRectangle.largestRectangleHistogram(heights); assertEquals(expected, result); // Case with multiple bars of the same height - heights = new int[] {4, 4, 4, 4}; + heights = new int[]{4, 4, 4, 4}; expected = "16"; result = LargestRectangle.largestRectangleHistogram(heights); assertEquals(expected, result); @@ -36,13 +36,13 @@ void testLargestRectangleHistogramWithEdgeCases() { assertEquals(expected, result); // Edge case with a single bar - heights = new int[] {5}; + heights = new int[]{5}; expected = "5"; result = LargestRectangle.largestRectangleHistogram(heights); assertEquals(expected, result); // Edge case with all bars of height 0 - heights = new int[] {0, 0, 0}; + heights = new int[]{0, 0, 0}; expected = "0"; result = LargestRectangle.largestRectangleHistogram(heights); assertEquals(expected, result); @@ -69,7 +69,7 @@ void testLargestRectangleHistogramWithComplexCases() { assertEquals(expected, result); // Case with a peak in the middle - heights = new int[] {2, 1, 5, 6, 2, 3, 1}; + heights = new int[]{2, 1, 5, 6, 2, 3, 1}; expected = "10"; result = LargestRectangle.largestRectangleHistogram(heights); assertEquals(expected, result); diff --git a/src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java b/src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java index 90887294638f..859d65b872c9 100644 --- a/src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java +++ b/src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; + import org.junit.jupiter.api.Test; public class MinStackUsingSingleStackTest { diff --git a/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java b/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java index bf015ddc9996..47076c9f41c1 100644 --- a/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java +++ b/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -18,8 +19,8 @@ void testFindNextGreaterElements(int[] input, int[] expected) { } static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {2, 7, 3, 5, 4, 6, 8}, new int[] {7, 8, 5, 6, 6, 8, 0}), Arguments.of(new int[] {5}, new int[] {0}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {2, 3, 4, 5, 0}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {0, 0, 0, 0, 0}), - Arguments.of(new int[] {4, 5, 2, 25}, new int[] {5, 25, 25, 0}), Arguments.of(new int[] {}, new int[] {})); + return Stream.of(Arguments.of(new int[]{2, 7, 3, 5, 4, 6, 8}, new int[]{7, 8, 5, 6, 6, 8, 0}), Arguments.of(new int[]{5}, new int[]{0}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{2, 3, 4, 5, 0}), Arguments.of(new int[]{5, 4, 3, 2, 1}, new int[]{0, 0, 0, 0, 0}), + Arguments.of(new int[]{4, 5, 2, 25}, new int[]{5, 25, 25, 0}), Arguments.of(new int[]{}, new int[]{})); } @Test diff --git a/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java b/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java index 62578baa6632..3bf6dc4021c8 100644 --- a/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java +++ b/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -18,8 +19,8 @@ void testFindNextSmallerElements(int[] input, int[] expected) { } static Stream provideTestCases() { - return Stream.of(Arguments.of(new int[] {2, 7, 3, 5, 4, 6, 8}, new int[] {-1, 2, 2, 3, 3, 4, 6}), Arguments.of(new int[] {5}, new int[] {-1}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {-1, 1, 2, 3, 4}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {-1, -1, -1, -1, -1}), - Arguments.of(new int[] {4, 5, 2, 25}, new int[] {-1, 4, -1, 2}), Arguments.of(new int[] {}, new int[] {})); + return Stream.of(Arguments.of(new int[]{2, 7, 3, 5, 4, 6, 8}, new int[]{-1, 2, 2, 3, 3, 4, 6}), Arguments.of(new int[]{5}, new int[]{-1}), Arguments.of(new int[]{1, 2, 3, 4, 5}, new int[]{-1, 1, 2, 3, 4}), Arguments.of(new int[]{5, 4, 3, 2, 1}, new int[]{-1, -1, -1, -1, -1}), + Arguments.of(new int[]{4, 5, 2, 25}, new int[]{-1, 4, -1, 2}), Arguments.of(new int[]{}, new int[]{})); } @Test diff --git a/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java b/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java index 882fe644ccd5..5efd358b3618 100644 --- a/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java +++ b/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; + import org.junit.jupiter.api.Test; public class PostfixEvaluatorTest { diff --git a/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java b/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java index a018865e69ec..51cb727cc9f5 100644 --- a/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java +++ b/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java b/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java index e2faa61955b3..16a69a408427 100644 --- a/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java +++ b/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; + import org.junit.jupiter.api.Test; public class PrefixEvaluatorTest { diff --git a/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java b/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java index 83fd09e1bbf6..a7cb93106de4 100644 --- a/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java +++ b/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -19,11 +20,11 @@ void testValidPrefixToInfixConversion(String prefix, String expectedInfix) { static Stream provideValidPrefixToInfixTestCases() { return Stream.of(Arguments.of("A", "A"), // Single operand - Arguments.of("+AB", "(A+B)"), // Addition - Arguments.of("*+ABC", "((A+B)*C)"), // Addition and multiplication - Arguments.of("-+A*BCD", "((A+(B*C))-D)"), // Mixed operators - Arguments.of("/-A*BC+DE", "((A-(B*C))/(D+E))"), // Mixed operators - Arguments.of("^+AB*CD", "((A+B)^(C*D))") // Mixed operators + Arguments.of("+AB", "(A+B)"), // Addition + Arguments.of("*+ABC", "((A+B)*C)"), // Addition and multiplication + Arguments.of("-+A*BCD", "((A+(B*C))-D)"), // Mixed operators + Arguments.of("/-A*BC+DE", "((A-(B*C))/(D+E))"), // Mixed operators + Arguments.of("^+AB*CD", "((A+B)^(C*D))") // Mixed operators ); } diff --git a/src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java b/src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java index b5eda9e8cb46..c82280fa6e32 100644 --- a/src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java +++ b/src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.NoSuchElementException; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/stacks/SortStackTest.java b/src/test/java/com/thealgorithms/stacks/SortStackTest.java index b9f2f1b6f106..57a86e5d07e0 100644 --- a/src/test/java/com/thealgorithms/stacks/SortStackTest.java +++ b/src/test/java/com/thealgorithms/stacks/SortStackTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Stack; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java b/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java index 97424a8f291d..3f3b3cd69a84 100644 --- a/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java +++ b/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java b/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java index 43137b358cf9..d1e782752c26 100644 --- a/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java +++ b/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java @@ -14,6 +14,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ class AhoCorasickTest { */ @BeforeEach void setUp() { - patterns = new String[] {"ACC", "ATC", "CAT", "GCG", "C", "T"}; + patterns = new String[]{"ACC", "ATC", "CAT", "GCG", "C", "T"}; text = "GCATCG"; } @@ -54,7 +55,7 @@ void testSearch() { @Test void testEmptyPatterns() { // Define an empty pattern array - final var emptyPatterns = new String[] {}; + final var emptyPatterns = new String[]{}; assertTrue(AhoCorasick.search(text, emptyPatterns).isEmpty()); } @@ -65,7 +66,7 @@ void testEmptyPatterns() { @Test void testPatternNotFound() { // Define patterns that are not present in the text - final var searchPatterns = new String[] {"XYZ", "123"}; + final var searchPatterns = new String[]{"XYZ", "123"}; final var expected = Map.of("XYZ", new ArrayList(), "123", new ArrayList()); assertEquals(expected, AhoCorasick.search(text, searchPatterns)); } @@ -77,7 +78,7 @@ void testPatternNotFound() { @Test void testPatternAtBeginning() { // Define patterns that start at the beginning of the text - final var searchPatterns = new String[] {"GC", "GCA", "GCAT"}; + final var searchPatterns = new String[]{"GC", "GCA", "GCAT"}; final var expected = Map.of("GC", new ArrayList<>(List.of(0)), "GCA", new ArrayList<>(List.of(0)), "GCAT", new ArrayList<>(List.of(0))); assertEquals(expected, AhoCorasick.search(text, searchPatterns)); } @@ -89,7 +90,7 @@ void testPatternAtBeginning() { @Test void testPatternAtEnd() { // Define patterns that end at the end of the text - final var searchPatterns = new String[] {"CG", "TCG", "ATCG"}; + final var searchPatterns = new String[]{"CG", "TCG", "ATCG"}; final var expected = Map.of("CG", new ArrayList<>(List.of(4)), "TCG", new ArrayList<>(List.of(3)), "ATCG", new ArrayList<>(List.of(2))); assertEquals(expected, AhoCorasick.search(text, searchPatterns)); } @@ -102,7 +103,7 @@ void testPatternAtEnd() { @Test void testMultipleOccurrencesOfPattern() { // Define patterns with multiple occurrences in the text - final var searchPatterns = new String[] {"AT", "T"}; + final var searchPatterns = new String[]{"AT", "T"}; final var expected = Map.of("AT", new ArrayList<>(List.of(2)), "T", new ArrayList<>(List.of(3))); assertEquals(expected, AhoCorasick.search(text, searchPatterns)); } @@ -114,7 +115,7 @@ void testMultipleOccurrencesOfPattern() { @Test void testCaseInsensitiveSearch() { // Define patterns with different cases - final var searchPatterns = new String[] {"gca", "aTc", "C"}; + final var searchPatterns = new String[]{"gca", "aTc", "C"}; final var expected = Map.of("gca", new ArrayList(), "aTc", new ArrayList(), "C", new ArrayList<>(Arrays.asList(1, 4))); assertEquals(expected, AhoCorasick.search(text, searchPatterns)); } diff --git a/src/test/java/com/thealgorithms/strings/AnagramsTest.java b/src/test/java/com/thealgorithms/strings/AnagramsTest.java index 88f6e0bb72ec..89a6831441ce 100644 --- a/src/test/java/com/thealgorithms/strings/AnagramsTest.java +++ b/src/test/java/com/thealgorithms/strings/AnagramsTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -13,7 +14,7 @@ record AnagramTestCase(String input1, String input2, boolean expected) { private static Stream anagramTestData() { return Stream.of(new AnagramTestCase("late", "tale", true), new AnagramTestCase("late", "teal", true), new AnagramTestCase("listen", "silent", true), new AnagramTestCase("hello", "olelh", true), new AnagramTestCase("hello", "world", false), new AnagramTestCase("deal", "lead", true), - new AnagramTestCase("binary", "brainy", true), new AnagramTestCase("adobe", "abode", true), new AnagramTestCase("cat", "act", true), new AnagramTestCase("cat", "cut", false)); + new AnagramTestCase("binary", "brainy", true), new AnagramTestCase("adobe", "abode", true), new AnagramTestCase("cat", "act", true), new AnagramTestCase("cat", "cut", false)); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/strings/CountWordsTest.java b/src/test/java/com/thealgorithms/strings/CountWordsTest.java index a8aca1ae6092..e493aacdb863 100644 --- a/src/test/java/com/thealgorithms/strings/CountWordsTest.java +++ b/src/test/java/com/thealgorithms/strings/CountWordsTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java index 5c0640348404..7e1d1fb8519f 100644 --- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java index dcdb7d5b3392..f2298c6ee0c6 100644 --- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java +++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -24,14 +25,14 @@ void throwsForWrongInput(int[] numbers) { } private static Stream provideTestCases() { - return Stream.of(Arguments.of(null, List.of("")), Arguments.of(new int[] {}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")), Arguments.of(new int[] {2, 3}, List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")), - Arguments.of(new int[] {2, 3, 4}, List.of("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi")), - Arguments.of(new int[] {3, 3}, List.of("dd", "de", "df", "ed", "ee", "ef", "fd", "fe", "ff")), Arguments.of(new int[] {8, 4}, List.of("tg", "th", "ti", "ug", "uh", "ui", "vg", "vh", "vi")), Arguments.of(new int[] {2, 0}, List.of("a ", "b ", "c ")), - Arguments.of(new int[] {9, 2}, List.of("wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc")), Arguments.of(new int[] {0}, List.of(" ")), Arguments.of(new int[] {1}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")), - Arguments.of(new int[] {1, 2, 0, 4}, List.of("a g", "a h", "a i", "b g", "b h", "b i", "c g", "c h", "c i"))); + return Stream.of(Arguments.of(null, List.of("")), Arguments.of(new int[]{}, List.of("")), Arguments.of(new int[]{2}, List.of("a", "b", "c")), Arguments.of(new int[]{2, 3}, List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")), + Arguments.of(new int[]{2, 3, 4}, List.of("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi")), + Arguments.of(new int[]{3, 3}, List.of("dd", "de", "df", "ed", "ee", "ef", "fd", "fe", "ff")), Arguments.of(new int[]{8, 4}, List.of("tg", "th", "ti", "ug", "uh", "ui", "vg", "vh", "vi")), Arguments.of(new int[]{2, 0}, List.of("a ", "b ", "c ")), + Arguments.of(new int[]{9, 2}, List.of("wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc")), Arguments.of(new int[]{0}, List.of(" ")), Arguments.of(new int[]{1}, List.of("")), Arguments.of(new int[]{2}, List.of("a", "b", "c")), + Arguments.of(new int[]{1, 2, 0, 4}, List.of("a g", "a h", "a i", "b g", "b h", "b i", "c g", "c h", "c i"))); } private static Stream wrongInputs() { - return Stream.of(Arguments.of(new int[] {-1}), Arguments.of(new int[] {10}), Arguments.of(new int[] {2, 2, -1, 0}), Arguments.of(new int[] {0, 0, 0, 10})); + return Stream.of(Arguments.of(new int[]{-1}), Arguments.of(new int[]{10}), Arguments.of(new int[]{2, 2, -1, 0}), Arguments.of(new int[]{0, 0, 0, 10})); } } diff --git a/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java b/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java index 791c4ba3ae32..f64bf45d03fb 100644 --- a/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java +++ b/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -11,7 +12,7 @@ public class LongestNonRepetitiveSubstringTest { private static Stream provideTestCases() { return Stream.of(Arguments.of("", 0), Arguments.of("a", 1), Arguments.of("abcde", 5), Arguments.of("aaaaa", 1), Arguments.of("abca", 3), Arguments.of("abcdeabc", 5), Arguments.of("a1b2c3", 6), Arguments.of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 62), - Arguments.of("aabb", 2), Arguments.of("abcdefghijabc", 10)); + Arguments.of("aabb", 2), Arguments.of("abcdefghijabc", 10)); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java b/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java index aa13c0f4a474..980c299477ba 100644 --- a/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java +++ b/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/strings/ManacherTest.java b/src/test/java/com/thealgorithms/strings/ManacherTest.java index dc74df31b866..8d25f9a269e0 100644 --- a/src/test/java/com/thealgorithms/strings/ManacherTest.java +++ b/src/test/java/com/thealgorithms/strings/ManacherTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,7 +18,7 @@ public void testLongestPalindrome(String input, String expected) { private static Stream provideTestCasesForLongestPalindrome() { return Stream.of(Arguments.of("abracadabraabcdefggfedcbaabracadabra", "aabcdefggfedcbaa"), Arguments.of("somelongtextwithracecarmiddletext", "racecar"), Arguments.of("bananananananana", "ananananananana"), Arguments.of("qwertydefgfedzxcvbnm", "defgfed"), - Arguments.of("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba")); + Arguments.of("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba")); } @ParameterizedTest @@ -38,7 +39,7 @@ public void testComplexCases(String input, String expected) { private static Stream provideTestCasesForComplexCases() { return Stream.of(Arguments.of("abcdefghijklmnopqrstuvwxyzttattarrattatabcdefghijklmnopqrstuvwxyz", "tattarrattat"), Arguments.of("aaaaabaaaaacbaaaaa", "aaaaabaaaaa"), Arguments.of("sometextrandomabcdefgabcdefghhgfedcbahijklmnopqrstuvwxyz", "abcdefghhgfedcba"), - Arguments.of("therewasasignthatsaidmadaminedenimadamitwasthereallalong", "madaminedenimadam")); + Arguments.of("therewasasignthatsaidmadaminedenimadamitwasthereallalong", "madaminedenimadam")); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java index 8d2354910e2a..74bc2555fc30 100644 --- a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java +++ b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java @@ -10,7 +10,7 @@ public class MyAtoiTest { @ParameterizedTest @CsvSource({"'42', 42", "' -42', -42", "'4193 with words', 4193", "'words and 987', 0", "'-91283472332', -2147483648", "'21474836460', 2147483647", "' +123', 123", "'', 0", "' ', 0", "'-2147483648', -2147483648", "'+2147483647', 2147483647", "' -0012a42', -12", - "'9223372036854775808', 2147483647", "'-9223372036854775809', -2147483648", "'3.14159', 3", "' -0012', -12", "' 0000000000012345678', 12345678", "' -0000000000012345678', -12345678", "' +0000000000012345678', 12345678", "'0', 0", "'+0', 0", "'-0', 0"}) + "'9223372036854775808', 2147483647", "'-9223372036854775809', -2147483648", "'3.14159', 3", "' -0012', -12", "' 0000000000012345678', 12345678", "' -0000000000012345678', -12345678", "' +0000000000012345678', 12345678", "'0', 0", "'+0', 0", "'-0', 0"}) void testMyAtoi(String input, int expected) { assertEquals(expected, MyAtoi.myAtoi(input)); diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java index d839e381c6dd..14a7bca44c4a 100644 --- a/src/test/java/com/thealgorithms/strings/PalindromeTest.java +++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.strings; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/com/thealgorithms/strings/PermuteStringTest.java b/src/test/java/com/thealgorithms/strings/PermuteStringTest.java index c726874f4cec..87b2488d826c 100644 --- a/src/test/java/com/thealgorithms/strings/PermuteStringTest.java +++ b/src/test/java/com/thealgorithms/strings/PermuteStringTest.java @@ -4,6 +4,7 @@ import java.util.Set; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -11,10 +12,10 @@ public class PermuteStringTest { private static Stream provideTestCases() { return Stream.of(new TestData("ABC", Set.of("ABC", "ACB", "BAC", "BCA", "CAB", "CBA")), new TestData("AB", Set.of("AB", "BA")), new TestData("A", Set.of("A")), new TestData("AA", Set.of("AA")), new TestData("123", Set.of("123", "132", "213", "231", "312", "321")), - new TestData("aA", Set.of("aA", "Aa")), new TestData("AaB", Set.of("AaB", "ABa", "aAB", "aBA", "BAa", "BaA")), new TestData("!@", Set.of("!@", "@!")), new TestData("!a@", Set.of("!a@", "!@a", "a!@", "a@!", "@!a", "@a!")), - new TestData("ABCD", Set.of("ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA")), - new TestData("A B", Set.of("A B", "AB ", " AB", " BA", "BA ", "B A")), - new TestData("abcd", Set.of("abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"))); + new TestData("aA", Set.of("aA", "Aa")), new TestData("AaB", Set.of("AaB", "ABa", "aAB", "aBA", "BAa", "BaA")), new TestData("!@", Set.of("!@", "@!")), new TestData("!a@", Set.of("!a@", "!@a", "a!@", "a@!", "@!a", "@a!")), + new TestData("ABCD", Set.of("ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA")), + new TestData("A B", Set.of("A B", "AB ", " AB", " BA", "BA ", "B A")), + new TestData("abcd", Set.of("abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"))); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java b/src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java index d4e1248d05ad..4c757cfdc39e 100644 --- a/src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java +++ b/src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -17,7 +18,7 @@ void testSubsequences(String input, String[] expected) { } static Stream provideTestCases() { - return Stream.of(Arguments.of("", new String[] {""}), Arguments.of("a", new String[] {"", "a"}), Arguments.of("ab", new String[] {"", "b", "a", "ab"}), Arguments.of("abc", new String[] {"", "c", "b", "bc", "a", "ac", "ab", "abc"}), - Arguments.of("aab", new String[] {"", "b", "a", "ab", "a", "ab", "aa", "aab"})); + return Stream.of(Arguments.of("", new String[]{""}), Arguments.of("a", new String[]{"", "a"}), Arguments.of("ab", new String[]{"", "b", "a", "ab"}), Arguments.of("abc", new String[]{"", "c", "b", "bc", "a", "ac", "ab", "abc"}), + Arguments.of("aab", new String[]{"", "b", "a", "ab", "a", "ab", "aa", "aab"})); } } diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java index 19daa61f48ca..eca34041f52c 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java @@ -8,7 +8,7 @@ public class ReverseStringRecursiveTest { @ParameterizedTest @CsvSource({"'Hello World', 'dlroW olleH'", "'helloworld', 'dlrowolleh'", "'123456789', '987654321'", "'', ''", "'A', 'A'", "'!123 ABC xyz!', '!zyx CBA 321!'", "'Abc 123 Xyz', 'zyX 321 cbA'", "'12.34,56;78:90', '09:87;65,43.21'", "'abcdEFGHiJKL', 'LKJiHGFEdcba'", - "'MixOf123AndText!', '!txeTdnA321fOxiM'"}) + "'MixOf123AndText!', '!txeTdnA321fOxiM'"}) public void testReverseString(String input, String expectedOutput) { assertEquals(expectedOutput, ReverseStringRecursive.reverse(input)); diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java index 501f702976ec..f884e371c6c3 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -11,7 +12,7 @@ public class ReverseStringTest { private static Stream testCases() { return Stream.of(Arguments.of("Hello World", "dlroW olleH"), Arguments.of("helloworld", "dlrowolleh"), Arguments.of("123456789", "987654321"), Arguments.of("", ""), Arguments.of("A", "A"), Arguments.of("ab", "ba"), - Arguments.of(" leading and trailing spaces ", " secaps gniliart dna gnidael "), Arguments.of("!@#$%^&*()", ")(*&^%$#@!"), Arguments.of("MixOf123AndText!", "!txeTdnA321fOxiM")); + Arguments.of(" leading and trailing spaces ", " secaps gniliart dna gnidael "), Arguments.of("!@#$%^&*()", ")(*&^%$#@!"), Arguments.of("MixOf123AndText!", "!txeTdnA321fOxiM")); } @ParameterizedTest diff --git a/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java b/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java index 7cab6aa7c698..614633e4579f 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.strings; import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java b/src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java index be460c7c4d91..8069ca899812 100644 --- a/src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java +++ b/src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java @@ -4,6 +4,7 @@ import java.util.Set; import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -18,6 +19,6 @@ void searchPattern(String text, String pattern, Set expectedOutput) { private static Stream provideTestCases() { return Stream.of(Arguments.of("abcbcabc", "abc", Set.of(0, 5)), Arguments.of("", "abc", Set.of()), Arguments.of("", "", Set.of()), Arguments.of("a", "b", Set.of()), Arguments.of("a", "a", Set.of(0)), Arguments.of("abcdabcabcabcd", "abcd", Set.of(0, 10)), Arguments.of("abc", "bcd", Set.of()), - Arguments.of("abcdefg", "xyz", Set.of()), Arguments.of("abcde", "", Set.of(1, 2, 3, 4, 5)), Arguments.of("abcabcabc", "abc", Set.of(0, 3, 6)), Arguments.of("abcabcabc", "abcabcabc", Set.of(0)), Arguments.of("aaabbbaaa", "aaa", Set.of(0, 6)), Arguments.of("abcdefg", "efg", Set.of(4))); + Arguments.of("abcdefg", "xyz", Set.of()), Arguments.of("abcde", "", Set.of(1, 2, 3, 4, 5)), Arguments.of("abcabcabc", "abc", Set.of(0, 3, 6)), Arguments.of("abcabcabc", "abcabcabc", Set.of(0)), Arguments.of("aaabbbaaa", "aaa", Set.of(0, 6)), Arguments.of("abcdefg", "efg", Set.of(4))); } } diff --git a/src/test/java/com/thealgorithms/strings/WordLadderTest.java b/src/test/java/com/thealgorithms/strings/WordLadderTest.java index 0854ad2b0c1f..0fdf92bbebf8 100644 --- a/src/test/java/com/thealgorithms/strings/WordLadderTest.java +++ b/src/test/java/com/thealgorithms/strings/WordLadderTest.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.List; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource;

    Operations