diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index fbc095909541..e10559ae8a65 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 */ diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java index 269880b8ddae..3471983f9c81 100644 --- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java +++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java @@ -41,7 +41,7 @@ public class AllPathsFromSourceToTarget { private final int v; // To store the paths from source to destination - static List> nm = new ArrayList<>(); + static final List> nm = new ArrayList<>(); // adjacency list private ArrayList[] adjList; diff --git a/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java index 6bfb026c7de9..a08e864601a2 100644 --- a/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java +++ b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java @@ -14,7 +14,7 @@ * {' ', ' ', ' '} * } * words = List.of("cat", "dog") - * + *

* Output: * { * {'c', 'a', 't'}, diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java index 2c2da659f3aa..d2402151c45e 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. diff --git a/src/main/java/com/thealgorithms/backtracking/MColoring.java b/src/main/java/com/thealgorithms/backtracking/MColoring.java index d0188dfd13aa..647ab4807302 100644 --- a/src/main/java/com/thealgorithms/backtracking/MColoring.java +++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java @@ -10,11 +10,11 @@ * Node class represents a graph node. Each node is associated with a color * (initially 1) and contains a set of edges representing its adjacent nodes. * - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class Node { int color = 1; // Initial color for each node - Set edges = new HashSet(); // Set of edges representing adjacent nodes + final Set edges = new HashSet(); // Set of edges representing adjacent nodes } /** @@ -60,7 +60,7 @@ static boolean isColoringPossible(ArrayList nodes, int n, int m) { q.add(sv); // Perform BFS to process all nodes and their adjacent nodes - while (q.size() != 0) { + while (!q.isEmpty()) { int top = q.peek(); // Get the current node from the queue q.remove(); 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 404f677738a0..9b80256b3a45 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -10,21 +10,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 diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java index b34ba660ebd7..67dd000636ee 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. */ diff --git a/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java b/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java index 4804e247ab03..9f282b76d33d 100644 --- a/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java +++ b/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java @@ -6,11 +6,11 @@ /** * Generates all UNIQUE permutations of a string, even when duplicate characters exist. - * + *

* Example: * Input: "AAB" * Output: ["AAB", "ABA", "BAA"] - * + *

* Time Complexity: O(n! * n) */ public final class UniquePermutation { diff --git a/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java b/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java index 1854cab20a7f..fbf53bffcca2 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 diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java index 452f17b6ace6..ddb8b8baf4d6 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -2,12 +2,12 @@ /** * 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 = * [ @@ -18,19 +18,19 @@ * 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. - * + *

* 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. - * + *

* Space Complexity: O(L) * - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word). */ diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java index e6bd35720d9f..75d4e8300757 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java @@ -2,12 +2,12 @@ /** * 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. - * + *

* Example usage: *

  * int decimal = BcdConversion.bcdToDecimal(0x1234);
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/CountBitsFlip.java b/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java index 8d2c757e5e0a..97f381ff87f5 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java @@ -2,16 +2,16 @@ /** * Implementation to count number of bits to be flipped to convert A to B - * + *

* Problem: Given two numbers A and B, count the number of bits needed to be * flipped to convert A to B. - * + *

* Example: * A = 10 (01010 in binary) * B = 20 (10100 in binary) * XOR = 30 (11110 in binary) - positions where bits differ * Answer: 4 bits need to be flipped - * + *

* Time Complexity: O(log n) - where n is the number of set bits * Space Complexity: O(1) * @@ -25,7 +25,7 @@ private CountBitsFlip() { /** * Counts the number of bits that need to be flipped to convert a to b - * + *

* Algorithm: * 1. XOR a and b to get positions where bits differ * 2. Count the number of set bits in the XOR result diff --git a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java index 9a761c572e2c..b9f8c0d6d43e 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java @@ -3,7 +3,7 @@ /** * 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) diff --git a/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java index 2398b8214371..a0e26f4cb2ff 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,7 +25,7 @@ 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}. * diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java index 1b8962344ea7..cfb3837ed42d 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java @@ -6,8 +6,8 @@ * 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) + *

+ * Author: Bama Charan Chhando(https://github.com/BamaCharanChhandogi) */ public final class IndexOfRightMostSetBit { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java index 09d5383322ff..234458aa41c0 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java @@ -2,7 +2,7 @@ /** * Checks whether a number is even - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public final class IsEven { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java index 4cdf3c6faa3e..6807f34a6e07 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java @@ -5,7 +5,7 @@ * A power of two is a number that can be expressed as 2^n where n is a non-negative integer. * This class provides a method to determine if a given integer is a power of two using bit manipulation. * - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public final class IsPowerTwo { private IsPowerTwo() { @@ -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..3b4d148a5cb9 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java @@ -2,7 +2,7 @@ /** * Lowest Set Bit - * @author Prayas Kumar (https://github.com/prayas7102) + * @author Prayas Kumar (...) */ public final class LowestSetBit { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java index 17e1a73ec062..e167f94a06a6 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java @@ -3,17 +3,17 @@ /** * 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. * - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan...ranChhandogi) */ public final class NonRepeatingNumberFinder { private NonRepeatingNumberFinder() { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java index bd4868d4dbd5..88d5f051bd72 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java @@ -4,20 +4,20 @@ * 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 * - * @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) + * @author Lakshyajeet SGoyal (https://github.com/DarkMatter-999) */ public final class NumberAppearingOddTimes { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java b/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java index a2da37aa81ee..128775dba000 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. * - 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 aae3a996e49d..97908141618b 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java @@ -1,8 +1,8 @@ package com.thealgorithms.bitmanipulation; /** - * @author - https://github.com/Monk-AbhinayVerma - * @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement + * @author - ... + * @Wikipedia - ... * The class OnesComplement computes the complement of binary number * and returns * the complemented binary string. diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java index 12c269d9be48..56c97e7322d3 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java @@ -4,14 +4,14 @@ * This class provides a method to reverse the bits of a 32-bit integer. * Reversing the bits means that the least significant bit (LSB) becomes * the most significant bit (MSB) and vice versa. - * + *

* Example: * Input (binary): 00000010100101000001111010011100 (43261596) * Output (binary): 00111001011110000010100101000000 (964176192) - * + *

* Time Complexity: O(32) - A fixed number of 32 iterations * Space Complexity: O(1) - No extra space used - * + *

* Note: * - If the input is negative, Java handles it using two’s complement representation. * - This function works on 32-bit integers by default. diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java index 624a4e2b858a..98f5d867777a 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java @@ -4,19 +4,19 @@ * 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) + *

+ * Aulukasb1b (https://github.com/lukasb1b) */ public final class SingleBitOperations { private SingleBitOperations() { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java index 98a7de8bdf1a..694acea67d36 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java @@ -3,11 +3,11 @@ /** * A utility class to swap every pair of adjacent bits in a given integer. * This operation shifts the even-positioned bits to odd positions and vice versa. - * + *

* Example: * - Input: 2 (binary: `10`) → Output: 1 (binary: `01`) * - Input: 43 (binary: `101011`) → Output: 23 (binary: `010111`) - * + *

* **Explanation of the Algorithm:** * 1. Mask even-positioned bits: Using `0xAAAAAAAA` (binary: `101010...`), * which selects bits in even positions. @@ -17,13 +17,13 @@ * - Right-shift even-positioned bits by 1 to move them to odd positions. * - Left-shift odd-positioned bits by 1 to move them to even positions. * 4. Combine both shifted results using bitwise OR (`|`) to produce the final result. - * + *

* Use Case: This algorithm can be useful in applications involving low-level bit manipulation, * such as encoding, data compression, or cryptographic transformations. - * + *

* Time Complexity: O(1) (constant time, since operations are bitwise). - * - * Author: Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) + *

+ * Author: LakshSingh Goyal (https://github.com/DarkMatter-999) */ public final class SwapAdjacentBits { private SwapAdjacentBits() { diff --git a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java index 9b8cecd791a6..146a3cf5cb4c 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java @@ -13,7 +13,7 @@ * *

Algorithm originally suggested by Jon von Neumann. * - * @author Abhinay Verma (https://github.com/Monk-AbhinayVerma) + * @author Abhinay Verma (...) */ 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..1b8a1b7252eb 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java @@ -2,12 +2,12 @@ /** * 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. - * + *

* Example usage: *

  * int binary = Xs3Conversion.xs3ToBinary(0x4567);
diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
index 979f18532eaa..c12907088ee2 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 - * + *

* 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 { @@ -23,8 +23,8 @@ private AffineCipher() { } // Key values of a and b - static int a = 17; - static int b = 20; + static final int a = 17; + static final int b = 20; /** * Encrypts a message using the Affine cipher. 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/Autokey.java b/src/main/java/com/thealgorithms/ciphers/Autokey.java index bb67f512accf..3a07a9328c78 100644 --- a/src/main/java/com/thealgorithms/ciphers/Autokey.java +++ b/src/main/java/com/thealgorithms/ciphers/Autokey.java @@ -5,7 +5,7 @@ * as it improves upon the classic Vigenère Cipher by using the plaintext itself to * extend the key. This makes it harder to break using frequency analysis, as it * doesn’t rely solely on a repeated key. - * https://en.wikipedia.org/wiki/Autokey_cipher + * ... * * @author bennybebo */ diff --git a/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java b/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java index 16dfd6e674af..945cc372499a 100644 --- a/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java @@ -7,7 +7,7 @@ * The Baconian Cipher is a substitution cipher where each letter is represented * by a group of five binary digits (A's and B's). It can also be used to hide * messages within other texts, making it a simple form of steganography. - * https://en.wikipedia.org/wiki/Bacon%27s_cipher + * ... * * @author Bennybebo */ diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index ea1807e62710..33439c6c199a 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -11,7 +11,7 @@ public class Blowfish { // Initializing substitution boxes - String[][] sBox = { + final String[][] sBox = { { "d1310ba6", "98dfb5ac", @@ -1047,7 +1047,7 @@ public class Blowfish { }; // Initializing subkeys with digits of pi - String[] subKeys = { + final String[] subKeys = { "243f6a88", "85a308d3", "13198a2e", @@ -1069,7 +1069,7 @@ public class Blowfish { }; // Initializing modVal to 2^32 - long modVal = 4294967296L; + final long modVal = 4294967296L; /** * This method returns binary representation of the hexadecimal number passed as parameter @@ -1115,7 +1115,7 @@ private String binToHex(String binary) { * This method returns a string obtained by XOR-ing two strings of same length passed a method * parameters * - * @param String a and b are string objects which will be XORed and are to be of same length + * @param a and @param 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) { @@ -1133,12 +1133,13 @@ private String xor(String a, String b) { * This method returns addition of two hexadecimal numbers passed as parameters and moded with * 2^32 * - * @param String a and b are hexadecimal numbers + * @param a hexadecimal number + * @param b hexadecimal number * @return String object which is a is addition that is then moded with 2^32 of hex numbers * passed as parameters */ private String addBin(String a, String b) { - String ans = ""; + String ans; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; @@ -1154,7 +1155,7 @@ private String addBin(String a, String b) { */ private String f(String plainText) { String[] a = new String[4]; - String ans = ""; + String ans; for (int i = 0; i < 8; i += 2) { // column number for S-box is a 8-bit value long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2); @@ -1198,8 +1199,8 @@ private String round(int time, String plainText) { * This method returns cipher text for the plaintext passed as the first parameter generated * using the key passed as the second parameter * - * @param String plainText is the text which is to be encrypted - * @param String key is the key which is to be used for generating cipher text + * @param plainText is the text which is to be encrypted + * @param key is the key which is to be used for generating cipher text * @return String cipherText is the encrypted value */ String encrypt(String plainText, String key) { @@ -1222,8 +1223,8 @@ String encrypt(String plainText, String key) { * This method returns plaintext for the ciphertext passed as the first parameter decoded * using the key passed as the second parameter * - * @param String ciphertext is the text which is to be decrypted - * @param String key is the key which is to be used for generating cipher text + * @param cipherText is the text which is to be decrypted + * @param key is the key which is to be used for generating cipher text * @return String plainText is the decrypted text */ String decrypt(String cipherText, String key) { diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java index b6b889b079ca..4bf1d121d498 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -80,7 +80,7 @@ public static String decrypt() { wordDecrypted.append(item); } } - return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, ""); + return wordDecrypted.toString().replace(ENCRYPTION_FIELD, ""); } /** diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java index 7f3eed70f3c2..a8d534b15cd2 100644 --- a/src/main/java/com/thealgorithms/ciphers/DES.java +++ b/src/main/java/com/thealgorithms/ciphers/DES.java @@ -2,7 +2,7 @@ /** * This class is build to demonstrate the application of the DES-algorithm - * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied + * (...) on a plain English message. The supplied * key must be in form of a 64 bit binary String. */ public class DES { 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/PermutationCipher.java b/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java index ce443545db1d..686dfb3e4219 100644 --- a/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java @@ -7,7 +7,7 @@ * A Java implementation of Permutation Cipher. * It is a type of transposition cipher in which the plaintext is divided into blocks * and the characters within each block are rearranged according to a fixed permutation key. - * + *

* For example, with key {3, 1, 2} and plaintext "HELLO", the text is divided into blocks * of 3 characters: "HEL" and "LO" (with padding). The characters are then rearranged * according to the key positions. diff --git a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java index 76ceb6dbce31..003373036e0d 100644 --- a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java @@ -3,7 +3,7 @@ public class PlayfairCipher { private char[][] matrix; - private String key; + private final String key; public PlayfairCipher(String key) { this.key = key; diff --git a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java index d7eaea757001..01307642562a 100644 --- a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java @@ -2,72 +2,162 @@ import java.util.Scanner; +/** + * ProductCipher combines substitution and transposition ciphers. + * Refactoring notes: + * - SRP: encryption, decryption, padding, and I/O are each in their own method. + * - OCP/DIP: SubstitutionCipher and TranspositionCipher implement the Cipher + * interface, so new cipher types can be added without touching existing code. + * - StringBuffer replaced with StringBuilder (thread-safety not needed here). + * - Magic number 5 (Caesar shift) extracted to a named constant. + * - The `n` variable is no longer reused for two different purposes. + * - God-method main() now delegates to focused, testable helpers. + */ final class ProductCipher { + private ProductCipher() { } - public static void main(String[] args) { - try (Scanner sc = new Scanner(System.in)) { - System.out.println("Enter the input to be encrypted: "); - String substitutionInput = sc.nextLine(); - System.out.println(" "); - System.out.println("Enter a number: "); - int n = sc.nextInt(); - - // Substitution encryption - StringBuffer substitutionOutput = new StringBuffer(); - for (int i = 0; i < substitutionInput.length(); i++) { - char c = substitutionInput.charAt(i); - substitutionOutput.append((char) (c + 5)); + // ------------------------------------------------------------------ // + // Cipher abstraction (Open/Closed + Dependency-Inversion principles) // + // ------------------------------------------------------------------ // + + interface Cipher { + String encrypt(String input, int key); + String decrypt(String input, int key); + } + + // ------------------------------------------------------------------ // + // Substitution cipher // + // ------------------------------------------------------------------ // + + static final class SubstitutionCipher implements Cipher { + + private static final int SHIFT = 5; + + @Override + public String encrypt(String input, int key) { + // `key` is unused for a fixed-shift substitution cipher, + // but kept in the signature to satisfy the Cipher contract. + StringBuilder result = new StringBuilder(input.length()); + for (char c : input.toCharArray()) { + result.append((char) (c + SHIFT)); } - System.out.println(" "); - System.out.println("Substituted text: "); - System.out.println(substitutionOutput); - - // Transposition encryption - String transpositionInput = substitutionOutput.toString(); - int modulus = transpositionInput.length() % n; - if (modulus != 0) { - modulus = n - modulus; - - for (; modulus != 0; modulus--) { - transpositionInput += "/"; - } + return result.toString(); + } + + @Override + public String decrypt(String input, int key) { + StringBuilder result = new StringBuilder(input.length()); + for (char c : input.toCharArray()) { + result.append((char) (c - SHIFT)); + } + return result.toString(); + } + } + + // ------------------------------------------------------------------ // + // Transposition cipher // + // ------------------------------------------------------------------ // + + static final class TranspositionCipher implements Cipher { + + private static final char PAD_CHAR = '/'; + + /** Pad the text so its length is a multiple of {@code numRows}. */ + String pad(String text, int numRows) { + int remainder = text.length() % numRows; + if (remainder == 0) { + return text; } - StringBuffer transpositionOutput = new StringBuffer(); - System.out.println(" "); + int paddingNeeded = numRows - remainder; + StringBuilder padded = new StringBuilder(text); + padded.repeat(String.valueOf(PAD_CHAR), Math.max(0, paddingNeeded)); + return padded.toString(); + } + + /** + * Reads the padded text column-by-column (row-major write, column-major read). + * Prints the transposition matrix as a `side effect for traceability. + */ + @Override + public String encrypt(String input, int numRows) { + String padded = pad(input, numRows); + int numCols = padded.length() / numRows; + System.out.println("Transposition Matrix: "); - for (int i = 0; i < n; i++) { - for (int j = 0; j < transpositionInput.length() / n; j++) { - char c = transpositionInput.charAt(i + (j * n)); + StringBuilder result = new StringBuilder(padded.length()); + + for (int row = 0; row < numRows; row++) { + for (int col = 0; col < numCols; col++) { + char c = padded.charAt(row + col * numRows); System.out.print(c); - transpositionOutput.append(c); + result.append(c); } System.out.println(); } - System.out.println(" "); - System.out.println("Final encrypted text: "); - System.out.println(transpositionOutput); - - // Transposition decryption - n = transpositionOutput.length() / n; - StringBuffer transpositionPlaintext = new StringBuffer(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < transpositionOutput.length() / n; j++) { - char c = transpositionOutput.charAt(i + (j * n)); - transpositionPlaintext.append(c); + + return result.toString(); + } + + /** Reverses the column-major read by treating the cipher as row-major. */ + @Override + public String decrypt(String input, int numRows) { + int numCols = input.length() / numRows; + StringBuilder result = new StringBuilder(input.length()); + + for (int row = 0; row < numCols; row++) { + for (int col = 0; col < numRows; col++) { + result.append(input.charAt(row + col * numCols)); } } + return result.toString(); + } + } - // Substitution decryption - StringBuffer plaintext = new StringBuffer(); - for (int i = 0; i < transpositionPlaintext.length(); i++) { - char c = transpositionPlaintext.charAt(i); - plaintext.append((char) (c - 5)); - } + // ------------------------------------------------------------------ // + // I/O helper (Single-Responsibility: only reads user input) // + // ------------------------------------------------------------------ // + + private static String readPlaintext(Scanner sc) { + System.out.println("Enter the input to be encrypted: "); + return sc.nextLine(); + } + + private static int readKey(Scanner sc) { + System.out.println("Enter a number: "); + return sc.nextInt(); + } + + // ------------------------------------------------------------------ // + // Entry point – thin orchestration only // + // ------------------------------------------------------------------ // + + public static void main(String[] args) { + Cipher substitution = new SubstitutionCipher(); + Cipher transposition = new TranspositionCipher(); + + try (Scanner sc = new Scanner(System.in)) { + String plaintext = readPlaintext(sc); + int key = readKey(sc); + + // Encrypt + String afterSubstitution = substitution.encrypt(plaintext, key); + System.out.println("\nSubstituted text: "); + System.out.println(afterSubstitution); + + System.out.println(); + String ciphertext = transposition.encrypt(afterSubstitution, key); + System.out.println("\nFinal encrypted text: "); + System.out.println(ciphertext); + + // Decrypt (use a separate variable; never reuse `key` for a different meaning) + int decryptionKey = ciphertext.length() / key; + String afterTranspositionDecrypt = transposition.decrypt(ciphertext, decryptionKey); + String recovered = substitution.decrypt(afterTranspositionDecrypt, key); System.out.println("Plaintext: "); - System.out.println(plaintext); + System.out.println(recovered); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index 28af1a62032a..8c6242ecb68e 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);
diff --git a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
index f81252980468..596c414b79b4 100644
--- a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
@@ -5,8 +5,8 @@
 /**
  * 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
+ * ...
+ * @author ...
  */
 
 public class RailFenceCipher {
diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
index f6c88ef730ec..b4edcf20ac50 100644
--- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
@@ -15,8 +15,6 @@ public class SimpleSubCipher {
     /**
      * Encrypt text by replacing each element with its opposite character.
      *
-     * @param message
-     * @param cipherSmall
      * @return Encrypted message
      */
     public String encode(String message, String cipherSmall) {
@@ -52,8 +50,6 @@ public String encode(String message, String cipherSmall) {
      * Decrypt message by replacing each element with its opposite character in
      * cipher.
      *
-     * @param encryptedMessage
-     * @param cipherSmall
      * @return message
      */
     public String decode(String encryptedMessage, String cipherSmall) {
diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
index 0f117853bb85..ad5ee18a3cd5 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 * diff --git a/src/main/java/com/thealgorithms/ciphers/XORCipher.java b/src/main/java/com/thealgorithms/ciphers/XORCipher.java index a612ccfbcdef..9070255b9c1d 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. - * + *

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

* Reference: XOR Cipher - Wikipedia * * @author lcsjunior diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index cc2e9105229a..0e39c7a9ea81 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. * @@ -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/compression/LZ78.java b/src/main/java/com/thealgorithms/compression/LZ78.java index 904c379cc2a2..28fdd50d521f 100644 --- a/src/main/java/com/thealgorithms/compression/LZ78.java +++ b/src/main/java/com/thealgorithms/compression/LZ78.java @@ -55,7 +55,7 @@ public record Token(int index, char nextChar) { * Each node represents a phrase and can have child nodes for extended phrases. */ private static final class TrieNode { - Map children = new HashMap<>(); + final Map children = new HashMap<>(); int index = -1; // -1 means not assigned yet } diff --git a/src/main/java/com/thealgorithms/conversions/AffineConverter.java b/src/main/java/com/thealgorithms/conversions/AffineConverter.java index 199a6dd517d5..720b570c2602 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. */ diff --git a/src/main/java/com/thealgorithms/conversions/AnytoAny.java b/src/main/java/com/thealgorithms/conversions/AnytoAny.java index e7bdbc2b79c4..06ba653af076 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. */ diff --git a/src/main/java/com/thealgorithms/conversions/Base64.java b/src/main/java/com/thealgorithms/conversions/Base64.java index 5219c4ba7f4e..aebca161839f 100644 --- a/src/main/java/com/thealgorithms/conversions/Base64.java +++ b/src/main/java/com/thealgorithms/conversions/Base64.java @@ -8,14 +8,14 @@ * Base64 is a group of binary-to-text encoding schemes that represent binary data * in an ASCII string format by translating it into a radix-64 representation. * Each base64 digit represents exactly 6 bits of data. - * + *

* Base64 encoding is commonly used when there is a need to encode binary data * that needs to be stored and transferred over media that are designed to deal * with textual data. - * - * Wikipedia Reference: https://en.wikipedia.org/wiki/Base64 + *

+ * Wikipedia Refhttps://en.wikipedia.org/wiki/Base64 * Author: Nithin U. - * Github: https://github.com/NithinU2802 + * https://github.com/NithinU2802 */ public final class Base64 { diff --git a/src/main/java/com/thealgorithms/conversions/IPConverter.java b/src/main/java/com/thealgorithms/conversions/IPConverter.java index 765cb0201dd5..21821553933d 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 * diff --git a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java index d42ffd027514..bf13e5597cff 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. diff --git a/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java b/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java index e85c608af5d0..85168d0d9587 100644 --- a/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java +++ b/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java @@ -60,7 +60,7 @@ private static String convertToWords(int number) { int hundredsDigit = number / 100; if (hundredsDigit > 0) { - if (result.length() > 0) { + if (!result.isEmpty()) { result.insert(0, " "); } result.insert(0, String.format("%s Hundred", BASE_NUMBERS_MAP.get(hundredsDigit))); @@ -93,7 +93,7 @@ public static String integerToEnglishWords(int number) { if (index > 0) { subResult += " " + THOUSAND_POWER_MAP.get(index); } - if (result.length() > 0) { + if (!result.isEmpty()) { result.insert(0, " "); } result.insert(0, subResult); 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/TemperatureConverter.java b/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java index 901db17c665d..b9dd2315bc96 100644 --- a/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java +++ b/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java @@ -12,7 +12,7 @@ * *

This class is final and cannot be instantiated. * - * @author krishna-medapati (https://github.com/krishna-medapati) + * @author krishna-medapati (...) * @see Wikipedia: Temperature Conversion */ public final class TemperatureConverter { diff --git a/src/main/java/com/thealgorithms/conversions/UnitConversions.java b/src/main/java/com/thealgorithms/conversions/UnitConversions.java index 15f74a21a17e..8cbc2bf46610 100644 --- a/src/main/java/com/thealgorithms/conversions/UnitConversions.java +++ b/src/main/java/com/thealgorithms/conversions/UnitConversions.java @@ -3,49 +3,75 @@ import static java.util.Map.entry; import java.util.Map; -import org.apache.commons.lang3.tuple.Pair; /** * A utility class to perform unit conversions between different measurement systems. - * - *

Currently, the class supports temperature conversions between several scales: - * Celsius, Fahrenheit, Kelvin, Réaumur, Delisle, and Rankine. - * - *

Example Usage

- *
- *   double result = UnitConversions.TEMPERATURE.convert("Celsius", "Fahrenheit", 100.0);
- *   // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C)
- * 
- * - *

This class makes use of an {@link UnitsConverter} that handles the conversion logic - * based on predefined affine transformations. These transformations include scaling factors - * and offsets for temperature conversions. - * - *

Temperature Scales Supported

- *
    - *
  • Celsius
  • - *
  • Fahrenheit
  • - *
  • Kelvin
  • - *
  • Réaumur
  • - *
  • Delisle
  • - *
  • Rankine
  • - *
*/ public final class UnitConversions { - private UnitConversions() { + + /** + * Enum managing supported temperature scales to eliminate magic strings + * and enforce structural type safety internally. + */ + private enum TemperatureScale { + CELSIUS("Celsius"), + FAHRENHEIT("Fahrenheit"), + KELVIN("Kelvin"), + REAUMUR("Réaumur"), + DELISLE("Delisle"), + RANKINE("Rankine"); + + private final String unitName; + + TemperatureScale(String unitName) { + this.unitName = unitName; + } + + public String getName() { + return unitName; + } } + // Mathematical Constants for Conversions (Eliminating Magic Numbers) + private static final double ABSOLUTE_ZERO_CELSIUS = -273.15; + + private static final double CELSIUS_TO_FAHRENHEIT_SCALE = 9.0 / 5.0; + private static final double CELSIUS_TO_FAHRENHEIT_OFFSET = 32.0; + + private static final double REAUMUR_TO_CELSIUS_SCALE = 5.0 / 4.0; + + private static final double DELISLE_TO_CELSIUS_SCALE = -2.0 / 3.0; + private static final double DELISLE_TO_CELSIUS_OFFSET = 100.0; + + private static final double RANKINE_TO_KELVIN_SCALE = 5.0 / 9.0; + /** - * A preconfigured instance of {@link UnitsConverter} for temperature conversions. - * The converter handles conversions between the following temperature units: - *
    - *
  • Kelvin to Celsius
  • - *
  • Celsius to Fahrenheit
  • - *
  • Réaumur to Celsius
  • - *
  • Delisle to Celsius
  • - *
  • Rankine to Kelvin
  • - *
+ * Preconfigured instance of UnitsConverter for temperature conversions. */ - public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)), entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)), - entry(Pair.of("Réaumur", "Celsius"), new AffineConverter(5.0 / 4.0, 0.0)), entry(Pair.of("Delisle", "Celsius"), new AffineConverter(-2.0 / 3.0, 100.0)), entry(Pair.of("Rankine", "Kelvin"), new AffineConverter(5.0 / 9.0, 0.0)))); -} + public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries( + entry( + new UnitPair(TemperatureScale.KELVIN.getName(), TemperatureScale.CELSIUS.getName()), + new AffineConverter(1.0, ABSOLUTE_ZERO_CELSIUS) + ), + entry( + new UnitPair(TemperatureScale.CELSIUS.getName(), TemperatureScale.FAHRENHEIT.getName()), + new AffineConverter(CELSIUS_TO_FAHRENHEIT_SCALE, CELSIUS_TO_FAHRENHEIT_OFFSET) + ), + entry( + new UnitPair(TemperatureScale.REAUMUR.getName(), TemperatureScale.CELSIUS.getName()), + new AffineConverter(REAUMUR_TO_CELSIUS_SCALE, 0.0) + ), + entry( + new UnitPair(TemperatureScale.DELISLE.getName(), TemperatureScale.CELSIUS.getName()), + new AffineConverter(DELISLE_TO_CELSIUS_SCALE, DELISLE_TO_CELSIUS_OFFSET) + ), + entry( + new UnitPair(TemperatureScale.RANKINE.getName(), TemperatureScale.KELVIN.getName()), + new AffineConverter(RANKINE_TO_KELVIN_SCALE, 0.0) + ) + )); + + private UnitConversions() { + // Prevent instantiation + } +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java index 00690b2c0f9b..c64053a81835 100644 --- a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java +++ b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java @@ -4,144 +4,161 @@ import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Set; -import org.apache.commons.lang3.tuple.Pair; /** - * A class that handles unit conversions using affine transformations. - * - *

The {@code UnitsConverter} allows converting values between different units using - * pre-defined affine conversion formulas. Each conversion is represented by an - * {@link AffineConverter} that defines the scaling and offset for the conversion. - * - *

For each unit, both direct conversions (e.g., Celsius to Fahrenheit) and inverse - * conversions (e.g., Fahrenheit to Celsius) are generated automatically. It also computes - * transitive conversions (e.g., Celsius to Kelvin via Fahrenheit if both conversions exist). - * - *

Key features include: - *

    - *
  • Automatic handling of inverse conversions (e.g., Fahrenheit to Celsius).
  • - *
  • Compositional conversions, meaning if conversions between A -> B and B -> C exist, - * it can automatically generate A -> C conversion.
  • - *
  • Supports multiple unit systems as long as conversions are provided in pairs.
  • - *
- * - *

Example Usage

- *
- * Map<Pair<String, String>, AffineConverter> basicConversions = Map.ofEntries(
- *     entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)),
- *     entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15))
- * );
- *
- * UnitsConverter converter = new UnitsConverter(basicConversions);
- * double result = converter.convert("Celsius", "Fahrenheit", 100.0);
- * // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C)
- * 
- * - *

Exception Handling

- *
    - *
  • If the input unit and output unit are the same, an {@link IllegalArgumentException} is thrown.
  • - *
  • If a conversion between the requested units does not exist, a {@link NoSuchElementException} is thrown.
  • - *
+ * Represents a directed conversion between two units using an affine transformation. */ -public final class UnitsConverter { - private final Map, AffineConverter> conversions; - private final Set units; +record UnitPair(String from, String to) { + UnitPair { + Objects.requireNonNull(from); + Objects.requireNonNull(to); + } - private static void putIfNeeded(Map, AffineConverter> conversions, final String inputUnit, final String outputUnit, final AffineConverter converter) { - if (!inputUnit.equals(outputUnit)) { - final var key = Pair.of(inputUnit, outputUnit); - conversions.putIfAbsent(key, converter); - } + @Override + public String toString() { + return from + " → " + to; } +} - private static Map, AffineConverter> addInversions(final Map, AffineConverter> knownConversions) { - Map, AffineConverter> res = new HashMap, AffineConverter>(); - for (final var curConversion : knownConversions.entrySet()) { - final var inputUnit = curConversion.getKey().getKey(); - final var outputUnit = curConversion.getKey().getValue(); - putIfNeeded(res, inputUnit, outputUnit, curConversion.getValue()); - putIfNeeded(res, outputUnit, inputUnit, curConversion.getValue().invert()); - } - return res; +/** + * Abstraction for a conversion graph that can compute transitive closures. + */ +interface ConversionGraph { + double convert(String from, String to, double value); + Set availableUnits(); + boolean hasConversion(String from, String to); +} + +/** + * Main public API — thin facade following SRP. + */ +public final class UnitsConverter implements ConversionGraph { + + private final ConversionGraph graph; + + /** + * Creates a new UnitsConverter with automatic inverse and transitive conversions. + * + * @param basicConversions initial direct conversions + */ + public UnitsConverter(Map basicConversions) { + this.graph = new AffineConversionGraph(basicConversions); } - private static Map, AffineConverter> addCompositions(final Map, AffineConverter> knownConversions) { - Map, AffineConverter> res = new HashMap, AffineConverter>(); - for (final var first : knownConversions.entrySet()) { - final var firstKey = first.getKey(); - putIfNeeded(res, firstKey.getKey(), firstKey.getValue(), first.getValue()); - for (final var second : knownConversions.entrySet()) { - final var secondKey = second.getKey(); - if (firstKey.getValue().equals(secondKey.getKey())) { - final var newConversion = second.getValue().compose(first.getValue()); - putIfNeeded(res, firstKey.getKey(), secondKey.getValue(), newConversion); - } - } + @Override + public double convert(String from, String to, double value) { + if (from.equals(to)) { + throw new IllegalArgumentException("Input and output units must be different."); } - return res; + return graph.convert(from, to, value); } - private static Map, AffineConverter> addAll(final Map, AffineConverter> knownConversions) { - final var res = addInversions(knownConversions); - return addCompositions(res); + @Override + public Set availableUnits() { + return graph.availableUnits(); } - private static Map, AffineConverter> computeAllConversions(final Map, AffineConverter> basicConversions) { - var tmp = basicConversions; - var res = addAll(tmp); - while (res.size() != tmp.size()) { - tmp = res; - res = addAll(tmp); + @Override + public boolean hasConversion(String from, String to) { + return graph.hasConversion(from, to); + } +} + +/** + * Internal implementation handling the conversion graph and transitive closure. + * Follows SRP and DIP. + */ +final class AffineConversionGraph implements ConversionGraph { + + private final Map conversions; + private final Set units; + + AffineConversionGraph(Map basicConversions) { + Map initial = basicConversions != null + ? new HashMap<>(basicConversions) + : Map.of(); + + this.conversions = computeFullClosure(initial); + this.units = extractUnits(this.conversions); + } + + private Map computeFullClosure(Map basic) { + Map current = addInversions(basic); + + boolean changed; + do { + Map next = addCompositions(current); + changed = next.size() > current.size(); + current = next; + } while (changed); + + return Map.copyOf(current); // immutable + } + + private Map addInversions(Map known) { + Map result = new HashMap<>(known.size() * 2); + + for (var entry : known.entrySet()) { + UnitPair pair = entry.getKey(); + AffineConverter conv = entry.getValue(); + + putIfDifferent(result, pair.from(), pair.to(), conv); + putIfDifferent(result, pair.to(), pair.from(), conv.invert()); } - return res; + return result; } - private static Set extractUnits(final Map, AffineConverter> conversions) { - Set res = new HashSet<>(); - for (final var conversion : conversions.entrySet()) { - res.add(conversion.getKey().getKey()); + private Map addCompositions(Map known) { + Map result = new HashMap<>(known); + + for (var first : known.entrySet()) { + UnitPair firstPair = first.getKey(); + AffineConverter firstConv = first.getValue(); + + for (var second : known.entrySet()) { + UnitPair secondPair = second.getKey(); + if (firstPair.to().equals(secondPair.from())) { + AffineConverter composed = second.getValue().compose(firstConv); + putIfDifferent(result, firstPair.from(), secondPair.to(), composed); + } + } } - return res; + return result; } - /** - * Constructor for {@code UnitsConverter}. - * - *

Accepts a map of basic conversions and automatically generates inverse and - * transitive conversions. - * - * @param basicConversions the initial set of unit conversions to add. - */ - public UnitsConverter(final Map, AffineConverter> basicConversions) { - conversions = computeAllConversions(basicConversions); - units = extractUnits(conversions); + private void putIfDifferent(Map map, String from, String to, AffineConverter conv) { + if (!from.equals(to)) { + map.putIfAbsent(new UnitPair(from, to), conv); + } } - /** - * Converts a value from one unit to another. - * - * @param inputUnit the unit of the input value. - * @param outputUnit the unit to convert the value into. - * @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. - */ - public double convert(final String inputUnit, final String outputUnit, final double value) { - if (inputUnit.equals(outputUnit)) { - throw new IllegalArgumentException("inputUnit must be different from outputUnit."); + private Set extractUnits(Map convs) { + Set unitsSet = new HashSet<>(); + for (UnitPair pair : convs.keySet()) { + unitsSet.add(pair.from()); } - final var conversionKey = Pair.of(inputUnit, outputUnit); - return conversions.computeIfAbsent(conversionKey, k -> { throw new NoSuchElementException("No converter for: " + k); }).convert(value); + return Set.copyOf(unitsSet); } - /** - * Retrieves the set of all units supported by this converter. - * - * @return a set of available units. - */ + @Override + public double convert(String from, String to, double value) { + UnitPair key = new UnitPair(from, to); + AffineConverter converter = conversions.get(key); + if (converter == null) { + throw new NoSuchElementException("No converter found for: " + key); + } + return converter.convert(value); + } + + @Override public Set availableUnits() { return units; } -} + + @Override + public boolean hasConversion(String from, String to) { + return conversions.containsKey(new UnitPair(from, to)); + } +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java b/src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java index fa048434a187..457088ce424c 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java @@ -51,8 +51,8 @@ public final class FIFOCache { * @param the type of the value being cached */ private static class CacheEntry { - V value; - long expiryTime; + final V value; + final long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java index bf2b928ec33c..b40cb68aad81 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java @@ -21,7 +21,7 @@ * @param The type of keys maintained by this cache. * @param The type of mapped values. * - * @author Akshay Dubey (https://github.com/itsAkshayDubey) + * @author Akshay Dubey (...) */ public class LFUCache { @@ -138,14 +138,13 @@ private void addNodeWithUpdatedFrequency(Node node) { node.next = temp; temp.previous = node; this.head = node; - break; } else { node.next = temp; node.previous = temp.previous; temp.previous.next = node; temp.previous = node; - break; } + break; } else { temp = temp.next; if (temp == null) { diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java index df3d4da912fe..e4656c3b76f5 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java @@ -54,8 +54,8 @@ public final class LIFOCache { * @param the type of the value being cached */ private static class CacheEntry { - V value; - long expiryTime; + final V value; + final long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). 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/caches/RRCache.java b/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java index 1821872be9cd..bb88f3c954ba 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java @@ -53,8 +53,8 @@ public final class RRCache { * @param the type of the value being cached */ private static class CacheEntry { - V value; - long expiryTime; + final V value; + final long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java b/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java index 25b01bce19f3..62034efaff53 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java @@ -11,9 +11,9 @@ * This implementation supports incrementing, querying the total count, * comparing with other G-Counters, and merging with another G-Counter * to compute the element-wise maximum. - * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) + * (...) * - * @author itakurah (https://github.com/itakurah) + * @author itakurah (...) */ class GCounter { diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/GSet.java b/src/main/java/com/thealgorithms/datastructures/crdt/GSet.java index 2b8959ed0136..21c623def1b0 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/GSet.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/GSet.java @@ -9,9 +9,9 @@ * it cannot be removed. The merge operation of two G-Sets is their union. * This implementation supports adding elements, looking up elements, comparing with other G-Sets, * and merging with another G-Set to create a new G-Set containing all unique elements from both sets. - * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) + * (...) * - * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) + * @author itakurah (Niklas Hoefflin) (...) */ public class GSet { diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java b/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java index d33bd3ee84d9..347ffb801966 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java @@ -110,8 +110,8 @@ private Element resolveConflict(Element e1, Element e2) { * @param The type of the key associated with the element. */ class Element { - T key; - Instant timestamp; + final T key; + final Instant timestamp; /** * Constructs a new Element with the specified key and timestamp. diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/ORSet.java b/src/main/java/com/thealgorithms/datastructures/crdt/ORSet.java index a4cc2ffdd4a6..07defb00488b 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/ORSet.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/ORSet.java @@ -16,7 +16,7 @@ * and merging with another OR-Set to create a new OR-Set containing all unique elements * from both sets. * - * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) + * @author itakurah (Niklas Hoefflin) (...) * @see Conflict-free_replicated_data_type * @see itakurah (Niklas Hoefflin) */ @@ -166,7 +166,6 @@ public void merge(ORSet other) { */ public static class Pair { private final T element; - private final String uniqueTag; /** * Constructs a pair with the specified element and unique tag. @@ -176,7 +175,6 @@ public static class Pair { */ public Pair(T element, String uniqueTag) { this.element = element; - this.uniqueTag = uniqueTag; } /** diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java b/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java index 53c21dcbd108..0c8dccf107d9 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java @@ -11,9 +11,9 @@ * This implementation supports incrementing, decrementing, querying the total count, * comparing with other PN-Counters, and merging with another PN-Counter * to compute the element-wise maximum for both increment and decrement counters. - * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) + * (...) * - * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) + * @author itakurah (Niklas Hoefflin) (...) */ class PNCounter { diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/TwoPSet.java b/src/main/java/com/thealgorithms/datastructures/crdt/TwoPSet.java index c0ce17b2802b..35e36c21a3f3 100644 --- a/src/main/java/com/thealgorithms/datastructures/crdt/TwoPSet.java +++ b/src/main/java/com/thealgorithms/datastructures/crdt/TwoPSet.java @@ -10,9 +10,9 @@ * Once an element is removed and placed in the tombstone set, it cannot be re-added, adhering to "remove-wins" semantics. * This implementation supports querying the presence of elements, adding elements, removing elements, * comparing with other 2P-Sets, and merging two 2P-Sets while preserving the remove-wins semantics. - * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) + * (...) * - * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) + * @author itakurah (Niklas Hoefflin) (...) */ public class TwoPSet { diff --git a/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java b/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java index 71951f67dfc8..03c0eac50537 100644 --- a/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java +++ b/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java @@ -21,7 +21,7 @@ public class DisjointSetUnionBySize { * Each node keeps track of its parent and the size of the set it represents. */ public static class Node { - public T value; + public final T value; public Node parent; public int size; // size of the set diff --git a/src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java b/src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java index 260f297bd713..4172a1bacc37 100644 --- a/src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java +++ b/src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java @@ -16,7 +16,7 @@ public class Node { /** * The data element associated with the node. */ - public T data; + public final T data; public Node(final T data) { this.data = data; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java index 741caa59c5b5..ee1e911069a0 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java @@ -19,7 +19,8 @@ private AStar() { * Represents a graph using an adjacency list. */ static class Graph { - private ArrayList> graph; + // 1. Made graph field final + private final ArrayList> graph; Graph(int size) { this.graph = new ArrayList<>(); @@ -43,9 +44,10 @@ private void addEdge(Edge edge) { * Represents an edge in the graph with a start node, end node, and weight. */ private static class Edge { - private int from; - private int to; - private int weight; + // 2, 3, 4. Made from, to, and weight fields final + private final int from; + private final int to; + private final int weight; Edge(int from, int to, int weight) { this.from = from; @@ -70,9 +72,10 @@ public int getWeight() { * Contains information about the path and its total distance. */ static class PathAndDistance { - private int distance; // total distance from the start node - private ArrayList path; // list of nodes in the path - private int estimated; // heuristic estimate for reaching the destination + // 5, 6, 7. Made distance, path, and estimated fields final + private final int distance; // total distance from the start node + private final ArrayList path; // list of nodes in the path + private final int estimated; // heuristic estimate for reaching the destination PathAndDistance(int distance, ArrayList path, int estimated) { this.distance = distance; @@ -141,4 +144,4 @@ public static PathAndDistance aStar(int from, int to, Graph graph, int[] heurist } return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index 5184dae58d28..5322e6870cb4 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -11,9 +11,9 @@ class BellmanFord /* */ { - int vertex; - int edge; - private Edge[] edges; + final int vertex; + final int edge; + private final Edge[] edges; private int index = 0; BellmanFord(int v, int e) { @@ -24,13 +24,13 @@ class BellmanFord /* class Edge { - int u; - int v; - int w; + final int u; + final int v; + final int w; /** - * @param u Source Vertex - * @param v End vertex + * @param a Source Vertex + * @param b End vertex * @param c Weight */ Edge(int a, int b, int c) { @@ -41,7 +41,7 @@ class Edge { } /** - * @param p[] Parent array which shows updates in edges + * @param p Parent array which shows updates in edges * @param i Current vertex under consideration */ void printPath(int[] p, int i) { @@ -124,7 +124,7 @@ public void go() { /** * @param source Starting vertex * @param end Ending vertex - * @param Edge Array of edges + * @param arr Array of edges */ public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java index 15ae5225533c..4d5e14dc5434 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}} - * + *

* 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}} - * + *

* 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. * @@ -44,14 +44,14 @@ private BipartiteGraphDFS() { * @param node Current vertex being processed * @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) { + private static boolean notbipartite(int v, ArrayList> adj, int[] color, int node) { if (color[node] == -1) { color[node] = 1; } for (Integer it : adj.get(node)) { if (color[it] == -1) { color[it] = 1 - color[node]; - if (!bipartite(v, adj, color, it)) { + if (!notbipartite(v, adj, color, it)) { return false; } } else if (color[it] == color[node]) { @@ -73,7 +73,7 @@ public static boolean isBipartite(int v, ArrayList> adj) { Arrays.fill(color, -1); for (int i = 0; i < v; i++) { if (color[i] == -1) { - if (!bipartite(v, adj, color, i)) { + if (!notbipartite(v, adj, color, i)) { return false; } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java index dcdb08ad133e..7aaf07e50a1d 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java @@ -5,9 +5,9 @@ /** * Boruvka's algorithm to find Minimum Spanning Tree - * (https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm) + * (...) * - * @author itakurah (https://github.com/itakurah) + * @author itakurah (...) */ final class BoruvkaAlgorithm { @@ -76,8 +76,8 @@ private static class Component { * Represents the state of Union-Find components and the result list */ private static class BoruvkaState { - List result; - Component[] components; + final List result; + final Component[] components; final Graph graph; BoruvkaState(final Graph graph) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java index 520a1681774a..6a83ea3f44a7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java @@ -13,7 +13,7 @@ class Graph> { class Node { - E name; + final E name; Node(E name) { this.name = name; @@ -22,8 +22,8 @@ class Node { class Edge { - Node startNode; - Node endNode; + final Node startNode; + final Node endNode; Edge(Node startNode, Node endNode) { this.startNode = startNode; @@ -31,8 +31,8 @@ class Edge { } } - ArrayList edgeList; - ArrayList nodeList; + final ArrayList edgeList; + final ArrayList nodeList; Graph() { edgeList = new ArrayList(); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java index aea2b74bd13b..63362d0b9a7f 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java @@ -6,9 +6,9 @@ class Cycle { private final int nodes; - private int[][] adjacencyMatrix; - private boolean[] visited; - ArrayList> cycles = new ArrayList>(); + private final int[][] adjacencyMatrix; + private final boolean[] visited; + final ArrayList> cycles = new ArrayList>(); Cycle() { Scanner in = new Scanner(System.in); @@ -62,7 +62,7 @@ private void dfs(Integer start, Integer curr, ArrayList temp) { } } - if (temp.size() > 0) { + if (!temp.isEmpty()) { temp.remove(temp.size() - 1); } visited[curr] = false; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DialsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DialsAlgorithm.java index da3fba88c618..16529feb5b78 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DialsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DialsAlgorithm.java @@ -10,11 +10,11 @@ * An implementation of Dial's Algorithm for the single-source shortest path problem. * This algorithm is an optimization of Dijkstra's algorithm and is particularly * efficient for graphs with small, non-negative integer edge weights. - * + *

* It uses a bucket queue (implemented here as a List of HashSets) to store vertices, * where each bucket corresponds to a specific distance from the source. This is more * efficient than a standard priority queue when the range of edge weights is small. - * + *

* Time Complexity: O(E + W * V), where E is the number of edges, V is the number * of vertices, and W is the maximum weight of any edge. * diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java index 70699a9461f7..4c94929d8bff 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java @@ -20,7 +20,7 @@ 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. * diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java index a686b808a970..8b5ba00834b0 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java @@ -23,7 +23,7 @@ public DijkstraOptimizedAlgorithm(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. * diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java index db716580d689..76ece5045f11 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java @@ -215,12 +215,12 @@ private static void contractBlossom(BlossomData blossomData) { * Auxiliary data class to encapsulate common parameters for the blossom operations. */ static class BlossomAuxData { - Queue queue; // Queue for BFS traversal - int[] parent; // Parent array to store the paths - int[] base; // Base array to track the base of each vertex - boolean[] inBlossom; // Flags to indicate if a vertex is in a blossom - int[] match; // Array to store matches for each vertex - boolean[] inQueue; // Flags to track vertices in the BFS queue + final Queue queue; // Queue for BFS traversal + final int[] parent; // Parent array to store the paths + final int[] base; // Base array to track the base of each vertex + final boolean[] inBlossom; // Flags to indicate if a vertex is in a blossom + final int[] match; // Array to store matches for each vertex + final boolean[] inQueue; // Flags to track vertices in the BFS queue BlossomAuxData(Queue queue, int[] parent, int[] base, boolean[] inBlossom, int[] match, boolean[] inQueue) { this.queue = queue; @@ -236,10 +236,10 @@ static class BlossomAuxData { * BlossomData class with reduced parameters. */ static class BlossomData { - BlossomAuxData auxData; // Use the auxiliary data class - int u; // One vertex in the edge - int v; // Another vertex in the edge - int lca; // Lowest Common Ancestor + final BlossomAuxData auxData; // Use the auxiliary data class + final int u; // One vertex in the edge + final int v; // Another vertex in the edge + final int lca; // Lowest Common Ancestor BlossomData(BlossomAuxData auxData, int u, int v, int lca) { this.auxData = auxData; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index e5e673a21794..d32356e973f7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -16,8 +16,8 @@ */ public class FloydWarshall { - private int[][] distanceMatrix; - private int numberofvertices; + private final int[][] distanceMatrix; + private final int numberofvertices; public static final int INFINITY = 999; /** diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java index b0970f36ddc5..b1f7ca2c1158 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java @@ -4,7 +4,7 @@ class AdjacencyListGraph> { - ArrayList vertices; + final ArrayList vertices; AdjacencyListGraph() { vertices = new ArrayList<>(); @@ -12,8 +12,8 @@ class AdjacencyListGraph> { private class Vertex { - E data; - ArrayList adjacentVertices; + final E data; + final ArrayList adjacentVertices; Vertex(E data) { adjacentVertices = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java index 351bd5b009e8..23fa51b81a89 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java @@ -7,17 +7,17 @@ /** * 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} + /** + * For more information, please visit Johnson's Algorithm */ public final class JohnsonsAlgorithm { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java index 9a97bc3f4808..eb7e353120c0 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java @@ -17,7 +17,7 @@ */ class AdjacencyList> { - Map> adj; + final Map> adj; /** * Constructor to initialize the adjacency list. @@ -71,7 +71,7 @@ Set getVertices() { */ class TopologicalSort> { - AdjacencyList graph; + final AdjacencyList graph; Map inDegree; /** diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index 331d7196b61c..e38b482e2431 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -27,9 +27,9 @@ public class Kruskal { */ static class Edge { - int from; - int to; - int weight; + final int from; + final int to; + final int weight; Edge(int from, int to, int weight) { this.from = from; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/UndirectedAdjacencyListGraph.java b/src/main/java/com/thealgorithms/datastructures/graphs/UndirectedAdjacencyListGraph.java index 8aafc1ef3368..ee1154cba8ac 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/UndirectedAdjacencyListGraph.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/UndirectedAdjacencyListGraph.java @@ -5,7 +5,7 @@ import java.util.HashSet; public class UndirectedAdjacencyListGraph { - private ArrayList> adjacencyList = new ArrayList<>(); + private final ArrayList> adjacencyList = new ArrayList<>(); /** * Adds a new node to the graph by adding an empty HashMap for its neighbors. diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 4bf21c7ed4c1..406994fd87f1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -1,8 +1,12 @@ package com.thealgorithms.datastructures.graphs; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.stream.IntStream; /** @@ -22,7 +26,6 @@ * For more information, see Graph Coloring. *

*/ -@SuppressWarnings({"rawtypes", "unchecked"}) public final class WelshPowell { private static final int BLANK_COLOR = -1; // Constant representing an uncolored state @@ -33,7 +36,7 @@ private WelshPowell() { * Represents a graph using an adjacency list. */ static final class Graph { - private final HashSet[] adjacencyLists; + private final List> adjacencyLists; /** * Initializes a graph with a specified number of vertices. @@ -46,25 +49,27 @@ private Graph(int vertices) { throw new IllegalArgumentException("Number of vertices cannot be negative"); } - adjacencyLists = new HashSet[vertices]; - Arrays.setAll(adjacencyLists, i -> new HashSet<>()); + adjacencyLists = new ArrayList<>(vertices); + for (int i = 0; i < vertices; i++) { + adjacencyLists.add(new HashSet<>()); + } } /** * Adds an edge between two vertices in the graph. * - * @param nodeA one end of the edge - * @param nodeB the other end of the edge + * @param vertexA one end of the edge + * @param vertexB the other end of the edge * @throws IllegalArgumentException if the vertices are out of bounds or if a self-loop is attempted */ - private void addEdge(int nodeA, int nodeB) { - validateVertex(nodeA); - validateVertex(nodeB); - if (nodeA == nodeB) { + private void addEdge(int vertexA, int vertexB) { + validateVertex(vertexA); + validateVertex(vertexB); + if (vertexA == vertexB) { throw new IllegalArgumentException("Self-loops are not allowed"); } - adjacencyLists[nodeA].add(nodeB); - adjacencyLists[nodeB].add(nodeA); + adjacencyLists.get(vertexA).add(vertexB); + adjacencyLists.get(vertexB).add(vertexA); } /** @@ -80,13 +85,14 @@ private void validateVertex(int vertex) { } /** - * Returns the adjacency list for a specific vertex. + * Returns the adjacency list for a specific vertex. The returned set is a read-only + * view: callers cannot mutate the graph's internal structure through it. * * @param vertex the index of the vertex * @return the set of adjacent vertices */ - HashSet getAdjacencyList(int vertex) { - return adjacencyLists[vertex]; + Set getAdjacencyList(int vertex) { + return Collections.unmodifiableSet(adjacencyLists.get(vertex)); } /** @@ -95,7 +101,7 @@ HashSet getAdjacencyList(int vertex) { * @return the number of vertices */ int getNumVertices() { - return adjacencyLists.length; + return adjacencyLists.size(); } } @@ -125,88 +131,96 @@ public static Graph makeGraph(int numberOfVertices, int[][] listOfEdges) { * @return an array of integers where each index represents a vertex and the value represents the color assigned */ public static int[] findColoring(Graph graph) { - int[] colors = initializeColors(graph.getNumVertices()); - Integer[] sortedVertices = getSortedNodes(graph); - for (int vertex : sortedVertices) { - if (isBlank(colors[vertex])) { - boolean[] usedColors = computeUsedColors(graph, vertex, colors); - final var newColor = firstUnusedColor(usedColors); - colors[vertex] = newColor; - Arrays.stream(sortedVertices).forEach(otherVertex -> { - if (isBlank(colors[otherVertex]) && !isAdjacentToColored(graph, otherVertex, colors)) { - colors[otherVertex] = newColor; - } - }); - } - } - return colors; + return new Coloring(graph).run(); } /** - * Helper method to check if a color is unassigned - * - * @param color the color to check - * @return {@code true} if the color is unassigned, {@code false} otherwise + * Bundles the graph being colored together with its in-progress color assignment. + * These two values were previously passed as a pair to nearly every helper method + * (a data clump); packaging them here lets each step read as an instance method + * with implicit access to shared state, instead of threading both through every call. */ - private static boolean isBlank(int color) { - return color == BLANK_COLOR; - } + private static final class Coloring { + private final Graph graph; + private final int[] colors; + + private Coloring(Graph graph) { + this.graph = graph; + this.colors = new int[graph.getNumVertices()]; + Arrays.fill(colors, BLANK_COLOR); + } - /** - * Checks if a vertex has adjacent colored vertices - * - * @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 - */ - private static boolean isAdjacentToColored(Graph graph, int vertex, int[] colors) { - return graph.getAdjacencyList(vertex).stream().anyMatch(otherVertex -> !isBlank(colors[otherVertex])); - } + private int[] run() { + Integer[] sortedVertices = getSortedVertices(); + for (int vertex : sortedVertices) { + if (isBlank(colors[vertex])) { + boolean[] usedColors = computeUsedColors(vertex); + int newColor = firstUnusedColor(usedColors); + colors[vertex] = newColor; + for (int otherVertex : sortedVertices) { + if (isBlank(colors[otherVertex]) && !isAdjacentToColored(otherVertex)) { + colors[otherVertex] = newColor; + } + } + } + } + return colors; + } - /** - * Initializes the colors array with blank color - * - * @param numberOfVertices the number of vertices in the graph - * @return an array of integers representing the colors assigned to the vertices - */ - private static int[] initializeColors(int numberOfVertices) { - int[] colors = new int[numberOfVertices]; - Arrays.fill(colors, BLANK_COLOR); - return colors; - } + /** + * Helper method to check if a color is unassigned + * + * @param color the color to check + * @return {@code true} if the color is unassigned, {@code false} otherwise + */ + private boolean isBlank(int color) { + return color == BLANK_COLOR; + } - /** - * Sorts the vertices by their degree in descending order - * - * @param graph the input graph - * @return an array of integers representing the vertices sorted by degree - */ - private static Integer[] getSortedNodes(final Graph graph) { - return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjacencyList(v).size())).toArray(Integer[] ::new); - } + /** + * Checks if a vertex has adjacent colored vertices + * + * @param vertex the vertex to check + * @return {@code true} if the vertex has adjacent colored vertices, {@code false} otherwise + */ + private boolean isAdjacentToColored(int vertex) { + return graph.getAdjacencyList(vertex).stream().anyMatch(neighbor -> !isBlank(colors[neighbor])); + } - /** - * Computes the colors already used by the adjacent vertices - * - * @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 - */ - private static boolean[] computeUsedColors(final Graph graph, final int vertex, final int[] colors) { - boolean[] usedColors = new boolean[graph.getNumVertices()]; - graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> !isBlank(color)).forEach(color -> usedColors[color] = true); - return usedColors; - } + /** + * Sorts the vertices by their degree in descending order + * + * @return an array of integers representing the vertices sorted by degree + */ + private Integer[] getSortedVertices() { + return IntStream.range(0, graph.getNumVertices()) + .boxed() + .sorted(Comparator.comparingInt(v -> graph.getAdjacencyList(v).size()).reversed()) + .toArray(Integer[] ::new); + } - /** - * Finds the first unused color - * - * @param usedColors the array of colors used by the adjacent vertices - * @return the first unused color - */ - private static int firstUnusedColor(boolean[] usedColors) { - return IntStream.range(0, usedColors.length).filter(color -> !usedColors[color]).findFirst().getAsInt(); + /** + * Computes the colors already used by the adjacent vertices + * + * @param vertex the vertex to check + * @return an array of booleans representing the colors used by the adjacent vertices + */ + private boolean[] computeUsedColors(int vertex) { + boolean[] usedColors = new boolean[graph.getNumVertices()]; + graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> !isBlank(color)).forEach(color -> usedColors[color] = true); + return usedColors; + } + + /** + * Finds the first unused color. + * + * @param usedColors the array of colors used by the adjacent vertices + * @return the first unused color + */ + private int firstUnusedColor(boolean[] usedColors) { + // Always present: a vertex has at most (numVertices - 1) neighbors, so at least + // one color in a numVertices-sized palette is guaranteed to remain unused. + return IntStream.range(0, usedColors.length).filter(color -> !usedColors[color]).findFirst().getAsInt(); + } } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java index 36d2cc8df160..2f9179fd078f 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java @@ -187,7 +187,7 @@ public boolean containsKey(K key) { * A private class representing a key-value pair (node) in the hash map. */ public class Node { - K key; + final K key; V value; /** diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java index 89e25f4eb0f7..9ede3c0cd507 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java @@ -171,7 +171,7 @@ public String toString() { * A private inner class representing a key-value pair (node) in the hash map. */ private class Node { - K key; + final K key; V val; /** diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java index 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/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java index 5760d39f1df7..ade05d4075e8 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java @@ -40,7 +40,7 @@ private Intersection() { /** * Computes the intersection of two integer arrays, preserving element frequency. * For example, given [1,2,2,3] and [2,2,4], the result will be [2,2]. - * + *

* Steps: * 1. Count the occurrences of each element in the first array using a map. * 2. Iterate over the second array and collect common elements. diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index 834de9c77881..79c6ad75c28a 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -196,8 +196,7 @@ public void delete(HeapNode x) { * @pre heap contains x */ private void decreaseKey(HeapNode x, int delta) { - int newKey = x.getKey() - delta; - x.key = newKey; + x.key = x.getKey() - delta; if (x.isRoot()) { // no parent to x this.updateMin(x); return; diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java index ad7229760fd0..5a1db5b14971 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java @@ -5,7 +5,7 @@ import java.util.IdentityHashMap; import java.util.Objects; import java.util.function.Consumer; - +import java.util.HashMap; /** * An addressable (indexed) min-priority queue with O(log n) updates. * diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java index 7ad92e8ba3c1..5e34a141fe50 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java @@ -17,7 +17,7 @@ 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. * @@ -33,13 +33,13 @@ public static int findKthLargest(int[] nums, int k) { minHeap.poll(); } } - return minHeap.peek(); + return minHeap.element(); } /** * 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. * @@ -55,6 +55,6 @@ public static int findKthSmallest(int[] nums, int k) { maxHeap.poll(); } } - return maxHeap.peek(); + return maxHeap.element(); } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 5b4b29cf1c2d..ffac21e8ec6f 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -7,12 +7,12 @@ * A Max Heap implementation where each node's key is higher 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 maximum element. - * + *

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

* Example usage: *

  * List elements = Arrays.asList(
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java
index 4e74aaec4a10..d5dae3e51eb9 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java
@@ -1,5 +1,6 @@
 package com.thealgorithms.datastructures.heaps;
 
+import java.util.NoSuchElementException;
 import java.util.PriorityQueue;
 
 /**
@@ -7,21 +8,22 @@
  * 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 */ public final class MedianFinder { + MedianFinder() { } - private PriorityQueue minHeap = new PriorityQueue<>(); - private PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); + private final PriorityQueue minHeap = new PriorityQueue<>(); + private final PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); /** * Adds a new number to the data stream. The number is placed in the appropriate @@ -29,8 +31,10 @@ public final class MedianFinder { * * @param num the number to be added to the data stream */ - public void addNum(int num) { - if (maxHeap.isEmpty() || num <= maxHeap.peek()) { + public void addNum(final int num) { + // element() throws NoSuchElementException instead of returning null, + // so the null-peek warning is eliminated entirely. + if (maxHeap.isEmpty() || num <= maxHeap.element()) { maxHeap.offer(num); } else { minHeap.offer(num); @@ -49,11 +53,15 @@ public void addNum(int num) { * median is the middle element from the max-heap. * * @return the median of the numbers in the data stream + * @throws NoSuchElementException if no numbers have been added yet */ public double findMedian() { + if (maxHeap.isEmpty()) { + throw new NoSuchElementException("Median is undefined for an empty data stream"); + } if (maxHeap.size() == minHeap.size()) { - return (maxHeap.peek() + minHeap.peek()) / 2.0; + return (maxHeap.element() + minHeap.element()) / 2.0; } - return maxHeap.peek(); + return maxHeap.element(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java b/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java index e41711f05914..de485307afa2 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 diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index 3a4822142b5f..3ab849aee953 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -7,12 +7,12 @@ * 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( diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java index 72a12cd58401..858623b767b6 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java @@ -3,14 +3,11 @@ /** * This class is a circular singly linked list implementation. In a circular linked list, * the last node points back to the first node, creating a circular chain. - * *

This implementation includes basic operations such as appending elements * to the end, removing elements from a specified position, and converting * the list to a string representation. - * * @param the type of elements held in this list */ -@SuppressWarnings("rawtypes") public class CircleLinkedList { /** @@ -21,7 +18,7 @@ public class CircleLinkedList { static final class Node { Node next; - E value; + final E value; private Node(E value, Node next) { this.value = value; @@ -120,7 +117,6 @@ public E remove(int pos) { if (destroy == tail) { tail = before; } - destroy = null; size--; return saved; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java index fbb48854c449..c825528aadaf 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java @@ -6,7 +6,7 @@ * the last node points back to the first node and the first node points back to * the last node, * creating a circular chain in both directions. - * + *

* This implementation includes basic operations such as appending elements to * the end, * removing elements from a specified position, and converting the list to a @@ -18,7 +18,7 @@ public class CircularDoublyLinkedList { static final class Node { Node next; Node prev; - E value; + final E value; private Node(E value, Node next, Node prev) { this.value = value; @@ -28,7 +28,7 @@ private Node(E value, Node next, Node prev) { } private int size; - Node head = null; + Node head; /** * Initializes a new circular doubly linked list. A dummy head node is used for diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java index 3902d08bfd14..da3abcb183dd 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java @@ -20,7 +20,7 @@ private CreateAndDetectLoop() { * data and a reference to the next node. */ static final class Node { - int data; + final int data; Node next; Node(int data) { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 58898ddc0fcf..affab2a4915e 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -95,7 +95,7 @@ class Link { /** * Value of node */ - public int value; + public final int value; /** * This points to the link in front of the new link */ @@ -293,7 +293,6 @@ public Link deleteTail() { * Delete the element from somewhere in the list * * @param x element to be deleted - * @return Link deleted */ public void delete(int x) { Link current = head; @@ -379,10 +378,9 @@ public void removeDuplicates(DoublyLinkedList l) { public void reverse() { // Keep references to the head and tail Link thisHead = this.head; - Link thisTail = this.tail; // Flip the head and tail references - this.head = thisTail; + this.head = this.tail; this.tail = thisHead; // While the link we're visiting is not null, flip the @@ -390,8 +388,7 @@ public void reverse() { Link nextLink = thisHead; while (nextLink != null) { Link nextLinkNext = nextLink.next; - Link nextLinkPrevious = nextLink.previous; - nextLink.next = nextLinkPrevious; + nextLink.next = nextLink.previous; nextLink.previous = nextLinkNext; // Now, we want to go to the next link diff --git a/src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java index 3c4106f178b9..6264815ffad3 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java @@ -1,12 +1,12 @@ package com.thealgorithms.datastructures.lists; /** * Implements an algorithm to flatten a multilevel linked list. - * + *

* In this specific problem structure, each node has a `next` pointer (to the * next node at the same level) and a `child` pointer (which points to the head * of another sorted linked list). The goal is to merge all these lists into a * single, vertically sorted linked list using the `child` pointer. - * + *

* The approach is a recursive one that leverages a merge utility, similar to * the merge step in Merge Sort. It recursively flattens the list starting from * the rightmost node and merges each node's child list with the already @@ -25,7 +25,7 @@ private FlattenMultilevelLinkedList() { * reference to the head of a child list. */ static class Node { - int data; + final int data; Node next; Node child; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java index 0f5c50530d92..983d57c73381 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java @@ -23,7 +23,7 @@ * *

This class is designed to handle nodes of integer linked lists and can be expanded for additional data types if needed.

* - * @author Arun Pandey (https://github.com/pandeyarun709) + * @author Arun Pandey (...) */ public class MergeKSortedLinkedList { @@ -78,7 +78,7 @@ Node mergeKList(Node[] a, int n) { * Represents a node in the linked list. */ static class Node { - int data; + final int data; Node next; Node(int data) { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java index 09eb854c8dc2..effcc840d6ef 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java @@ -24,7 +24,7 @@ * *

This implementation assumes the input lists are already sorted in ascending order.

* - * @author https://github.com/shellhub + * @author ... * @see List */ public final class MergeSortedArrayList { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MiddleOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MiddleOfLinkedList.java index 0ee788db2ff9..a4c6bd26c026 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MiddleOfLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MiddleOfLinkedList.java @@ -9,7 +9,7 @@ * *

This method does not modify the input list.

* - *

Reference: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare

+ *

Reference: ...'s_tortoise_and_hare

* *

Complexity:

*
    diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java index dac88dd9f241..1d3a2c056f24 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java @@ -35,7 +35,7 @@ public class RandomNode { static class ListNode { - int val; + final int val; ListNode next; ListNode(int val) { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java index 9b9464d388b5..51043229107a 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java @@ -28,7 +28,7 @@ *
*

* - * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * Author: Bama Charan Chhandogi (...) */ public class ReverseKGroup { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java b/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java index 47ee5397097c..d672f3011964 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java @@ -27,7 +27,7 @@ * *

* - * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * Author: Bama Charan Chhandogi (...) */ public class RotateSinglyLinkedLists { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java index ff4af4437cc7..f4062f933514 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java @@ -263,7 +263,6 @@ public void deleteDuplicates() { } // skip all duplicates pred.next = newHead.next; - newHead = null; // otherwise, move predecessor } // move forward diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java index e515c9e4adc4..38b0ce70accf 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java @@ -12,7 +12,7 @@ *

*

* Further information can be found here: - * https://runestone.academy/ns/books/published/cppds/LinearLinked/ImplementinganOrderedList.html + * ... *

* * Usage Example: diff --git a/src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java b/src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java index 9d803003c658..a423ce6884bf 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java @@ -3,7 +3,7 @@ public class TortoiseHareAlgo { static final class Node { Node next; - E value; + final E value; private Node(E value, Node next) { this.value = value; @@ -11,7 +11,7 @@ private Node(E value, Node next) { } } - private Node head = null; + private Node head; public TortoiseHareAlgo() { head = null; diff --git a/src/main/java/com/thealgorithms/datastructures/queues/Deque.java b/src/main/java/com/thealgorithms/datastructures/queues/Deque.java index 4cfa2b442ca0..a4e4e0fc2272 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/Deque.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/Deque.java @@ -17,7 +17,7 @@ public class Deque { * Node for the deque */ private static class DequeNode { - S val; + final S val; DequeNode next = null; DequeNode prev = null; @@ -59,12 +59,11 @@ public void addLast(T val) { DequeNode newNode = new DequeNode<>(val); if (tail == null) { head = newNode; - tail = newNode; } else { newNode.prev = tail; tail.next = newNode; - tail = newNode; } + tail = newNode; size++; } @@ -196,7 +195,7 @@ public static void main(String[] args) { int dequeSize = myDeque.size(); for (int i = 0; i < dequeSize; i++) { - int removing = -1; + int removing; if (i / 39.0 < 0.5) { removing = myDeque.pollFirst(); } else { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java index 6ba16199dbb8..3168a6f45b61 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java @@ -9,7 +9,7 @@ public class LinkedQueue implements Iterable { * Node class representing each element in the queue. */ private static class Node { - T data; + final T data; Node next; Node(T data) { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java index b877a5843b98..19df6ffc278a 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -9,18 +9,18 @@ * give numbers that are bigger, a higher priority. Queues in theory have no * fixed size but when using an array implementation it does. *

- * Additional contributions made by: PuneetTri(https://github.com/PuneetTri) + * Additional contributions made by: PuneetTri(...) */ class PriorityQueue { /** * The max size of the queue */ - private int maxSize; + private final int maxSize; /** * The array for the queue */ - private int[] queueArray; + private final int[] queueArray; /** * How many items are in the queue */ 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/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/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java index bbcdfe1cc2a8..66c68f0b09e0 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java @@ -17,7 +17,7 @@ public class NodeStack { * Node class representing each element in the stack. */ private class Node { - Item data; + final Item data; Node previous; Node(Item data) { diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index d87f5f4ea86a..320f5dc938ee 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -54,7 +54,7 @@ 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. diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java index c12097dfa28c..4cb3889c66c5 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java @@ -17,7 +17,7 @@ private StackOfLinkedList() { // A node class for the linked list class Node { - public int data; + public final int data; public Node next; Node(int data) { @@ -78,7 +78,7 @@ public int pop() { Node destroy = head; head = head.next; int retValue = destroy.data; - destroy = null; // Help garbage collection + // Help garbage collection size--; return retValue; } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java index 07fc5c87b6c4..ba87106f0ca1 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java @@ -30,7 +30,7 @@ public class AVLSimple { private class Node { - int data; + final int data; int height; Node left; Node right; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java index 77ee5d5fa23e..27509ee1a16b 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java @@ -77,7 +77,7 @@ public void delete(int delKey) { } // Find the node to be deleted - Node node = root; + Node node; Node child = root; while (child != null) { node = child; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java index 1962eaa0a106..a130ee019fff 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 diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java index 2c94224ddeb4..0538474a5404 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java @@ -8,7 +8,6 @@ * *

* A recursive implementation of generic type BST. - * * Reference: Wiki links for BST *

* @@ -58,8 +57,7 @@ private void prettyDisplay(Node node, int level) { public static void main(String[] args) { System.out.println("Testing for integer data..."); // Integer - BSTRecursiveGeneric integerTree = new BSTRecursiveGeneric(); - + BSTRecursiveGeneric integerTree = new BSTRecursiveGeneric<>(); integerTree.add(5); integerTree.add(10); integerTree.add(-9); @@ -94,7 +92,20 @@ public static void main(String[] args) { System.out.println(); System.out.println("Testing for string data..."); // String - BSTRecursiveGeneric stringTree = new BSTRecursiveGeneric(); + BSTRecursiveGeneric stringTree = getStringBSTRecursiveGeneric(); + System.out.println("Pretty Display of current tree is:"); + stringTree.prettyDisplay(); + /* + Will print in following order + banana hills India pineapple + */ + stringTree.inorder(); + System.out.println("Pretty Display of current tree is:"); + stringTree.prettyDisplay(); + } + + private static BSTRecursiveGeneric getStringBSTRecursiveGeneric() { + BSTRecursiveGeneric stringTree = new BSTRecursiveGeneric<>(); stringTree.add("banana"); stringTree.add("apple"); @@ -110,19 +121,11 @@ public static void main(String[] args) { stringTree.remove("boy"); assert !stringTree.find("boy") : "Since boy was not present so deleting would do no change"; - stringTree.add("india"); + stringTree.add("India"); stringTree.add("hills"); assert stringTree.find("hills") : "hills was inserted but not found"; - System.out.println("Pretty Display of current tree is:"); - stringTree.prettyDisplay(); - /* - Will print in following order - banana hills india pineapple - */ - stringTree.inorder(); - System.out.println("Pretty Display of current tree is:"); - stringTree.prettyDisplay(); + return stringTree; } /** @@ -184,7 +187,6 @@ private Node insert(Node node, T data) { /** * Recursively print Preorder traversal of the BST - * * @param node the root node */ private void preOrder(Node node) { @@ -241,7 +243,7 @@ private void inOrder(Node node) { * elements to argument list. * * @param node the root node - * @param sortedList the list to add the srted elements into + * @param sortedList the list to add the sorted elements into */ private void inOrderSort(Node node, List sortedList) { if (node == null) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BTree.java index 2c19253b45e7..9ea8cbb28e9c 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BTree.java @@ -2,23 +2,18 @@ import java.util.ArrayList; -/** - * Implementation of a B-Tree, a self-balancing tree data structure that maintains sorted data - * and allows searches, sequential access, insertions, and deletions in logarithmic time. - * - * B-Trees are generalizations of binary search trees in that a node can have more than two children. - * They're widely used in databases and file systems. - * - * For more information: https://en.wikipedia.org/wiki/B-tree - */ - +/// Implementation of a B-Tree, a self-balancing tree data structure that maintains sorted data +/// and allows searches, sequential access, insertions, and deletions in logarithmic time. +/// B-Trees are generalizations of binary search trees in that a node can have more than two children. +/// They're widely used in databases and file systems. +/// For more information: [...](https://en.wikipedia.org/wiki/B-tree) public class BTree { static class BTreeNode { - int[] keys; - int t; // Minimum degree (defines range for number of keys) - BTreeNode[] children; + final int[] keys; + final int t; // Minimum degree (defines range for number of keys) + final BTreeNode[] children; int n; // Current number of keys - boolean leaf; + final boolean leaf; BTreeNode(int t, boolean leaf) { this.t = t; @@ -245,14 +240,10 @@ private void merge(int idx) { child.keys[t - 1] = keys[idx]; - for (int i = 0; i < sibling.n; ++i) { - child.keys[i + t] = sibling.keys[i]; - } + if (sibling.n >= 0) System.arraycopy(sibling.keys, 0, child.keys, 0 + t, sibling.n); if (!child.leaf) { - for (int i = 0; i <= sibling.n; ++i) { - child.children[i + t] = sibling.children[i]; - } + if (sibling.n + 1 >= 0) System.arraycopy(sibling.children, 0, child.children, 0 + t, sibling.n + 1); } for (int i = idx + 1; i < n; ++i) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java index 2f9b3b489d56..e170bd518adf 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java @@ -2,8 +2,8 @@ /** * Leetcode 606: Construct String from Binary Tree: - * https://leetcode.com/problems/construct-string-from-binary-tree/ - * + * ... + *

* Utility class to convert a {@link BinaryTree} into its string representation. *

* The conversion follows a preorder traversal pattern (root → left → right) diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java index fff84111663b..28adb5fa1fca 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 auxiliary diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java b/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java index 0b29dd6f5f5e..1f39b8cd1358 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java @@ -37,7 +37,7 @@ public static final class CentroidTree { private final int[] parent; private final int[] subtreeSize; private final boolean[] removed; - private int root; + private final int root; /** * Constructs a centroid tree from an adjacency list. diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java index 17d84bf11d54..4f74c18683cd 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java @@ -11,7 +11,7 @@ * 2 2 * / \ / \ * 3 4 4 3 - * + *

* Below is not symmetric because values is different in last level * 1 * / \ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java index 5378a01f6642..2b545721c5de 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java @@ -2,8 +2,8 @@ public class FenwickTree { - private int n; - private int[] fenTree; + private final int n; + private final int[] fenTree; /* Constructor which takes the size of the array as a parameter */ public FenwickTree(int n) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java index 7d969a59def0..b644b51aa2fd 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java @@ -19,7 +19,7 @@ public class GenericTree { private static final class Node { int data; - ArrayList child = new ArrayList<>(); + final ArrayList child = new ArrayList<>(); } private final Node root; @@ -224,14 +224,15 @@ public void removeleavescall() { private void removeleaves(Node node) { ArrayList arr = new ArrayList<>(); for (int i = 0; i < node.child.size(); i++) { - if (node.child.get(i).child.size() == 0) { + if (node.child.get(i).child.isEmpty()) { arr.add(i); } else { removeleaves(node.child.get(i)); } } for (int i = arr.size() - 1; i >= 0; i--) { - node.child.remove(arr.get(i) + 0); + int indexToRemove = arr.get(i); // Automatically unboxes Integer to int + node.child.remove(indexToRemove); // Safely calls remove(int index) } } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/HeavyLightDecomposition.java b/src/main/java/com/thealgorithms/datastructures/trees/HeavyLightDecomposition.java index ed67f9ae3394..b4c3df96740e 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/HeavyLightDecomposition.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/HeavyLightDecomposition.java @@ -8,20 +8,20 @@ * HLD is used to efficiently handle path queries on trees, such as maximum, * sum, or updates. It decomposes the tree into heavy and light chains, * enabling queries in O(log N) time. - * Wikipedia Reference: https://en.wikipedia.org/wiki/Heavy-light_decomposition + * Wikipedia Reference: ... * Author: Nithin U. - * Github: https://github.com/NithinU2802 + * Github: ... */ public class HeavyLightDecomposition { - private List> tree; - private int[] parent; - private int[] depth; - private int[] subtreeSize; - private int[] chainHead; - private int[] position; - private int[] nodeValue; - private int[] segmentTree; + private final List> tree; + private final int[] parent; + private final int[] depth; + private final int[] subtreeSize; + private final int[] chainHead; + private final int[] position; + private final int[] nodeValue; + private final int[] segmentTree; private int positionIndex; public HeavyLightDecomposition(int n) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java index 5a001ff9ab9f..f238047b6d37 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java @@ -8,10 +8,10 @@ /** * 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: diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index 5190e82f74ef..1c6f697fd7e1 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -68,7 +68,7 @@ public class KDTree { static class Point { - int[] coordinates; + final int[] coordinates; public int getCoordinate(int i) { return coordinates[i]; @@ -142,7 +142,7 @@ public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { static class Node { private Point point; - private int axis; // 0 for x, 1 for y, 2 for z, etc. + private final int axis; // 0 for x, 1 for y, 2 for z, etc. private Node left = null; // Left child private Node right = null; // Right child diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java index 3aceac4d1852..46f82a233a11 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java @@ -8,10 +8,10 @@ /** * 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: diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java index 3ef664f3fa7d..e2d51e892d15 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java @@ -9,7 +9,7 @@ class TreeNode { // Members - int key; + final int key; TreeNode left; TreeNode right; @@ -26,8 +26,8 @@ class TreeNode { // distance of node from root class QItem { - TreeNode node; - int hd; + final TreeNode node; + final int hd; QItem(TreeNode n, int h) { node = n; @@ -38,7 +38,7 @@ class QItem { // Class for a Binary Tree class Tree { - TreeNode root; + final TreeNode root; // Constructors Tree() { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java index e0d255b1e784..e55d4e238243 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java @@ -10,8 +10,8 @@ * @author Sailok Chinta */ class Point { - public double x; - public double y; + public final double x; + public final double y; Point(double x, double y) { this.x = x; @@ -26,8 +26,8 @@ class Point { * @author Sailok Chinta */ class BoundingBox { - public Point center; - public double halfWidth; + public final Point center; + public final double halfWidth; BoundingBox(Point center, double halfWidth) { this.center = center; @@ -59,7 +59,7 @@ 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 @@ -69,7 +69,7 @@ public class QuadTree { private final BoundingBox boundary; private final int capacity; - private List pointList; + private final List pointList; private boolean divided; private QuadTree northWest; private QuadTree northEast; @@ -128,11 +128,7 @@ public boolean insert(Point point) { return true; } - if (southEast.insert(point)) { - return true; - } - - return false; + return southEast.insert(point); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java index 01222b739ff0..60acf01d2b76 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java @@ -12,7 +12,7 @@ public class RedBlackBST { private class Node { - int key = -1; + int key; int color = BLACK; Node left = nil; Node right = nil; @@ -95,7 +95,7 @@ private void insert(Node node) { private void fixTree(Node node) { while (node.p.color == RED) { - Node y = nil; + Node y; if (node.p == node.p.p.left) { y = node.p.p.right; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java index cff27c12f1ca..fff2b9c53a4a 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java @@ -52,12 +52,12 @@ public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { BinaryTree.Node second = q2.poll(); // check that some node can be null // if the check is true: both nodes are null or both nodes are not null - if (!equalNodes(first, second)) { + if (equalNodes(first, second)) { return false; } if (first != null) { - if (!equalNodes(first.left, second.left)) { + if (equalNodes(first.left, second.left)) { return false; } if (first.left != null) { @@ -65,7 +65,7 @@ public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { q2.add(second.left); } - if (!equalNodes(first.right, second.right)) { + if (equalNodes(first.right, second.right)) { return false; } if (first.right != null) { @@ -79,11 +79,11 @@ public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { private static boolean equalNodes(BinaryTree.Node p, BinaryTree.Node q) { if (p == null && q == null) { - return true; + return false; } if (p == null || q == null) { - return false; + return true; } - return p.data == q.data; + return p.data != q.data; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java index 57b3edc163ca..121fcac6da29 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java @@ -2,9 +2,9 @@ public class SegmentTree { - private int[] segTree; + private final int[] segTree; private int n; - private int[] arr; + private final int[] arr; /* Constructor which takes the size of the array and the array as a parameter*/ public SegmentTree(int n, int[] arr) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree2D.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree2D.java index 40b9e8a73533..428ee150debc 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree2D.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree2D.java @@ -4,7 +4,7 @@ * 2D Segment Tree (Tree of Trees) implementation. * This data structure supports point updates and submatrix sum queries * in a 2D grid. It achieves this by nesting 1D Segment Trees within a 1D Segment Tree. - * + *

* Time Complexity: * - Build/Initialization: O(N * M) * - Point Update: O(log N * log M) diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java index 2668b609aedc..585f18068887 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java @@ -1,33 +1,22 @@ package com.thealgorithms.datastructures.trees; +import java.io.Serial; import java.util.LinkedList; import java.util.List; /** * Implementation of a Splay Tree data structure. - * - * A splay tree is a self-adjusting binary search tree with the additional - * property + *

+ * 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. + * operations such as insertion, deletion, and searching in O(log n) amortized time. */ public class SplayTree { - public static final TreeTraversal PRE_ORDER = new PreOrderTraversal(); - public static final TreeTraversal IN_ORDER = new InOrderTraversal(); - public static final TreeTraversal POST_ORDER = new PostOrderTraversal(); + + // Preserved public API constants + public static final TreeTraversal PRE_ORDER = TraversalStrategy.PRE_ORDER; + public static final TreeTraversal IN_ORDER = TraversalStrategy.IN_ORDER; + public static final TreeTraversal POST_ORDER = TraversalStrategy.POST_ORDER; private Node root; @@ -57,15 +46,18 @@ public void insert(final int key) { * @return True if the key is found, otherwise false. */ public boolean search(int key) { + if (isEmpty()) { + return false; + } root = splay(root, key); - return root != null && root.key == key; + return root.key == key; } /** * Deletes a key from the SplayTree. * * @param key The key to delete. - * @throws IllegalArgumentException If the tree is empty. + * @throws EmptyTreeException If the tree is empty. */ public void delete(final int key) { if (isEmpty()) { @@ -81,9 +73,9 @@ public void delete(final int key) { if (root.left == null) { root = root.right; } else { - Node temp = root; + Node rightSubtree = root.right; root = splay(root.left, findMax(root.left).key); - root.right = temp.right; + root.right = rightSubtree; } } @@ -95,171 +87,96 @@ public void delete(final int key) { */ public List traverse(TreeTraversal traversal) { List result = new LinkedList<>(); - traversal.traverse(root, result); + // Safely delegate to the internal enum strategy, hiding Node exposure + if (traversal instanceof TraversalStrategy strategy) { + strategy.execute(root, result); + } return result; } - /** - * Finds the node with the maximum key in a given subtree. - * - *

- * This method traverses the right children of the subtree until it finds the - * rightmost node, which contains the maximum key. - *

- * - * @param root The root node of the subtree. - * @return The node with the maximum key in the subtree. - */ - private Node findMax(Node root) { - while (root.right != null) { - root = root.right; + private Node findMax(Node node) { + while (node.right != null) { + node = node.right; } - return root; + return node; } /** - * Zig operation. - * - *

- * The zig operation is used to perform a single rotation on a node to move it - * closer to - * the root of the tree. It is typically applied when the node is a left child - * of its parent - * and needs to be rotated to the right. - *

- * - * @param x The node to perform the zig operation on. - * @return The new root node after the operation. + * Zig operation (Right Rotation). */ - private Node rotateRight(Node x) { - Node y = x.left; - x.left = y.right; - y.right = x; - return y; + private Node rotateRight(Node node) { + Node leftChild = node.left; + node.left = leftChild.right; + leftChild.right = node; + return leftChild; } /** - * Zag operation. - * - *

- * The zag operation is used to perform a single rotation on a node to move it - * closer to - * the root of the tree. It is typically applied when the node is a right child - * of its parent - * and needs to be rotated to the left. - *

- * - * @param x The node to perform the zag operation on. - * @return The new root node after the operation. + * Zag operation (Left Rotation). */ - private Node rotateLeft(Node x) { - Node y = x.right; - x.right = y.left; - y.left = x; - return y; + private Node rotateLeft(Node node) { + Node rightChild = node.right; + node.right = rightChild.left; + rightChild.left = node; + return rightChild; } /** - * Splay operation. - * - *

- * The splay operation is the core operation of a splay tree. It moves a - * specified node - * closer to the root of the tree by performing a series of rotations. The goal - * of the splay - * operation is to improve the access time for frequently accessed nodes by - * bringing them - * closer to the root. - *

- * - *

- * The splay operation consists of three main cases: - *

    - *
  • Zig-Zig case: Perform two consecutive rotations.
  • - *
  • Zig-Zag case: Perform two consecutive rotations in opposite - * directions.
  • - *
  • Zag-Zag case: Perform two consecutive rotations.
  • - *
- *

- * - *

- * After performing the splay operation, the accessed node becomes the new root - * of the tree. - *

- * - * @param root The root of the subtree to splay. - * @param key The key to splay around. - * @return The new root of the splayed subtree. + * Splay operation. Moves the accessed node to the root. */ - private Node splay(Node root, final int key) { - if (root == null || root.key == key) { - return root; + private Node splay(Node node, final int key) { + if (node == null || node.key == key) { + return node; } - if (root.key > key) { - if (root.left == null) { - return root; + if (node.key > key) { + if (node.left == null) { + return node; } - // Zig-Zig case - if (root.left.key > key) { - root.left.left = splay(root.left.left, key); - root = rotateRight(root); - } else if (root.left.key < key) { - root.left.right = splay(root.left.right, key); - if (root.left.right != null) { - root.left = rotateLeft(root.left); + if (node.left.key > key) { + node.left.left = splay(node.left.left, key); + node = rotateRight(node); + } else if (node.left.key < key) { + node.left.right = splay(node.left.right, key); + if (node.left.right != null) { + node.left = rotateLeft(node.left); } } - return (root.left == null) ? root : rotateRight(root); + return (node.left == null) ? node : rotateRight(node); } else { - if (root.right == null) { - return root; + if (node.right == null) { + return node; } - // Zag-Zag case - if (root.right.key > key) { - root.right.left = splay(root.right.left, key); - if (root.right.left != null) { - root.right = rotateRight(root.right); + if (node.right.key > key) { + node.right.left = splay(node.right.left, key); + if (node.right.left != null) { + node.right = rotateRight(node.right); } - } else if (root.right.key < key) { - root.right.right = splay(root.right.right, key); - root = rotateLeft(root); + } else if (node.right.key < key) { + node.right.right = splay(node.right.right, key); + node = rotateLeft(node); } - return (root.right == null) ? root : rotateLeft(root); + return (node.right == null) ? node : rotateLeft(node); } } - private Node insertRec(Node root, final int key) { - if (root == null) { + private Node insertRec(Node node, final int key) { + if (node == null) { return new Node(key); } - if (key < root.key) { - root.left = insertRec(root.left, key); - } else if (key > root.key) { - root.right = insertRec(root.right, key); + if (key < node.key) { + node.left = insertRec(node.left, key); + } else if (key > node.key) { + node.right = insertRec(node.right, key); } else { throw new DuplicateKeyException("Duplicate key: " + key); } - return root; - } - - public static class EmptyTreeException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public EmptyTreeException(String message) { - super(message); - } + return node; } - public static class DuplicateKeyException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public DuplicateKeyException(String message) { - super(message); - } - } + // --- Inner Classes and Interfaces --- private static class Node { final int key; @@ -268,57 +185,73 @@ private static class Node { Node(int key) { this.key = key; - left = null; - right = null; } } + /** + * Public interface acting as a type token for traversals. + * No longer exposes internal Node architecture to the public API. + */ public interface TreeTraversal { - /** - * Recursive function for a specific order traversal. - * - * @param root The root of the subtree to traverse. - * @param result The list to store the traversal result. - */ - void traverse(Node root, List result); + // Marker interface to preserve public API footprint } - private static final class InOrderTraversal implements TreeTraversal { - private InOrderTraversal() { - } - - public void traverse(Node root, List result) { - if (root != null) { - traverse(root.left, result); - result.add(root.key); - traverse(root.right, result); + /** + * Private internal implementation of the traversal strategies. + * This keeps the 'Node' references completely encapsulated within SplayTree. + */ + private enum TraversalStrategy implements TreeTraversal { + PRE_ORDER { + @Override + void execute(Node root, List result) { + if (root != null) { + result.add(root.key); + execute(root.left, result); + execute(root.right, result); + } } - } + }, + IN_ORDER { + @Override + void execute(Node root, List result) { + if (root != null) { + execute(root.left, result); + result.add(root.key); + execute(root.right, result); + } + } + }, + POST_ORDER { + @Override + void execute(Node root, List result) { + if (root != null) { + execute(root.left, result); + execute(root.right, result); + result.add(root.key); + } + } + }; + + abstract void execute(Node root, List result); } - private static final class PreOrderTraversal implements TreeTraversal { - private PreOrderTraversal() { - } + // --- Custom Exceptions --- - public void traverse(Node root, List result) { - if (root != null) { - result.add(root.key); - traverse(root.left, result); - traverse(root.right, result); - } + public static class EmptyTreeException extends RuntimeException { + @Serial + private static final long serialVersionUID = 1L; + + public EmptyTreeException(String message) { + super(message); } } - private static final class PostOrderTraversal implements TreeTraversal { - private PostOrderTraversal() { - } + public static class DuplicateKeyException extends RuntimeException { + @Serial + private static final long serialVersionUID = 1L; - public void traverse(Node root, List result) { - if (root != null) { - traverse(root.left, result); - traverse(root.right, result); - result.add(root.key); - } + public DuplicateKeyException(String message) { + super(message); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java index fd8876cecb70..878bb6565b40 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java @@ -25,7 +25,7 @@ public final class ThreadedBinaryTree { private Node root; private static final class Node { - int value; + final int value; Node left; Node right; boolean leftIsThread; @@ -58,7 +58,7 @@ public void insert(int value) { } Node current = root; - Node parent = null; + Node parent; while (true) { parent = current; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/Treap.java b/src/main/java/com/thealgorithms/datastructures/trees/Treap.java index 1e5d551cc40b..5f0a0f2929ab 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/Treap.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/Treap.java @@ -15,21 +15,21 @@ 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 */ - public int value; - private int priority; + public final int value; + private final int priority; private int size; public TreapNode left; public TreapNode right; @@ -61,11 +61,11 @@ private void updateSize() { * random -> to generate random priority for the nodes in the Treap */ private TreapNode root; - private Random random = new Random(); + private final Random random = new Random(); /** * Constructors - * + *

* Treap() -> create an empty Treap * Treap(int[] nodeValues) -> add the elements given in the array to the Treap */ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java index cf56731fb079..7b35a8c68238 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java @@ -34,9 +34,9 @@ private final class Node { } // Using an arraylist to store the inorder traversal of the given binary tree - static ArrayList list = new ArrayList<>(); + static final ArrayList list = new ArrayList<>(); // root of Tree - Node root; + final Node root; TreeRandomNode() { root = null; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/Trie.java b/src/main/java/com/thealgorithms/datastructures/trees/Trie.java index 02f28d4d83ad..de947ffa4f7d 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/Trie.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/Trie.java @@ -8,8 +8,8 @@ * Each node also has a boolean value to indicate if it is the end of a word. */ class TrieNode { - char value; - HashMap child; + final char value; + final HashMap child; boolean end; /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieAutocomplete.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieAutocomplete.java index 624e3d65bfc1..101f42a09352 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TrieAutocomplete.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieAutocomplete.java @@ -10,7 +10,7 @@ class TrieAutocomplete { // Trie node static class TrieNode { - TrieNode[] children = new TrieNode[ALPHABET_SIZE]; + final TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isWordEnd is true if the node represents // end of a word @@ -137,8 +137,7 @@ static int printAutoSuggestions(TrieNode root, final String query) { // If there are nodes below the last // matching character. if (!isLast) { - String prefix = query; - suggestionsRec(pCrawl, prefix); + suggestionsRec(pCrawl, query); return 1; } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java index c1d15390d4b9..97064a51874f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java @@ -3,94 +3,73 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.Queue; -/* The following class implements a vertical order traversal -in a tree from top to bottom and left to right, so for a tree : - 1 - / \ - 2 3 - / \ \ - 4 5 6 - \ / \ - 7 8 10 - \ - 9 - the sequence will be : - 4 2 7 1 5 9 3 8 6 10 +/** + * Implements a vertical order traversal in a tree from top to bottom + * and left to right. */ public final class VerticalOrderTraversal { + private VerticalOrderTraversal() { } - /*Function that receives a root Node and prints the tree - in Vertical Order.*/ - public static ArrayList verticalTraversal(BinaryTree.Node root) { + /** + * Modern Java Record to encapsulate a node and its vertical column index. + * This replaces the bulky inner class and parallel queues. + */ + private record NodeColumnPair(BinaryTree.Node node, int column) {} + + /** + * Prints the tree in Vertical Order. + * Note: Visibility changed to package-private to match BinaryTree.Node. + * * @param root The root node of the binary tree. + * @return An ArrayList containing the vertical traversal order. + */ + static ArrayList verticalTraversal(BinaryTree.Node root) { if (root == null) { return new ArrayList<>(); } - /*Queue to store the Nodes.*/ - Queue queue = new LinkedList<>(); - - /*Queue to store the index of particular vertical - column of a tree , with root at 0, Nodes on left - with negative index and Nodes on right with positive - index. */ - Queue index = new LinkedList<>(); + Queue queue = new LinkedList<>(); + Map> columnMap = new HashMap<>(); - /*Map of Integer and ArrayList to store all the - elements in a particular index in a single arrayList - that will have a key equal to the index itself. */ - Map> map = new HashMap<>(); + int minColumn = 0; + int maxColumn = 0; - /* min and max stores leftmost and right most index to - later print the tree in vertical fashion.*/ - int max = 0; - int min = 0; - queue.offer(root); - index.offer(0); + queue.offer(new NodeColumnPair(root, 0)); while (!queue.isEmpty()) { - if (queue.peek().left != null) { - /*Adding the left Node if it is not null - and its index by subtracting 1 from it's - parent's index*/ - queue.offer(queue.peek().left); - index.offer(index.peek() - 1); - } - if (queue.peek().right != null) { - /*Adding the right Node if it is not null - and its index by adding 1 from it's - parent's index*/ - queue.offer(queue.peek().right); - index.offer(index.peek() + 1); + NodeColumnPair current = queue.poll(); + + // Accessing record components uses method syntax '()' + BinaryTree.Node currentNode = current.node(); + int currentColumn = current.column(); + + // Automatically create a new list if the column doesn't exist yet + columnMap.computeIfAbsent(currentColumn, k -> new ArrayList<>()) + .add(currentNode.data); + + // Track bounds to avoid needing to sort map keys later + minColumn = Math.min(minColumn, currentColumn); + maxColumn = Math.max(maxColumn, currentColumn); + + if (currentNode.left != null) { + queue.offer(new NodeColumnPair(currentNode.left, currentColumn - 1)); } - /*If the map does not contains the index a new - ArrayList is created with the index as key.*/ - if (!map.containsKey(index.peek())) { - ArrayList a = new ArrayList<>(); - map.put(index.peek(), a); + + if (currentNode.right != null) { + queue.offer(new NodeColumnPair(currentNode.right, currentColumn + 1)); } - /*For a index, corresponding Node data is added - to the respective ArrayList present at that - index. */ - map.get(index.peek()).add(queue.peek().data); - max = Math.max(max, index.peek()); - min = Math.min(min, index.peek()); - /*The Node and its index are removed - from their respective queues.*/ - index.poll(); - queue.poll(); } - /*Finally map data is printed here which has keys - from min to max. Each ArrayList represents a - vertical column that is added in ans ArrayList.*/ - ArrayList ans = new ArrayList<>(); - for (int i = min; i <= max; i++) { - ans.addAll(map.get(i)); + + ArrayList result = new ArrayList<>(); + for (int i = minColumn; i <= maxColumn; i++) { + result.addAll(columnMap.get(i)); } - return ans; + + return result; } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/trees/WaveletTree.java b/src/main/java/com/thealgorithms/datastructures/trees/WaveletTree.java index 6feaa6f35048..f644e4b86ae0 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/WaveletTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/WaveletTree.java @@ -11,8 +11,8 @@ public class WaveletTree { private class Node { - int low; - int high; + final int low; + final int high; Node left; Node right; List leftCount; // Prefix sums of elements going to the left child @@ -223,9 +223,8 @@ private int kthSmallest(Node node, int left, int right, int k) { int elementsToLeft = countLeftInR - countLeftInLMinus1; if (k <= elementsToLeft) { - int newL = countLeftInLMinus1; int newR = countLeftInR - 1; - return kthSmallest(node.left, newL, newR, k); + return kthSmallest(node.left, countLeftInLMinus1, newR, k); } else { int newL = left - countLeftInLMinus1; int newR = right - countLeftInR; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java index 84fe0eb2c42a..2918b3f9e429 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java @@ -56,8 +56,9 @@ public static List> traverse(BinaryTree.Node root) { // traverse all the level nodes for (int i = 0; i < nodesOnLevel; i++) { BinaryTree.Node node = q.poll(); + assert node != null; if (prevLevelFromLeftToRight) { - level.add(0, node.data); + level.addFirst(node.data); } else { level.add(node.data); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java index 6c53666e5856..f5559f990166 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java @@ -53,7 +53,7 @@ class NRKTree { public NRKTree left; public NRKTree right; - public int data; + public final int data; NRKTree(int x) { this.left = null; diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index d69288f72200..5e186712e643 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -39,7 +39,7 @@ public LargeTreeNode(E data) { * * @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) + * @see TreeNode#TreeNode(Object, TreeNode) */ public LargeTreeNode(E data, LargeTreeNode parentNode) { super(data, parentNode); @@ -51,7 +51,7 @@ public LargeTreeNode(E data, LargeTreeNode parentNode) { * @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) + * @see TreeNode#TreeNode(Object, TreeNode) */ public LargeTreeNode(E data, LargeTreeNode parentNode, Collection> childNodes) { super(data, parentNode); diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java index a10817830962..d239db7d8b86 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java @@ -3,7 +3,7 @@ /** * 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. diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index eefffacee8d6..2cacb2f92a6a 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -41,7 +41,7 @@ public SimpleTreeNode(E data) { * * @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) + * @see TreeNode */ public SimpleTreeNode(E data, SimpleTreeNode parentNode) { 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 1639bec6e5a0..4c00ed4180e7 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java @@ -2,7 +2,7 @@ /** * 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. diff --git a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java index 36587a21c863..f12a23aea7d4 100644 --- a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java +++ b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java @@ -3,7 +3,7 @@ /** * The common interface of most searching algorithms that search in matrixes. * - * @author Aitor Fidalgo (https://github.com/aitorfi) + * @author Aitor Fidalgo (...) */ public interface MatrixSearchAlgorithm { /** diff --git a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java index eb5b42756958..3166bceae039 100644 --- a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java +++ b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java @@ -3,7 +3,7 @@ /** * The common interface of most searching algorithms * - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) */ public interface SearchAlgorithm { /** diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java index 323098a99887..7dc07726a387 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java +++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java @@ -9,11 +9,11 @@ public final class ClosestPair { /** * Number of points */ - int numberPoints; + final int numberPoints; /** * Input data, maximum 10000. */ - Location[] array; + final Location[] array; /** * Minimum point coordinate. */ @@ -53,8 +53,8 @@ public static void setSecondCount(int secondCount) { */ public static class Location { - double x; - double y; + final double x; + final double y; /** * @param xpar (IN Parameter) x coordinate
diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java index 0e8d9442138c..558b1bd2cb1b 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java +++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java @@ -11,7 +11,7 @@ */ public class SkylineAlgorithm { - private ArrayList points; + private final ArrayList points; /** * Main constructor of the application. ArrayList points gets created, which @@ -127,8 +127,8 @@ public ArrayList produceFinalSkyLine(ArrayList left, ArrayList * 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 @@ -24,7 +24,7 @@ private Abbreviation() { * @param b The target string containing only uppercase letters. * @return {@code true} if string `a` can be transformed into string `b`, * {@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..b7b2be19f2d4 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,7 +21,7 @@ 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. diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index ccd54ee4349a..57a65989d338 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -2,7 +2,7 @@ /** * Java program for Boundary fill algorithm. - * @author Akshay Dubey (https://github.com/itsAkshayDubey) + * @author Akshay Dubey (...) */ public final class BoundaryFill { private BoundaryFill() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java index d01066f611bd..b2a78b94ceb2 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java @@ -4,7 +4,7 @@ /** * 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 diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index 7edc9603dc8b..6c8c7378ad1e 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -1,7 +1,7 @@ package com.thealgorithms.dynamicprogramming; /** - * @author Varun Upadhyay (https://github.com/varunu28) + * @author Varun Upadhyay (...) */ public final class CoinChange { private CoinChange() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java index 9721d4ab0ad5..ba7520fb1078 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java @@ -5,14 +5,14 @@ /** * Implementation of the full Damerau–Levenshtein distance algorithm. - * + *

* This algorithm calculates the minimum number of operations required * to transform one string into another. Supported operations are: * insertion, deletion, substitution, and transposition of adjacent characters. - * + *

* Unlike the restricted version (OSA), this implementation allows multiple * edits on the same substring, computing the true edit distance. - * + *

* Time Complexity: O(n * m * max(n, m)) * Space Complexity: O(n * m) */ @@ -60,7 +60,7 @@ private static void validateInputs(String s1, String s2) { /** * Builds a character map containing all unique characters from both strings. * Each character is initialized with a position value of 0. - * + *

* This map is used to track the last occurrence position of each character * during the distance computation, which is essential for handling transpositions. * @@ -81,11 +81,11 @@ private static Map buildCharacterMap(String s1, String s2) { /** * Initializes the dynamic programming table for the algorithm. - * + *

* The table has dimensions (n+2) x (m+2) where n and m are the lengths * of the input strings. The extra rows and columns are used to handle * the transposition operation correctly. - * + *

* The first row and column are initialized with the maximum possible distance, * while the second row and column represent the base case of transforming * from an empty string. @@ -116,11 +116,11 @@ private static int[][] initializeTable(int n, int m) { /** * Fills the dynamic programming table by computing the minimum edit distance * for each substring pair. - * + *

* This method implements the core algorithm logic, iterating through both strings * and computing the minimum cost of transforming substrings. It considers all * four operations: insertion, deletion, substitution, and transposition. - * + *

* The character position map is updated as we progress through the first string * to enable efficient transposition cost calculation. * @@ -156,13 +156,13 @@ private static void fillTable(String s1, String s2, int[][] dp, Map * This method evaluates four possible operations: * 1. Substitution: replace character at position i with character at position j * 2. Insertion: insert character from s2 at position j * 3. Deletion: delete character from s1 at position i * 4. Transposition: swap characters that have been seen before - * + *

* The transposition cost accounts for the gap between the current position * and the last position where matching characters were found. * diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java b/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java index 7dae7603fedc..f549bf4f2ee6 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java @@ -61,7 +61,7 @@ private static long countWithDigitSum(long number, int target) { /** * Recursive memoized function to explore digit placements. - * + *

* Time Complexity: O(number_of_digits * target_sum * 10) * Space Complexity: O(number_of_digits * target_sum * 2) * diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index 0d6aff2bbef3..045d62b42b19 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -4,7 +4,7 @@ import java.util.Map; /** - * @author Varun Upadhyay (https://github.com/varunu28) + * @author Varun Upadhyay (...) */ public final class Fibonacci { private Fibonacci() { @@ -76,7 +76,7 @@ public static int fibBotUp(int n) { *

* Whereas , the above functions will take O(n) Space. * @throws IllegalArgumentException if n is negative - * @author Shoaib Rayeen (https://github.com/shoaibrayeen) + * @author Shoaib Rayeen (...) */ public static int fibOptimized(int n) { if (n < 0) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index 7a0a3da94c1e..8cef4bfa36ae 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 { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java index 0d4c8d501f9f..5ca5714f809f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java @@ -4,14 +4,11 @@ /** * 0/1 Knapsack Problem - Dynamic Programming solution. - * * This algorithm solves the classic optimization problem where we have n items, * each with a weight and a value. The goal is to maximize the total value * without exceeding the knapsack's weight capacity. - * * Time Complexity: O(n * W) * Space Complexity: O(W) - * * Example: * values = {60, 100, 120} * weights = {10, 20, 30} @@ -64,7 +61,7 @@ public static int knapSack(final int weightCapacity, final int[] weights, final return dp[weightCapacity]; } - /* + // Example main method for local testing only. public static void main(String[] args) { int[] values = {60, 100, 120}; @@ -74,5 +71,5 @@ public static void main(String[] args) { int maxValue = knapSack(weightCapacity, weights, values); System.out.println("Maximum value = " + maxValue); // Output: 220 } - */ + } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java index abc1e321ca8f..cee0edb9bac5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java @@ -4,11 +4,11 @@ * The {@code KnapsackZeroOne} provides Recursive solution for the 0/1 Knapsack * problem. Solves by exploring all combinations of items using recursion. No * memoization or dynamic programming optimizations are applied. - * + *

* Time Complexity: O(2^n) — explores all subsets. * Space Complexity: O(n) — due to recursive call stack. - * - * Problem Reference: https://en.wikipedia.org/wiki/Knapsack_problem + *

+ * Problem Refhttps://en.wikipedia.org/wiki/Knapsack_problem */ public final class KnapsackZeroOne { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java index c560efc61c71..62b5ad53618f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java @@ -5,18 +5,18 @@ * This method uses dynamic programming to build up a solution iteratively, * filling a 2-D array where each entry dp[i][w] represents the maximum value * achievable with the first i items and a knapsack capacity of w. - * + *

* The tabulation approach is efficient because it avoids redundant calculations * by solving all subproblems in advance and storing their results, ensuring * each subproblem is solved only once. This is a key technique in dynamic programming, * making it possible to solve problems that would otherwise be infeasible due to * exponential time complexity in naive recursive solutions. - * + *

* Time Complexity: O(n * W), where n is the number of items and W is the knapsack capacity. * Space Complexity: O(n * W) for the DP table. - * - * For more information, see: - * https://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming + *

+ * For more informatisee: + * https://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming */ public final class KnapsackZeroOneTabulation { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java index 119d65dfe365..41c82d37c827 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,18 +43,18 @@ 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. diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java index ba1def551192..d55af13c89e5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java @@ -9,7 +9,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..d123c65321e7 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 { @@ -26,7 +26,7 @@ public static String getLCS(String str1, String str2) { return null; } // If either string is empty, return an empty string as LCS. - if (str1.length() == 0 || str2.length() == 0) { + if (str1.isEmpty() || str2.isEmpty()) { return ""; } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java index 470833ce9c97..b08b858da67f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java @@ -1,7 +1,7 @@ package com.thealgorithms.dynamicprogramming; /** - * @author Afrizal Fikri (https://github.com/icalF) + * @author Afrizal Fikri (...) */ public final class LongestIncreasingSubsequence { private LongestIncreasingSubsequence() { @@ -53,7 +53,7 @@ else if (array[i] > tail[length - 1]) { } /** - * @author Alon Firestein (https://github.com/alonfirestein) + * @author Alon Firestein (...) */ // A function for finding the length of the LIS algorithm in O(nlogn) complexity. public static int findLISLen(int[] a) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java index 7bc0855e0566..47e70b6adb6b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java @@ -4,7 +4,7 @@ * Implementation of the Longest Increasing Subsequence (LIS) problem using * an O(n log n) dynamic programming solution enhanced with binary search. * - * @author Vusal Huseynov (https://github.com/huseynovvusal) + * @author Vusal Huseynov (...) */ public final class LongestIncreasingSubsequenceNLogN { private LongestIncreasingSubsequenceNLogN() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java index 02696bfca9c2..e717cc674a86 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java @@ -4,7 +4,7 @@ * Given a string containing just the characters '(' and ')', find the length of * the longest valid (well-formed) parentheses substring. * - * @author Libin Yang (https://github.com/yanglbme) + * @author Libin Yang (...) * @since 2018/10/5 */ public final class LongestValidParentheses { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java index 49af3ae3db88..1118b494c533 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java @@ -4,7 +4,7 @@ * Class to find the maximum sum of non-adjacent elements in an array. This * class contains two approaches: one with O(n) space complexity and another * with O(1) space optimization. For more information, refer to - * https://takeuforward.org/data-structure/maximum-sum-of-non-adjacent-elements-dp-5/ + * ... */ final class MaximumSumOfNonAdjacentElements { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java b/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java index 13b640cf0d04..7247ebe7cca7 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java @@ -4,7 +4,7 @@ * The Needleman–Wunsch algorithm performs global sequence alignment between two strings. * It computes the optimal alignment score using dynamic programming, * given a scoring scheme for matches, mismatches, and gaps. - * + *

* Time Complexity: O(n * m) * Space Complexity: O(n * m) */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java index 428176ea6c40..6064e1e2c49c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java @@ -13,7 +13,7 @@ * and 10 as its left child. The total cost is 50 * 1 + 34 * 2 = 118. * *

Reference: - * https://en.wikipedia.org/wiki/Optimal_binary_search_tree + * ... */ public final class OptimalBinarySearchTree { private OptimalBinarySearchTree() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index e31bb73096e8..bc347350f55e 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -4,8 +4,8 @@ * This class refers to the Optimal Job Scheduling problem with the following constrains: * - precedence relation between the processes * - machine pair dependent transportation delays - * - * https://en.wikipedia.org/wiki/Optimal_job_scheduling + *

* https://en.wikipedia.org/wiki/Optimal_job_scheduling * * @author georgioct@csd.auth.gr */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java index 8c72fa347f50..ef3ab5d508c2 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java @@ -2,11 +2,11 @@ import java.util.Arrays; /** * @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. diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java index 181ac72a654d..97262eb73792 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java @@ -5,11 +5,11 @@ * 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 + *

+ * Memoization vs Tabul: https://www.geeksforgeeks.org/tabulation-vs-memoization/ + * Question...tching/1 */ public final class RegexMatching { private RegexMatching() { @@ -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. * @@ -28,13 +28,13 @@ private RegexMatching() { * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ public static boolean regexRecursion(String src, String pat) { - if (src.length() == 0 && pat.length() == 0) { + if (src.isEmpty() && pat.isEmpty()) { return true; } - if (src.length() != 0 && pat.length() == 0) { + if (!src.isEmpty() && pat.isEmpty()) { return false; } - if (src.length() == 0 && pat.length() != 0) { + if (src.isEmpty() && !pat.isEmpty()) { for (int i = 0; i < pat.length(); i++) { if (pat.charAt(i) != '*') { return false; @@ -64,7 +64,7 @@ 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. * @@ -108,7 +108,7 @@ 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. * @@ -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/SmithWaterman.java b/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java index c0d66f68b502..69ca7e42dddd 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java @@ -3,7 +3,7 @@ /** * Smith–Waterman algorithm for local sequence alignment. * Finds the highest scoring local alignment between substrings of two sequences. - * + *

* Time Complexity: O(n * m) * Space Complexity: O(n * m) */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java index e9c15c1b4f24..478d711c3036 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java @@ -3,11 +3,11 @@ /** * 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 + *

+ * Wikhttps://en.wikipedia.org/wiki/Subset_sum_problem */ public final class SumOfSubset { @@ -22,7 +22,7 @@ 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 diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java index 9fd82ccaf078..4448b6ed8a72 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java @@ -5,7 +5,7 @@ /** * This class implements the algorithm for calculating the maximum weighted matching in a tree. * The tree is represented as an undirected graph with weighted edges. - * + *

* Problem Description: * Given an undirected tree G = (V, E) with edge weights γ: E → N and a root r ∈ V, * the goal is to find a maximum weight matching M ⊆ E such that no two edges in M @@ -16,8 +16,8 @@ */ public class TreeMatching { - private UndirectedAdjacencyListGraph graph; - private int[][] dp; + private final UndirectedAdjacencyListGraph graph; + private final int[][] dp; /** * Constructor that initializes the graph and the DP table. diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java index 3ff6cc620236..71b3e69bb2ba 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java @@ -2,7 +2,7 @@ /** * The {@code Tribonacci} class provides a method to compute the n-th number in the Tribonacci sequence. - * N-th Tribonacci Number - https://leetcode.com/problems/n-th-tribonacci-number/description/ + * N-th Tribonacci Number - ... */ public final class Tribonacci { private Tribonacci() { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java index 22ad8a7dd8e3..197e2a5d5a13 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java @@ -4,7 +4,7 @@ /** * Author: Siddhant Swarup Mallick - * Github: https://github.com/siddhant2002 + * Github: ... *

* Problem Description: * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java index 8c7ea6179e3f..a13725532812 100755 --- a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java @@ -12,7 +12,7 @@ * using dynamic programming and recursion. It ensures that duplicate characters * are not counted multiple times in the subsequences.

* - *

Author: https://github.com/Tuhinm2002

+ *

Author: ...

*/ public final class UniqueSubsequencesCount { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java index 8658ea30af00..45b53d135917 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java @@ -3,13 +3,12 @@ /** * * Author: Janmesh Singh - * Github: https://github.com/janmeshjs - + * Github: ... * 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. - * + *

* Use DP to return True if the pattern matches the entire text and False otherwise * */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java index 022b43184a88..72ddc2a9f2b3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java @@ -5,19 +5,19 @@ * 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. - * + *

* 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. - * + *

* 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) diff --git a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java index 51d9930c0250..540aae90c873 100644 --- a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java +++ b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java @@ -11,8 +11,8 @@ * *

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} + /** + * For more information, please visit Bresenham's 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 d44d20c68807..7ab87c4e4fe4 100644 --- a/src/main/java/com/thealgorithms/geometry/ConvexHull.java +++ b/src/main/java/com/thealgorithms/geometry/ConvexHull.java @@ -3,55 +3,186 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; +import java.util.Comparator; + +// ───────────────────────────────────────────────────────────────────────────── +// 1. Shared geometry utilities +// (SRP: one class owns all pure geometric calculations used by both algorithms) +// ───────────────────────────────────────────────────────────────────────────── /** - * 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 + * Pure geometric helper methods shared across convex-hull algorithms. * - * @author Hardvan + *

All methods are stateless and side-effect-free. + * No algorithm control-flow lives here — only geometry.

*/ -public final class ConvexHull { - private ConvexHull() { - } +final class HullGeometry { + + /** Sentinel used when no extreme-point distance has been recorded yet. */ + static final int NO_DISTANCE = Integer.MIN_VALUE; + + private HullGeometry() {} - private static boolean checkPointOrientation(Point i, Point j, Point k) { - int detK = Point.orientation(i, j, k); - if (detK > 0) { - return true; // pointsLeftOfIJ - } else if (detK < 0) { - return false; // pointsRightOfIJ + /** + * Determines whether point {@code k} lies on the same side of line {@code ij} + * as the reference direction established by the first non-collinear point. + * + *

For collinear points the method returns {@code true} when {@code k} falls + * between {@code i} and {@code j} (inclusive), so that segment endpoints are + * treated as hull candidates.

+ * + * @return {@code true} if {@code k} is left-of or on the segment {@code ij}; + * {@code false} if it is right-of the line + */ + static boolean isOnExpectedSide(Point i, Point j, Point k) { + int orientation = Point.orientation(i, j, k); + if (orientation > 0) { + return true; // k is left of i→j + } else if (orientation < 0) { + return false; // k is right of i→j } else { - return k.compareTo(i) >= 0 && k.compareTo(j) <= 0; + return k.compareTo(i) >= 0 && k.compareTo(j) <= 0; // k is collinear, between i and j } } - public static List convexHullBruteForce(List points) { + /** + * Returns the squared Euclidean distance between {@code p1} and {@code p2}. + * + *

Using squared distance avoids floating-point arithmetic while still + * providing a consistent total order on distances.

+ */ + static long squaredDistance(Point p1, Point p2) { + long dx = (long) p1.x() - p2.x(); + long dy = (long) p1.y() - p2.y(); + return dx * dx + dy * dy; + } + + /** + * Sorts {@code hullPoints} in counter-clockwise order starting from the + * bottom-most, left-most point (the angular pivot). + * + *

Intermediate collinear points are removed so that only the farthest + * point along each ray from the pivot is retained.

+ * + * @param hullPoints mutable list of hull points to sort in-place and return + * @return the same list, now ordered counter-clockwise + */ + static List sortCounterClockwise(List hullPoints) { + if (hullPoints.size() <= 2) { + Collections.sort(hullPoints); + return hullPoints; + } + + Point pivot = findBottomLeftPoint(hullPoints); + List remaining = sortByPolarAngle(hullPoints, pivot); + return buildOrderedHull(pivot, remaining); + } + + // ── private helpers ─────────────────────────────────────────────────────── + + /** Finds the bottom-most, left-most point in {@code points}. */ + private static Point findBottomLeftPoint(List points) { + Point pivot = points.getFirst(); + for (Point p : points) { + if (p.y() < pivot.y() || (p.y() == pivot.y() && p.x() < pivot.x())) { + pivot = p; + } + } + return pivot; + } + + /** + * Returns all points except {@code pivot}, sorted by polar angle relative + * to {@code pivot}. Collinear points are ordered closer-first so that the + * final hull-building step can simply keep the last one. + */ + private static List sortByPolarAngle(List hullPoints, Point pivot) { + List remaining = new ArrayList<>(hullPoints); + remaining.remove(pivot); + remaining.sort((p1, p2) -> { + int crossProduct = Point.orientation(pivot, p1, p2); + if (crossProduct == 0) { + // Collinear: put the closer point first so we discard it later + return Long.compare(squaredDistance(pivot, p1), squaredDistance(pivot, p2)); + } + // Negative cross product means p1 is CCW from p2 → p1 should come first + return -crossProduct; + }); + return remaining; + } + + /** + * Builds the final ordered list by placing {@code pivot} first and + * discarding intermediate collinear points (keeping only the farthest one + * along each ray). + */ + private static List buildOrderedHull(Point pivot, List sorted) { + List result = new ArrayList<>(); + result.add(pivot); + + for (int i = 0; i < sorted.size() - 1; i++) { + int orientation = Point.orientation(pivot, sorted.get(i), sorted.get(i + 1)); + if (orientation != 0) { + // Current point is the farthest at its angle — keep it + result.add(sorted.get(i)); + } + // orientation == 0 means the next point is farther along the same ray — skip this one + } + // The last sorted point is always kept: it is either unique at its angle + // or the farthest among a collinear group + result.add(sorted.getLast()); + + return result; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 2. Strategy interface +// (OCP + DIP: new algorithms can be added without touching existing code; +// callers depend on this abstraction, not on concrete classes) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Strategy contract for convex-hull algorithms. + * + *

Any class implementing this interface accepts a list of {@link Point}s + * and returns the hull vertices in counter-clockwise order.

+ */ +interface ConvexHullAlgorithm { + /** + * Computes the convex hull of {@code points}. + * + * @param points the input point set (not modified) + * @return the hull vertices in counter-clockwise order + */ + List compute(List points); +} + +// ───────────────────────────────────────────────────────────────────────────── +// 3. Brute-force algorithm +// (SRP: this class is solely responsible for the O(n³) brute-force method) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Convex-hull computation using the O(n³) brute-force edge-enumeration method. + * + *

For every pair of points {@code (i, j)}, the algorithm checks whether all + * remaining points lie on the same side of the directed line {@code i→j}. + * If they do, both endpoints are hull vertices.

+ */ +final class BruteForceHull implements ConvexHullAlgorithm { + + @Override + public List compute(List points) { Set convexSet = new TreeSet<>(Comparator.naturalOrder()); for (int i = 0; i < points.size() - 1; i++) { for (int j = i + 1; j < points.size(); j++) { - boolean allPointsOnOneSide = true; - boolean leftSide = checkPointOrientation(points.get(i), points.get(j), points.get((i + 1) % points.size())); - - for (int k = 0; k < points.size(); k++) { - if (k != i && k != j && checkPointOrientation(points.get(i), points.get(j), points.get(k)) != leftSide) { - allPointsOnOneSide = false; - break; - } - } - - if (allPointsOnOneSide) { + if (isHullEdge(points, i, j)) { convexSet.add(points.get(i)); convexSet.add(points.get(j)); } @@ -62,146 +193,187 @@ public static List convexHullBruteForce(List points) { } /** - * Computes the convex hull using a recursive divide-and-conquer approach. - * Returns points in counter-clockwise order starting from the bottom-most, left-most point. - * - * @param points the input points - * @return the convex hull points in counter-clockwise order + * Returns {@code true} when the directed edge from {@code points[i]} to + * {@code points[j]} has all other points on the same side. */ - public static List convexHullRecursive(List points) { + private boolean isHullEdge(List points, int i, int j) { + // Use the point just after i as the reference side + boolean referenceSide = HullGeometry.isOnExpectedSide( + points.get(i), points.get(j), points.get((i + 1) % points.size()) + ); + + for (int k = 0; k < points.size(); k++) { + if (k == i || k == j) { + continue; + } + if (HullGeometry.isOnExpectedSide(points.get(i), points.get(j), points.get(k)) != referenceSide) { + return false; + } + } + return true; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 4. Recursive (divide-and-conquer) algorithm +// (SRP: this class is solely responsible for the recursive hull method) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Convex-hull computation using a recursive divide-and-conquer approach. + * + *

The algorithm splits the point set into an upper and a lower hull relative + * to the line connecting the leftmost and rightmost points, then recursively + * finds the extreme point of each sub-hull.

+ * + *

Returns points in counter-clockwise order starting from the bottom-most, + * left-most point.

+ */ +final class RecursiveHull implements ConvexHullAlgorithm { + + @Override + public List compute(List points) { if (points.size() < 3) { List result = new ArrayList<>(points); Collections.sort(result); return result; } - Collections.sort(points); - Set convexSet = new HashSet<>(); - Point leftMostPoint = points.getFirst(); - Point rightMostPoint = points.getLast(); + List sorted = new ArrayList<>(points); + Collections.sort(sorted); - convexSet.add(leftMostPoint); - convexSet.add(rightMostPoint); + Point leftMost = sorted.getFirst(); + Point rightMost = sorted.getLast(); + + Set convexSet = new HashSet<>(); + convexSet.add(leftMost); + convexSet.add(rightMost); List upperHull = new ArrayList<>(); List lowerHull = new ArrayList<>(); - for (int i = 1; i < points.size() - 1; i++) { - int det = Point.orientation(leftMostPoint, rightMostPoint, points.get(i)); - if (det > 0) { - upperHull.add(points.get(i)); - } else if (det < 0) { - lowerHull.add(points.get(i)); - } - } + partitionPoints(sorted, leftMost, rightMost, upperHull, lowerHull); - constructHull(upperHull, leftMostPoint, rightMostPoint, convexSet); - constructHull(lowerHull, rightMostPoint, leftMostPoint, convexSet); + constructHull(upperHull, leftMost, rightMost, convexSet); + constructHull(lowerHull, rightMost, leftMost, convexSet); - // Convert to list and sort in counter-clockwise order - return sortCounterClockwise(new ArrayList<>(convexSet)); + return HullGeometry.sortCounterClockwise(new ArrayList<>(convexSet)); } - private static void constructHull(Collection points, Point left, Point right, Set convexSet) { - if (!points.isEmpty()) { - Point extremePoint = null; - int extremePointDistance = Integer.MIN_VALUE; - List candidatePoints = new ArrayList<>(); - - for (Point p : points) { - int det = Point.orientation(left, right, p); - if (det > 0) { - candidatePoints.add(p); - if (det > extremePointDistance) { - extremePointDistance = det; - extremePoint = p; - } - } - } - - if (extremePoint != null) { - constructHull(candidatePoints, left, extremePoint, convexSet); - convexSet.add(extremePoint); - constructHull(candidatePoints, extremePoint, right, convexSet); + /** + * Splits interior points into upper and lower hulls relative to the + * baseline {@code leftMost → rightMost}. + */ + private void partitionPoints(List sorted, Point leftMost, Point rightMost, + List upperHull, List lowerHull) { + for (int i = 1; i < sorted.size() - 1; i++) { + int orientation = Point.orientation(leftMost, rightMost, sorted.get(i)); + if (orientation > 0) { + upperHull.add(sorted.get(i)); + } else if (orientation < 0) { + lowerHull.add(sorted.get(i)); } } } /** - * Sorts convex hull points in counter-clockwise order starting from - * the bottom-most, left-most point. - * - * @param hullPoints the unsorted convex hull points - * @return the points sorted in counter-clockwise order + * Recursively identifies the extreme point on the left side of the directed + * line {@code left → right} and adds confirmed hull vertices to + * {@code convexSet}. */ - private static List sortCounterClockwise(List hullPoints) { - if (hullPoints.size() <= 2) { - Collections.sort(hullPoints); - return hullPoints; + private void constructHull(Collection points, Point left, Point right, Set convexSet) { + if (points.isEmpty()) { + return; } - // Find the bottom-most, left-most point (pivot) - Point pivot = hullPoints.getFirst(); - for (Point p : hullPoints) { - if (p.y() < pivot.y() || (p.y() == pivot.y() && p.x() < pivot.x())) { - pivot = p; - } + Point extremePoint = findExtremePoint(points, left, right); + if (extremePoint == null) { + return; } - // Sort other points by polar angle with respect to pivot - final Point finalPivot = pivot; - List sorted = new ArrayList<>(hullPoints); - sorted.remove(finalPivot); + List leftCandidates = collectLeftOf(points, left, right); - sorted.sort((p1, p2) -> { - int crossProduct = Point.orientation(finalPivot, p1, p2); + constructHull(leftCandidates, left, extremePoint, convexSet); + convexSet.add(extremePoint); + constructHull(leftCandidates, extremePoint, right, convexSet); + } - if (crossProduct == 0) { - // Collinear points: sort by distance from pivot (closer first for convex hull) - long dist1 = distanceSquared(finalPivot, p1); - long dist2 = distanceSquared(finalPivot, p2); - return Long.compare(dist1, dist2); - } + /** + * Returns the point in {@code points} that lies furthest to the left of the + * directed line {@code left → right}, or {@code null} if no such point exists. + */ + private Point findExtremePoint(Collection points, Point left, Point right) { + Point extremePoint = null; + int maxDistance = HullGeometry.NO_DISTANCE; - // Positive cross product means p2 is counter-clockwise from p1 - // We want counter-clockwise order, so if p2 is CCW from p1, p1 should come first - return -crossProduct; - }); + for (Point p : points) { + int distance = Point.orientation(left, right, p); + if (distance > 0 && distance > maxDistance) { + maxDistance = distance; + extremePoint = p; + } + } + return extremePoint; + } - // Build result with pivot first, filtering out intermediate collinear points + /** + * Returns all points in {@code points} that lie strictly to the left of the + * directed line {@code left → right}. + */ + private List collectLeftOf(Collection points, Point left, Point right) { List result = new ArrayList<>(); - result.add(finalPivot); - - if (!sorted.isEmpty()) { - // This loop iterates through the points sorted by angle. - // For points that are collinear with the pivot, we only want the one that is farthest away. - // The sort places closer points first. - for (int i = 0; i < sorted.size() - 1; i++) { - // Check the orientation of the pivot, the current point, and the next point. - int orientation = Point.orientation(finalPivot, sorted.get(i), sorted.get(i + 1)); - - // If the orientation is not 0, it means the next point (i+1) is at a new angle. - // Therefore, the current point (i) must be the farthest point at its angle. We keep it. - if (orientation != 0) { - result.add(sorted.get(i)); - } - // If the orientation is 0, the points are collinear. We discard the current point (i) - // because it is closer to the pivot than the next point (i+1). + for (Point p : points) { + if (Point.orientation(left, right, p) > 0) { + result.add(p); } - // Always add the very last point from the sorted list. It is either the only point - // at its angle, or it's the farthest among a set of collinear points. - result.add(sorted.getLast()); } - return result; } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 5. Public façade (preserves the original public API surface exactly) +// (DIP: static helpers now delegate to the strategy implementations) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Public entry point for convex-hull computation. + * + *

Provides two named factory methods that preserve the original API while + * delegating to independent, interchangeable {@link ConvexHullAlgorithm} + * implementations.

+ * + *

Algorithms provided:

+ *
    + *
  1. Brute-Force Method — O(n³), via {@link BruteForceHull}
  2. + *
  3. Recursive Divide-and-Conquer Method — O(n log n), via {@link RecursiveHull}
  4. + *
+ * + * @author Hardvan + */ +public final class ConvexHull { + + private ConvexHull() {} + + /** + * Computes the convex hull using the O(n³) brute-force method. + * + * @param points the input points + * @return the convex hull vertices + */ + public static List convexHullBruteForce(List points) { + return new BruteForceHull().compute(points); + } /** - * Computes the squared distance between two points to avoid floating point operations. + * Computes the convex hull using a recursive divide-and-conquer approach. + * Returns points in counter-clockwise order starting from the bottom-most, + * left-most point. + * + * @param points the input points + * @return the convex hull points in counter-clockwise order */ - private static long distanceSquared(Point p1, Point p2) { - long dx = (long) p1.x() - p2.x(); - long dy = (long) p1.y() - p2.y(); - return dx * dx + dy * dy; + public static List convexHullRecursive(List points) { + return new RecursiveHull().compute(points); } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/geometry/DDALine.java b/src/main/java/com/thealgorithms/geometry/DDALine.java index cb24951f398a..7dd288f4c5ea 100644 --- a/src/main/java/com/thealgorithms/geometry/DDALine.java +++ b/src/main/java/com/thealgorithms/geometry/DDALine.java @@ -8,11 +8,11 @@ * The {@code DDALine} class implements the Digital Differential Analyzer (DDA) * line drawing algorithm. It computes points along a line between two given * endpoints using floating-point arithmetic. - * + *

* The algorithm is straightforward but less efficient compared to * Bresenham’s line algorithm, since it relies on floating-point operations. - * - * For more information, please visit {@link https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)} + /** + * For more information, please visit Digital Differential Analyzer Algorithm */ public final class DDALine { diff --git a/src/main/java/com/thealgorithms/geometry/GrahamScan.java b/src/main/java/com/thealgorithms/geometry/GrahamScan.java index 1a373cf315a2..b2b74d43e103 100644 --- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java +++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java @@ -9,11 +9,11 @@ * 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 - * https://algs4.cs.princeton.edu/99hull/GrahamScan.java.html + *

+ * 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* https://algs4.cs.princeton.edu/99hull/GrahamScan.java.html */ public class GrahamScan { diff --git a/src/main/java/com/thealgorithms/geometry/Haversine.java b/src/main/java/com/thealgorithms/geometry/Haversine.java index fa1799e9f076..8279521817a6 100644 --- a/src/main/java/com/thealgorithms/geometry/Haversine.java +++ b/src/main/java/com/thealgorithms/geometry/Haversine.java @@ -1,11 +1,11 @@ package com.thealgorithms.geometry; /** * This Class implements the Haversine formula to calculate the distance between two points on a sphere (like Earth) from their latitudes and longitudes. - * + *

* The Haversine formula is used in navigation and mapping to find the great-circle distance, * which is the shortest distance between two points along the surface of a sphere. It is often * used to calculate the "as the crow flies" distance between two geographical locations. - * + *

* The formula is reliable for all distances, including small ones, and avoids issues with * numerical instability that can affect other methods. * diff --git a/src/main/java/com/thealgorithms/geometry/LineIntersection.java b/src/main/java/com/thealgorithms/geometry/LineIntersection.java index 8d65833816b3..4f82cf0fac0b 100644 --- a/src/main/java/com/thealgorithms/geometry/LineIntersection.java +++ b/src/main/java/com/thealgorithms/geometry/LineIntersection.java @@ -38,11 +38,7 @@ public static boolean intersects(Point p1, Point p2, Point q1, Point q2) { if (o3 == 0 && onSegment(q1, p1, q2)) { return true; } - if (o4 == 0 && onSegment(q1, p2, q2)) { - return true; - } - - return false; + return o4 == 0 && onSegment(q1, p2, q2); } /** diff --git a/src/main/java/com/thealgorithms/geometry/WusLine.java b/src/main/java/com/thealgorithms/geometry/WusLine.java index 3539daaf6e5a..f4794e5ce9a4 100644 --- a/src/main/java/com/thealgorithms/geometry/WusLine.java +++ b/src/main/java/com/thealgorithms/geometry/WusLine.java @@ -8,16 +8,16 @@ * The {@code WusLine} class implements Xiaolin Wu's line drawing algorithm, * which produces anti-aliased lines by varying pixel brightness * according to the line's proximity to pixel centers. - * + *

* This implementation returns the pixel coordinates along with * their associated intensity values (in range [0.0, 1.0]), allowing * rendering systems to blend accordingly. - * + *

* The algorithm works by: * - Computing a line's intersection with pixel boundaries * - Assigning intensity values based on distance from pixel centers * - Drawing pairs of pixels perpendicular to the line's direction - * + *

* Reference: Xiaolin Wu, "An Efficient Antialiasing Technique", * Computer Graphics (SIGGRAPH '91 Proceedings). * @@ -30,7 +30,7 @@ private WusLine() { /** * Represents a pixel and its intensity for anti-aliased rendering. - * + *

* The intensity value determines how bright the pixel should be drawn, * with 1.0 being fully opaque and 0.0 being fully transparent. */ @@ -73,7 +73,7 @@ private static class EndpointData { /** * Draws an anti-aliased line using Wu's algorithm. - * + *

* The algorithm produces smooth lines by drawing pairs of pixels at each * x-coordinate (or y-coordinate for steep lines), with intensities based on * the line's distance from pixel centers. diff --git a/src/main/java/com/thealgorithms/graph/BronKerbosch.java b/src/main/java/com/thealgorithms/graph/BronKerbosch.java index 0510d9bcf494..6f2d81535502 100644 --- a/src/main/java/com/thealgorithms/graph/BronKerbosch.java +++ b/src/main/java/com/thealgorithms/graph/BronKerbosch.java @@ -1,99 +1,137 @@ package com.thealgorithms.graph; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; +// ───────────────────────────────────────────────────────────────────────────── +// 1. Graph abstraction (DIP: high-level code depends on this, not on HashSet) +// ───────────────────────────────────────────────────────────────────────────── + /** - * Implementation of the Bron–Kerbosch algorithm with pivoting for enumerating all maximal cliques - * in an undirected graph. - * - *

The input graph is represented as an adjacency list where {@code adjacency.get(u)} returns the - * set of vertices adjacent to {@code u}. The algorithm runs in time proportional to the number of - * maximal cliques produced and is widely used for clique enumeration problems.

- * - * @author Wikipedia: Bron–Kerbosch algorithm + * Read-only view of an undirected graph used by the clique enumeration algorithm. */ -public final class BronKerbosch { +interface Graph { + /** Returns the number of vertices. */ + int size(); + + /** + * Returns an unmodifiable set of neighbors for vertex {@code u}. + * + * @throws IndexOutOfBoundsException if {@code u} is out of range + */ + Set neighbours(int u); +} + +// ───────────────────────────────────────────────────────────────────────────── +// 2. Concrete Graph implementation +// (SRP: only responsible for storing and exposing adjacency) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Immutable adjacency-list graph built from a raw {@code List>}. + */ +final class AdjacencyListGraph implements Graph { + + private final List> adjacency; + + /** + * Constructs a validated, defensive copy of the supplied adjacency list. + * + * @param raw the adjacency list to copy; already validated by {@link GraphValidator} + */ + AdjacencyListGraph(List> raw) { + int n = raw.size(); + List> copy = new ArrayList<>(n); + for (int u = 0; u < n; u++) { + Set neighbours = new HashSet<>(raw.get(u)); + neighbours.remove(u); // strip self-loops + copy.add(Collections.unmodifiableSet(neighbours)); + } + this.adjacency = Collections.unmodifiableList(copy); + } + + @Override + public int size() { + return adjacency.size(); + } - private BronKerbosch() { + @Override + public Set neighbours(int u) { + return adjacency.get(u); } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 3. Input validation +// (SRP: one class, one job — catch bad input before it enters the algorithm) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Validates a raw adjacency list before it is used to construct a {@link Graph}. + */ +final class GraphValidator { + + private GraphValidator() {} /** - * Finds all maximal cliques of the provided graph. + * Throws {@link IllegalArgumentException} if the adjacency list is malformed. * - * @param adjacency adjacency list where {@code adjacency.size()} equals the number of vertices - * @return a list containing every maximal clique, each represented as a {@link Set} of vertices - * @throws IllegalArgumentException if the adjacency list is {@code null}, contains {@code null} - * entries, or references invalid vertices + * @param adjacency the list to validate */ - public static List> findMaximalCliques(List> adjacency) { + static void validate(List> adjacency) { if (adjacency == null) { throw new IllegalArgumentException("Adjacency list must not be null"); } - int n = adjacency.size(); - List> graph = new ArrayList<>(n); - for (int u = 0; u < n; u++) { - Set neighbors = adjacency.get(u); - if (neighbors == null) { + for (Set neighbours : adjacency) { + if (neighbours == null) { throw new IllegalArgumentException("Adjacency list must not contain null sets"); } - Set copy = new HashSet<>(); - for (int v : neighbors) { + for (int v : neighbours) { if (v < 0 || v >= n) { - throw new IllegalArgumentException("Neighbor index out of bounds: " + v); - } - if (v != u) { - copy.add(v); + throw new IllegalArgumentException("Neighbour index out of bounds: " + v); } } - graph.add(copy); - } - - Set r = new HashSet<>(); - Set p = new HashSet<>(); - Set x = new HashSet<>(); - for (int v = 0; v < n; v++) { - p.add(v); } - - List> cliques = new ArrayList<>(); - bronKerboschPivot(r, p, x, graph, cliques); - return cliques; } +} - private static void bronKerboschPivot(Set r, Set p, Set x, List> graph, List> cliques) { - if (p.isEmpty() && x.isEmpty()) { - cliques.add(new HashSet<>(r)); - return; - } +// ───────────────────────────────────────────────────────────────────────────── +// 4. Pivot selection strategy +// (OCP: swap out strategies without touching the solver; +// DIP: solver depends on the interface, not a concrete choice) +// ───────────────────────────────────────────────────────────────────────────── - int pivot = choosePivot(p, x, graph); - Set candidates = new HashSet<>(p); - if (pivot != -1) { - candidates.removeAll(graph.get(pivot)); - } +/** + * Strategy for choosing a pivot vertex during Bron–Kerbosch enumeration. + */ +interface PivotStrategy { + /** + * Selects a pivot from {@code candidates ∪ excluded}. + * + * @param candidates the current P set + * @param excluded the current X set + * @param graph the graph being searched + * @return the chosen pivot, or {@code -1} if the union is empty + */ + int choosePivot(Set candidates, Set excluded, Graph graph); +} - for (Integer v : candidates) { - r.add(v); - Set newP = intersection(p, graph.get(v)); - Set newX = intersection(x, graph.get(v)); - bronKerboschPivot(r, newP, newX, graph, cliques); - r.remove(v); - p.remove(v); - x.add(v); - } - } +/** + * Picks the vertex from {@code P ∪ X} with the highest degree in the full graph. + * This is the classic Tomita et al. (2006) heuristic. + */ +final class MaxDegreePivotStrategy implements PivotStrategy { - private static int choosePivot(Set p, Set x, List> graph) { + @Override + public int choosePivot(Set candidates, Set excluded, Graph graph) { int pivot = -1; int maxDegree = -1; - Set union = new HashSet<>(p); - union.addAll(x); - for (Integer v : union) { - int degree = graph.get(v).size(); + for (int v : union(candidates, excluded)) { + int degree = graph.neighbours(v).size(); if (degree > maxDegree) { maxDegree = degree; pivot = v; @@ -102,13 +140,169 @@ private static int choosePivot(Set p, Set x, List return pivot; } - private static Set intersection(Set base, Set neighbors) { + private static Set union(Set a, Set b) { + Set result = new HashSet<>(a); + result.addAll(b); + return result; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 5. Search-state value object +// (removes the "data clump" smell: R/P/X always travelled together) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Immutable snapshot of one recursive frame in the Bron–Kerbosch search: + * the current clique {@code R}, candidate vertices {@code P}, and + * already-processed vertices {@code X}. + * + *

Mutation methods return new instances, keeping each frame independent.

+ */ +final class SearchState { + + final Set clique; // R + final Set candidates; // P + final Set excluded; // X + + SearchState(Set clique, Set candidates, Set excluded) { + this.clique = Collections.unmodifiableSet(new HashSet<>(clique)); + this.candidates = Collections.unmodifiableSet(new HashSet<>(candidates)); + this.excluded = Collections.unmodifiableSet(new HashSet<>(excluded)); + } + + /** Returns the initial state for a graph with {@code n} vertices. */ + static SearchState initial(int n) { + Set allVertices = new HashSet<>(); + for (int v = 0; v < n; v++) { + allVertices.add(v); + } + return new SearchState(new HashSet<>(), allVertices, new HashSet<>()); + } + + /** Returns a new state with {@code vertex} added to the clique and both sets intersected with its neighbours. */ + SearchState expandWith(int vertex, Graph graph) { + Set neighbours = graph.neighbours(vertex); + Set newClique = new HashSet<>(clique); + newClique.add(vertex); + return new SearchState(newClique, intersection(candidates, neighbours), intersection(excluded, neighbours)); + } + + /** Returns a new state with {@code vertex} moved from candidates to excluded. */ + SearchState processVertex(int vertex) { + Set newCandidates = new HashSet<>(candidates); + newCandidates.remove(vertex); + Set newExcluded = new HashSet<>(excluded); + newExcluded.add(vertex); + return new SearchState(clique, newCandidates, newExcluded); + } + + boolean isMaximalClique() { + return candidates.isEmpty() && excluded.isEmpty(); + } + + private static Set intersection(Set base, Set filter) { Set result = new HashSet<>(); - for (Integer v : base) { - if (neighbors.contains(v)) { + for (int v : base) { + if (filter.contains(v)) { result.add(v); } } return result; } } + +// ───────────────────────────────────────────────────────────────────────────── +// 6. Algorithm orchestrator +// (SRP: only responsible for the recursive enumeration logic; +// DIP: depends on Graph and PivotStrategy abstractions) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Enumerates all maximal cliques using the Bron–Kerbosch algorithm with pivoting. + * + *

The solver is constructed with a {@link PivotStrategy}, making the pivot + * heuristic interchangeable without modifying this class (OCP).

+ */ +final class BronKerboschSolver { + + private final PivotStrategy pivotStrategy; + + /** + * Creates a solver using the supplied pivot strategy. + * + * @param pivotStrategy the strategy for choosing a pivot vertex; must not be null + */ + BronKerboschSolver(PivotStrategy pivotStrategy) { + if (pivotStrategy == null) { + throw new IllegalArgumentException("PivotStrategy must not be null"); + } + this.pivotStrategy = pivotStrategy; + } + + /** + * Finds all maximal cliques in {@code graph}. + * + * @param graph the graph to search + * @return a list of maximal cliques, each as an unmodifiable set of vertices + */ + List> findMaximalCliques(Graph graph) { + List> cliques = new ArrayList<>(); + enumerate(SearchState.initial(graph.size()), graph, cliques); + return cliques; + } + + private void enumerate(SearchState state, Graph graph, List> cliques) { + if (state.isMaximalClique()) { + cliques.add(state.clique); + return; + } + + int pivot = pivotStrategy.choosePivot(state.candidates, state.excluded, graph); + Set pivotNeighbours = pivot == -1 ? new HashSet<>() : graph.neighbours(pivot); + + // Iterate over P \ N(pivot) — a snapshot copy is needed since state is immutable anyway + Set toExpand = new HashSet<>(state.candidates); + toExpand.removeAll(pivotNeighbours); + + SearchState current = state; + for (int vertex : toExpand) { + enumerate(current.expandWith(vertex, graph), graph, cliques); + current = current.processVertex(vertex); + } + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// 7. Public façade (preserves the original public API surface exactly) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Public entry point for maximal-clique enumeration via the Bron–Kerbosch algorithm. + * + *

This façade wires together {@link GraphValidator}, {@link AdjacencyListGraph}, + * {@link MaxDegreePivotStrategy}, and {@link BronKerboschSolver}, keeping all + * callers insulated from the internal decomposition.

+ * + * @see + * Wikipedia: Bron–Kerbosch algorithm + */ +public final class BronKerbosch { + + private BronKerbosch() {} + + /** + * Finds all maximal cliques of the provided graph. + * + * @param adjacency adjacency list where {@code adjacency.size()} equals the number of vertices + * @return a list containing every maximal clique, each represented as a {@link Set} of vertices + * @throws IllegalArgumentException if the adjacency list is {@code null}, contains {@code null} + * entries, or references invalid vertices + */ + public static List> findMaximalCliques(List> adjacency) { + GraphValidator.validate(adjacency); + Graph graph = new AdjacencyListGraph(adjacency); + BronKerboschSolver solver = new BronKerboschSolver(new MaxDegreePivotStrategy()); + return solver.findMaximalCliques(graph); + } +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java b/src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java index f397989911d9..199a51e310f6 100644 --- a/src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java +++ b/src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java @@ -20,7 +20,7 @@ public class ConstrainedShortestPath { */ public static class Graph { - private List> adjacencyList; + private final List> adjacencyList; public Graph(int numNodes) { adjacencyList = new ArrayList<>(); @@ -61,8 +61,8 @@ public record Edge(int from, int to, int cost, int resource) { } } - private Graph graph; - private int maxResource; + private final Graph graph; + private final int maxResource; /** * Constructs a CSPSolver with the given graph and maximum resource constraint. diff --git a/src/main/java/com/thealgorithms/graph/Dinic.java b/src/main/java/com/thealgorithms/graph/Dinic.java index c45bd62ddfbb..0f1917a507cd 100644 --- a/src/main/java/com/thealgorithms/graph/Dinic.java +++ b/src/main/java/com/thealgorithms/graph/Dinic.java @@ -35,85 +35,125 @@ private Dinic() { * indices invalid */ public static int maxFlow(int[][] capacity, int source, int sink) { + validateInput(capacity, source, sink); + + if (source == sink) { + return 0; + } + + int[][] residual = buildResidualGraph(capacity); + return computeMaxFlow(residual, source, sink); + } + + private static void validateInput(int[][] capacity, int source, int sink) { + validateCapacityMatrix(capacity); + validateSourceAndSink(capacity.length, source, sink); + } + + private static void validateCapacityMatrix(int[][] capacity) { if (capacity == null || capacity.length == 0) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } - final int n = capacity.length; - for (int i = 0; i < n; i++) { - if (capacity[i] == null || capacity[i].length != n) { + + int n = capacity.length; + for (int[] ints : capacity) { + if (ints == null || ints.length != n) { throw new IllegalArgumentException("Capacity matrix must be square"); } - for (int j = 0; j < n; j++) { - if (capacity[i][j] < 0) { - throw new IllegalArgumentException("Capacities must be non-negative"); - } + validateNonNegativeRow(ints); + } + } + + private static void validateNonNegativeRow(int[] row) { + for (int value : row) { + if (value < 0) { + throw new IllegalArgumentException("Capacities must be non-negative"); } } - if (source < 0 || sink < 0 || source >= n || sink >= n) { + } + + private static void validateSourceAndSink(int vertexCount, int source, int sink) { + if (source < 0 || sink < 0 || source >= vertexCount || sink >= vertexCount) { throw new IllegalArgumentException("Source and sink must be valid vertex indices"); } - if (source == sink) { - return 0; - } + } - // residual capacities + private static int[][] buildResidualGraph(int[][] capacity) { + int n = capacity.length; int[][] residual = new int[n][n]; for (int i = 0; i < n; i++) { residual[i] = Arrays.copyOf(capacity[i], n); } + return residual; + } + private static int computeMaxFlow(int[][] residual, int source, int sink) { + int n = residual.length; int[] level = new int[n]; int flow = 0; + while (bfsBuildLevelGraph(residual, source, sink, level)) { - int[] next = new int[n]; // current-edge optimization - int pushed; - do { - pushed = dfsBlocking(residual, level, next, source, sink, Integer.MAX_VALUE); - flow += pushed; - } while (pushed > 0); + int[] next = new int[n]; + flow += sendBlockingFlow(residual, level, next, source, sink); } + return flow; } + private static int sendBlockingFlow(int[][] residual, int[] level, int[] next, int source, int sink) { + int totalPushed = 0; + int pushed; + + do { + pushed = dfsBlocking(residual, level, next, source, sink, Integer.MAX_VALUE); + totalPushed += pushed; + } while (pushed > 0); + + return totalPushed; + } + private static boolean bfsBuildLevelGraph(int[][] residual, int source, int sink, int[] level) { Arrays.fill(level, -1); level[source] = 0; - Queue q = new ArrayDeque<>(); - q.add(source); - while (!q.isEmpty()) { - int u = q.poll(); + + Queue queue = new ArrayDeque<>(); + queue.add(source); + + while (!queue.isEmpty()) { + int u = queue.poll(); for (int v = 0; v < residual.length; v++) { if (residual[u][v] > 0 && level[v] == -1) { level[v] = level[u] + 1; if (v == sink) { return true; } - q.add(v); + queue.add(v); } } } + return level[sink] != -1; } - private static int dfsBlocking(int[][] residual, int[] level, int[] next, int u, int sink, int f) { + private static int dfsBlocking(int[][] residual, int[] level, int[] next, int u, int sink, int flow) { if (u == sink) { - return f; + return flow; } - final int n = residual.length; + + int n = residual.length; for (int v = next[u]; v < n; v++, next[u] = v) { - if (residual[u][v] <= 0) { + if (residual[u][v] <= 0 || level[v] != level[u] + 1) { continue; } - if (level[v] != level[u] + 1) { - continue; - } - int pushed = dfsBlocking(residual, level, next, v, sink, Math.min(f, residual[u][v])); + + int pushed = dfsBlocking(residual, level, next, v, sink, Math.min(flow, residual[u][v])); if (pushed > 0) { residual[u][v] -= pushed; residual[v][u] += pushed; return pushed; } } + return 0; } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/graph/EdmondsKarp.java b/src/main/java/com/thealgorithms/graph/EdmondsKarp.java index 59e7b09cb49c..4ca6c2e1d813 100644 --- a/src/main/java/com/thealgorithms/graph/EdmondsKarp.java +++ b/src/main/java/com/thealgorithms/graph/EdmondsKarp.java @@ -37,21 +37,7 @@ public static int maxFlow(int[][] capacity, int source, int sink) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } - final int n = capacity.length; - for (int row = 0; row < n; row++) { - if (capacity[row] == null || capacity[row].length != n) { - throw new IllegalArgumentException("Capacity matrix must be square"); - } - for (int col = 0; col < n; col++) { - if (capacity[row][col] < 0) { - throw new IllegalArgumentException("Capacities must be non-negative"); - } - } - } - - if (source < 0 || source >= n || sink < 0 || sink >= n) { - throw new IllegalArgumentException("Source and sink must be valid vertex indices"); - } + final int n = getN(capacity, source, sink); if (source == sink) { return 0; } @@ -83,6 +69,25 @@ public static int maxFlow(int[][] capacity, int source, int sink) { return maxFlow; } + private static int getN(int[][] capacity, int source, int sink) { + final int n = capacity.length; + for (int[] ints : capacity) { + if (ints == null || ints.length != n) { + throw new IllegalArgumentException("Capacity matrix must be square"); + } + for (int col = 0; col < n; col++) { + if (ints[col] < 0) { + throw new IllegalArgumentException("Capacities must be non-negative"); + } + } + } + + if (source < 0 || source >= n || sink < 0 || sink >= n) { + throw new IllegalArgumentException("Source and sink must be valid vertex indices"); + } + return n; + } + private static boolean bfs(int[][] residual, int source, int sink, int[] parent) { Arrays.fill(parent, -1); parent[source] = source; diff --git a/src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java b/src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java index 82da5c8163e5..96e883e33dac 100644 --- a/src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java +++ b/src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java @@ -7,16 +7,16 @@ import java.util.List; /** - * Implementation of Hierholzer's Algorithm for finding an Eulerian Path or Circuit + * Implementation of Hierholzer's Algorithm for finding a Eulerian Path or Circuit * in a directed graph. * *

- * An Eulerian Circuit is a path that starts and ends at the same vertex + * A Eulerian Circuit is a path that starts and ends at the same vertex * and visits every edge exactly once. *

* *

- * An Eulerian Path visits every edge exactly once but may start and end + * A Eulerian Path visits every edge exactly once but may start and end * at different vertices. *

* @@ -97,7 +97,7 @@ public HierholzerEulerianPath(Graph graph) { } /** - * Finds an Eulerian Path or Circuit using Hierholzer’s Algorithm. + * Finds a Eulerian Path or Circuit using Hierholzer’s Algorithm. * * @return list of vertices representing the Eulerian Path/Circuit, * or an empty list if none exists @@ -225,7 +225,7 @@ private List rotateEulerianCircuitIfNeeded(List path, int[] ou } } - if (preferredStart != -1 && path.get(0) != preferredStart) { + if (preferredStart != -1 && path.getFirst() != preferredStart) { int idx = 0; for (Integer node : path) { // replaced indexed loop if (node == preferredStart) { @@ -235,28 +235,32 @@ private List rotateEulerianCircuitIfNeeded(List path, int[] ou } if (idx > 0) { - List rotated = new ArrayList<>(); - int currentIndex = 0; - for (Integer node : path) { // replaced indexed loop - if (currentIndex >= idx) { - rotated.add(node); - } - currentIndex++; - } - currentIndex = 0; - for (Integer node : path) { // replaced indexed loop - if (currentIndex < idx) { - rotated.add(node); - } - currentIndex++; - } - path = rotated; + path = getIntegerList(path, idx); } } } return path; } + private static List getIntegerList(List path, int idx) { + List rotated = new ArrayList<>(); + int currentIndex = 0; + for (Integer node : path) { // replaced indexed loop + if (currentIndex >= idx) { + rotated.add(node); + } + currentIndex++; + } + currentIndex = 0; + for (Integer node : path) { // replaced indexed loop + if (currentIndex < idx) { + rotated.add(node); + } + currentIndex++; + } + return rotated; + } + /** * Checks weak connectivity (undirected) among vertices that have non-zero degree. * diff --git a/src/main/java/com/thealgorithms/graph/HopcroftKarp.java b/src/main/java/com/thealgorithms/graph/HopcroftKarp.java index 76f7f3eaa3a7..839fdec8c776 100644 --- a/src/main/java/com/thealgorithms/graph/HopcroftKarp.java +++ b/src/main/java/com/thealgorithms/graph/HopcroftKarp.java @@ -7,10 +7,10 @@ /** * Hopcroft–Karp algorithm for maximum bipartite matching. - * + *

* Left part: vertices [0,nLeft-1], Right part: [0,nRight-1]. * Adjacency list: for each left vertex u, list right vertices v it connects to. - * + *

* Time complexity: O(E * sqrt(V)). * * @see diff --git a/src/main/java/com/thealgorithms/graph/StoerWagner.java b/src/main/java/com/thealgorithms/graph/StoerWagner.java index b204834c431a..e0985bc038c0 100644 --- a/src/main/java/com/thealgorithms/graph/StoerWagner.java +++ b/src/main/java/com/thealgorithms/graph/StoerWagner.java @@ -4,8 +4,8 @@ * An implementation of the Stoer-Wagner algorithm to find the global minimum cut of an undirected, weighted graph. * A minimum cut is a partition of the graph's vertices into two disjoint sets with the minimum possible edge weight * sum connecting the two sets. - * - * Wikipedia: https://en.wikipedia.org/wiki/Stoer%E2%80%93Wagner_algorithm + *

+ * Wikipedhttps://en.wikipedia.org/wiki/Stoer%E2%80%93Wagner_algorithm * Time Complexity: O(V^3) where V is the number of vertices. */ public class StoerWagner { diff --git a/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java b/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java index ba75b2f4b1b8..1979bbc707c8 100644 --- a/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java +++ b/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java @@ -8,10 +8,6 @@ /** * 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. - * @return The number of strongly connected components. */ public class StronglyConnectedComponentOptimized { diff --git a/src/main/java/com/thealgorithms/graph/TarjanBridges.java b/src/main/java/com/thealgorithms/graph/TarjanBridges.java index dbe2e710429a..427e362631e5 100644 --- a/src/main/java/com/thealgorithms/graph/TarjanBridges.java +++ b/src/main/java/com/thealgorithms/graph/TarjanBridges.java @@ -80,7 +80,7 @@ private static class BridgeFinder { private final List bridges; private final int[] discoveryTime; private final int[] lowLink; - boolean[] visited; + final boolean[] visited; private int timer; BridgeFinder(int vertexCount, List> adjacencyList, List bridges) { diff --git a/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java b/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java index dfc8386de6ce..a9318c74dee0 100644 --- a/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java +++ b/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java @@ -15,7 +15,7 @@ * All existing edge weights must be non-negative. Zero-weight edges are allowed.

* *

References: - * - Wikipedia: Yen's algorithm (https://en.wikipedia.org/wiki/Yen%27s_algorithm) + * - Wikipedia: Yen's algorithm (...) * - Dijkstra's algorithm for the base shortest path computation.

*/ public final class YensKShortestPaths { diff --git a/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java b/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java index 53181a654215..0c4dc55b8581 100644 --- a/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java +++ b/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java @@ -12,7 +12,7 @@ * *

References: *

    - *
  • https://cp-algorithms.com/graph/01_bfs.html
  • + *
  • ...
  • *
*/ public final class ZeroOneBfs { diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java b/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java index 54ba4eb650a8..6741d978b2f6 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. diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java b/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java index 9535a7c6190e..816b7ecb7c00 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java @@ -7,12 +7,12 @@ * 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 + *

+ * ProbleLink: https://en.wikipedia.org/wiki/Continuous_knapsack_problem */ public final class FractionalKnapsack { private FractionalKnapsack() { diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java b/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java index a4a0366375eb..79bd1071d106 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java @@ -6,7 +6,7 @@ /** * Implementation of the Gale-Shapley Algorithm for Stable Matching. - * Problem link: https://en.wikipedia.org/wiki/Stable_marriage_problem + * Problem link: ... */ public final class GaleShapley { diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java b/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java index ceb664a31e8a..b16b58866a41 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java @@ -11,9 +11,9 @@ private JobSequencing() { // Define a Job class that implements Comparable for sorting by profit in descending order static class Job implements Comparable { - char id; - int deadline; - int profit; + final char id; + final int deadline; + final int profit; // Compare jobs by profit in descending order @Override diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java b/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java index 07bd0b73326f..ddefea867c2f 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,7 +33,7 @@ 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}} diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java b/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java index c7f219ef3eab..ec6c8aef6d12 100644 --- a/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java +++ b/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java @@ -7,11 +7,11 @@ private MinimizingLateness() { } public static class Job { - String jobName; + final String jobName; int startTime = 0; int lateness = 0; - int processingTime; - int deadline; + final int processingTime; + final int deadline; public Job(String jobName, int processingTime, int deadline) { this.jobName = jobName; diff --git a/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java b/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java index 6e8611b86332..4fee4c4f0376 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 - * + *

+ * Refere* 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. @@ -30,10 +30,10 @@ public class CohenSutherland { private static final int TOP = 8; // 1000 // Define the clipping window - double xMin; - double yMin; - double xMax; - double yMax; + final double xMin; + final double yMin; + final double xMax; + final double yMax; public CohenSutherland(double xMin, double yMin, double xMax, double yMax) { this.xMin = xMin; diff --git a/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java b/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java index 723e2bb2fbf9..67d9439de50b 100644 --- a/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java +++ b/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java @@ -14,8 +14,8 @@ * * 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. @@ -23,10 +23,10 @@ public class LiangBarsky { // Define the clipping window - double xMin; - double xMax; - double yMin; - double yMax; + final double xMin; + final double xMax; + final double yMin; + final double yMax; public LiangBarsky(double xMin, double yMin, double xMax, double yMax) { this.xMin = xMin; diff --git a/src/main/java/com/thealgorithms/maths/AbundantNumber.java b/src/main/java/com/thealgorithms/maths/AbundantNumber.java index 804ac4d71477..b945885ffe07 100644 --- a/src/main/java/com/thealgorithms/maths/AbundantNumber.java +++ b/src/main/java/com/thealgorithms/maths/AbundantNumber.java @@ -4,10 +4,10 @@ * In number theory, an abundant number or excessive number is a positive integer for which * the sum of its proper divisors is greater than the number. * Equivalently, it is a number for which the sum of proper divisors (or aliquot sum) is greater than n. - * + *

* The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. - * - * Wiki: https://en.wikipedia.org/wiki/Abundant_number + *

+ Wiki: https://en.wikipedia.org/wiki/Abundant_number */ public final class AbundantNumber { diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index 996843b56826..98211df9ef79 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -7,7 +7,7 @@ * all proper divisors of n, that is, all divisors of n other than n itself. For * example, the proper divisors of 15 (that is, the positive divisors of 15 that * are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + - * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum + * 3 + 5). Wikipedia: ... */ public final class AliquotSum { private AliquotSum() { diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index b30831bfdc58..016870692828 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -13,7 +13,7 @@ * It is unknown if there are infinitely many pairs of amicable numbers. * *

- * link: https://en.wikipedia.org/wiki/Amicable_numbers + * link: ... *

* Simple Example: (220, 284) * 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110} <-SUM = 284 @@ -27,7 +27,7 @@ private AmicableNumber() { * * @param from range start value * @param to range end value (inclusive) - * @return list with amicable numbers found in given range. + * @return set with amicable numbers found in given range. */ public static Set> findAllInRange(int from, int to) { if (from <= 0 || to <= 0 || to < from) { diff --git a/src/main/java/com/thealgorithms/maths/Area.java b/src/main/java/com/thealgorithms/maths/Area.java index 84fc67159379..c588992e3259 100644 --- a/src/main/java/com/thealgorithms/maths/Area.java +++ b/src/main/java/com/thealgorithms/maths/Area.java @@ -21,6 +21,12 @@ private Area() { * String of IllegalArgumentException for base */ private static final String POSITIVE_BASE = "Base must be greater than 0"; + private static final String POSITIVE_SIDE_LENGTH = "Side length must be greater than 0"; + private static final String POSITIVE_LENGTH = "Length must be greater than 0"; + private static final String POSITIVE_WIDTH = "Width must be greater than 0"; + private static final String POSITIVE_SLANT_HEIGHT = "Slant height must be greater than 0"; + private static final String POSITIVE_BASE_1 = "First base must be greater than 0"; + private static final String POSITIVE_BASE_2 = "Second base must be greater than 0"; /** * Calculate the surface area of a cube. @@ -30,7 +36,7 @@ private Area() { */ public static double surfaceAreaCube(final double sideLength) { if (sideLength <= 0) { - throw new IllegalArgumentException("Side length must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_SIDE_LENGTH); } return 6 * sideLength * sideLength; } @@ -43,15 +49,15 @@ public static double surfaceAreaCube(final double sideLength) { * @param height height of the cuboid * @return surface area of given cuboid */ - public static double surfaceAreaCuboid(final double length, double width, double height) { + public static double surfaceAreaCuboid(final double length, final double width,final double height) { if (length <= 0) { - throw new IllegalArgumentException("Length must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_LENGTH); } if (width <= 0) { - throw new IllegalArgumentException("Width must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_WIDTH); } if (height <= 0) { - throw new IllegalArgumentException("Height must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_HEIGHT); } return 2 * (length * width + length * height + width * height); } @@ -78,10 +84,10 @@ public static double surfaceAreaSphere(final double radius) { */ public static double surfaceAreaPyramid(final double sideLength, final double slantHeight) { if (sideLength <= 0) { - throw new IllegalArgumentException(""); + throw new IllegalArgumentException(POSITIVE_SIDE_LENGTH); } if (slantHeight <= 0) { - throw new IllegalArgumentException("slant height must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_SLANT_HEIGHT); } double baseArea = sideLength * sideLength; double lateralSurfaceArea = 2 * sideLength * slantHeight; @@ -93,14 +99,14 @@ public static double surfaceAreaPyramid(final double sideLength, final double sl * * @param length length of a rectangle * @param width width of a rectangle - * @return area of given rectangle + * @return surface area of given rectangle */ public static double surfaceAreaRectangle(final double length, final double width) { if (length <= 0) { - throw new IllegalArgumentException("Length must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_LENGTH); } if (width <= 0) { - throw new IllegalArgumentException("Width must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_WIDTH); } return length * width; } @@ -108,9 +114,9 @@ public static double surfaceAreaRectangle(final double length, final double widt /** * Calculate surface area of a cylinder. * - * @param radius radius of the floor + * @param radius radius of the base circle * @param height height of the cylinder. - * @return volume of given cylinder + * @return surface area of given cylinder */ public static double surfaceAreaCylinder(final double radius, final double height) { if (radius <= 0) { @@ -126,11 +132,11 @@ public static double surfaceAreaCylinder(final double radius, final double heigh * Calculate the area of a square. * * @param sideLength side length of square - * @return area of given square + * @return surface area of given square */ public static double surfaceAreaSquare(final double sideLength) { if (sideLength <= 0) { - throw new IllegalArgumentException("Side Length must be greater than 0"); + throw new IllegalArgumentException(POSITIVE_SIDE_LENGTH); } return sideLength * sideLength; } @@ -138,9 +144,9 @@ public static double surfaceAreaSquare(final double sideLength) { /** * Calculate the area of a triangle. * - * @param base base of triangle + * @param baseLength base of triangle * @param height height of triangle - * @return area of given triangle + * @return surface area of given triangle */ public static double surfaceAreaTriangle(final double baseLength, final double height) { if (baseLength <= 0) { @@ -155,9 +161,9 @@ public static double surfaceAreaTriangle(final double baseLength, final double h /** * Calculate the area of a parallelogram. * - * @param base base of a parallelogram + * @param baseLength base of a parallelogram * @param height height of a parallelogram - * @return area of given parallelogram + * @return surface area of given parallelogram */ public static double surfaceAreaParallelogram(final double baseLength, final double height) { if (baseLength <= 0) { @@ -172,17 +178,17 @@ public static double surfaceAreaParallelogram(final double baseLength, final dou /** * Calculate the area of a trapezium. * - * @param base1 upper base of trapezium - * @param base2 bottom base of trapezium + * @param baseLength1 upper base of trapezium + * @param baseLength2 bottom base of trapezium * @param height height of trapezium - * @return area of given trapezium + * @return surface area of given trapezium */ public static double surfaceAreaTrapezium(final double baseLength1, final double baseLength2, final double height) { if (baseLength1 <= 0) { - throw new IllegalArgumentException(POSITIVE_BASE + 1); + throw new IllegalArgumentException(POSITIVE_BASE_1 ); } if (baseLength2 <= 0) { - throw new IllegalArgumentException(POSITIVE_BASE + 2); + throw new IllegalArgumentException(POSITIVE_BASE_2 ); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); @@ -194,10 +200,10 @@ public static double surfaceAreaTrapezium(final double baseLength1, final double * Calculate the area of a circle. * * @param radius radius of circle - * @return area of given circle + * @return surface area of given circle */ public static double surfaceAreaCircle(final double radius) { - if (radius <= 0) { + if (radius <= 0.0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } return Math.PI * radius * radius; @@ -210,7 +216,7 @@ public static double surfaceAreaCircle(final double radius) { * @return surface area of given hemisphere */ public static double surfaceAreaHemisphere(final double radius) { - if (radius <= 0) { + if (radius <= 0.0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } return 3 * Math.PI * radius * radius; @@ -224,10 +230,10 @@ public static double surfaceAreaHemisphere(final double radius) { * @return surface area of given cone. */ public static double surfaceAreaCone(final double radius, final double height) { - if (radius <= 0) { + if (radius <= 0.0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } - if (height <= 0) { + if (height <= 0.0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return Math.PI * radius * (radius + Math.pow(height * height + radius * radius, 0.5)); diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index 9a7a014ec99f..d4de9e99d7bb 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/ChebyshevIteration.java b/src/main/java/com/thealgorithms/maths/ChebyshevIteration.java index bc30f1ba6e7e..005799957ee0 100644 --- a/src/main/java/com/thealgorithms/maths/ChebyshevIteration.java +++ b/src/main/java/com/thealgorithms/maths/ChebyshevIteration.java @@ -14,7 +14,7 @@ * m(A) (smallest eigenvalue) and M(A) (largest eigenvalue). * *

- * Wikipedia: https://en.wikipedia.org/wiki/Chebyshev_iteration + * Wikipedia: ... * * @author Mitrajit Ghorui(KeyKyrios) */ @@ -54,7 +54,7 @@ public static double[] solve(double[][] a, double[] b, double[] x0, double minEi double d = (maxEigenvalue + minEigenvalue) / 2.0; double c = (maxEigenvalue - minEigenvalue) / 2.0; - double alpha = 0.0; + double alpha; double alphaPrev = 0.0; for (int k = 0; k < maxIterations; k++) { diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java index 87fc5af57b8d..9d15883ffc34 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -35,7 +35,7 @@ private static void padding(Collection x, int newSize) { * FFT algorithm for faster calculations of the two DFTs and the final IDFT. * *

- * More info: https://en.wikipedia.org/wiki/Convolution_theorem + * More info: ... * * @param a The first signal. * @param b The other signal. diff --git a/src/main/java/com/thealgorithms/maths/Combinations.java b/src/main/java/com/thealgorithms/maths/Combinations.java index 2b4a78613190..34fca3a20cef 100644 --- a/src/main/java/com/thealgorithms/maths/Combinations.java +++ b/src/main/java/com/thealgorithms/maths/Combinations.java @@ -40,8 +40,6 @@ public static long combinations(int n, int k) { * Using this base value and above formula we can compute the next term * nC(k+1) * - * @param n - * @param k * @return nCk */ public static long combinationsOptimized(int n, int k) { diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index ed1ba1bbefc3..ac2fe09b1583 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -38,8 +38,8 @@ private static void padding(Collection x, int newSize) { * for faster calculations of the two DFTs and the final IDFT. * *

- * More info: https://en.wikipedia.org/wiki/Convolution_theorem - * https://ccrma.stanford.edu/~jos/ReviewFourier/FFT_Convolution.html + * More info: ... + * ... * * @param a The first signal. * @param b The other signal. diff --git a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java index b652d4903da8..8d429c993f0f 100644 --- a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java +++ b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java @@ -18,8 +18,8 @@ private DeterminantOfMatrix() { static int determinant(int[][] a, int n) { int det = 0; int sign = 1; - int p = 0; - int q = 0; + int p; + int q; if (n == 1) { det = a[0][0]; } else { diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java index e8f5305c7569..a7f5cc3269fa 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 diff --git a/src/main/java/com/thealgorithms/maths/DistanceBetweenTwoPoints.java b/src/main/java/com/thealgorithms/maths/DistanceBetweenTwoPoints.java index cd1c9205b328..acc34a633401 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceBetweenTwoPoints.java +++ b/src/main/java/com/thealgorithms/maths/DistanceBetweenTwoPoints.java @@ -8,7 +8,7 @@ * *

Formula: d = sqrt((x2 - x1)^2 + (y2 - y1)^2) * - *

Reference: https://en.wikipedia.org/wiki/Euclidean_distance + *

Reference: ... */ public final class DistanceBetweenTwoPoints { diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index f7e2c7629551..28771ae149ac 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -29,7 +29,7 @@ public static int hammingDistance(int[] b1, int[] b2) { } public static double minkowskiDistance(double[] p1, double[] p2, int p) { - double d = 0; + double d; double distance = 0.0; if (p1.length != p2.length) { diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index 3663b6c534aa..728af7291862 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -12,8 +12,8 @@ * is calculated by evaluating the differential equation at the previous step, * multiplying the result with the step-size and adding it to the last y-value: * y_n+1 = y_n + stepSize * f(x_n, y_n). (description adapted from - * https://en.wikipedia.org/wiki/Euler_method ) (see also: - * https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ ) + * ... ) (see also: + * ... ) */ public final class EulerMethod { private EulerMethod() { diff --git a/src/main/java/com/thealgorithms/maths/EulerPseudoprime.java b/src/main/java/com/thealgorithms/maths/EulerPseudoprime.java index 9a03f4e21d17..7341de13f48c 100644 --- a/src/main/java/com/thealgorithms/maths/EulerPseudoprime.java +++ b/src/main/java/com/thealgorithms/maths/EulerPseudoprime.java @@ -5,12 +5,12 @@ /** * The {@code EulerPseudoprime} class implements the Euler primality test. - * + *

* It is based on Euler’s criterion: * For an odd prime number {@code n} and any integer {@code a} coprime to {@code n}: * a^((n-1)/2) ≡ (a/n) (mod n) * where (a/n) is the Jacobi symbol. - * + *

* This algorithm is a stronger probabilistic test than Fermat’s test. * It may still incorrectly identify a composite as “probably prime” (Euler pseudoprime), * but such cases are rare. diff --git a/src/main/java/com/thealgorithms/maths/EvilNumber.java b/src/main/java/com/thealgorithms/maths/EvilNumber.java index 419133702fd4..2b6c80cf09e6 100644 --- a/src/main/java/com/thealgorithms/maths/EvilNumber.java +++ b/src/main/java/com/thealgorithms/maths/EvilNumber.java @@ -3,9 +3,9 @@ /** * In number theory, an evil number is a non-negative integer that has an even number of 1s in its binary expansion. * Non-negative integers that are not evil are called odious numbers. - * - * Evil Number Wiki: https://en.wikipedia.org/wiki/Evil_number - * Odious Number Wiki: https://en.wikipedia.org/wiki/Odious_number + *

+ * Evil Number Wihttps://en.wikipedia.org/wiki/Evil_number + * Odious Number Wihttps://en.wikipedia.org/wiki/Odious_number */ public final class EvilNumber { diff --git a/src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java b/src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java index 4934d4493bf2..0649708df4e5 100644 --- a/src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java +++ b/src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java @@ -8,7 +8,7 @@ * *

* For more details, see - * https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm + * ... */ public final class ExtendedEuclideanAlgorithm { @@ -40,9 +40,8 @@ public static long[] extendedGCD(long a, long b) { long y1 = result[2]; // Update coefficients using the results from the recursive call - long x = y1; long y = x1 - a / b * y1; - return new long[] {gcd, x, y}; + return new long[] {gcd, y1, y}; } } diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java index 91754bd1a80b..f0a3ff5f0522 100644 --- a/src/main/java/com/thealgorithms/maths/FFT.java +++ b/src/main/java/com/thealgorithms/maths/FFT.java @@ -21,7 +21,7 @@ private FFT() { * *

* More info: - * https://introcs.cs.princeton.edu/java/32class/Complex.java.html + * ... */ static class Complex { @@ -183,14 +183,13 @@ public double imaginary() { * *

* More info: - * https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html - * 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 inverse True if you want to find the inverse FFT. - * @return */ public static ArrayList fft(ArrayList x, boolean inverse) { /* Pad the signal with zeros if necessary */ @@ -260,8 +259,8 @@ public static ArrayList inverseFFT(int n, boolean inverse, ArrayList - * More info: https://cp-algorithms.com/algebra/fft.html - * https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/ + * More info: ... + * ... * * @param num The integer you want to reverse its bits. * @param log2n The number of bits you want to reverse. diff --git a/src/main/java/com/thealgorithms/maths/FFTBluestein.java b/src/main/java/com/thealgorithms/maths/FFTBluestein.java index 7a03c20cc642..7c81f5416c4a 100644 --- a/src/main/java/com/thealgorithms/maths/FFTBluestein.java +++ b/src/main/java/com/thealgorithms/maths/FFTBluestein.java @@ -19,8 +19,8 @@ private FFTBluestein() { * *

* More info: - * https://en.wikipedia.org/wiki/Chirp_Z-transform#Bluestein.27s_algorithm - * http://tka4.org/materials/lib/Articles-Books/Numerical%20Algorithms/Hartley_Trasform/Bluestein%27s%20FFT%20algorithm%20-%20Wikipedia,%20the%20free%20encyclopedia.htm + * ... + * ... * * @param x The discrete signal which is then converted to the FFT or the * IFFT of signal x. diff --git a/src/main/java/com/thealgorithms/maths/FastExponentiation.java b/src/main/java/com/thealgorithms/maths/FastExponentiation.java index 27f49e27ff30..4cbf081b0846 100644 --- a/src/main/java/com/thealgorithms/maths/FastExponentiation.java +++ b/src/main/java/com/thealgorithms/maths/FastExponentiation.java @@ -14,8 +14,8 @@ *

* *

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} + /** + * For more information, please visit Exponentiation by Squaring */ public final class FastExponentiation { diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java index 01a52b913d30..48dbff494f9e 100644 --- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java +++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java @@ -12,7 +12,7 @@ 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..a8c6cef46ad7 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java @@ -27,7 +27,7 @@ public static boolean isPerfectSquare(long number) { * @param number the number * @return true if {@code number} is a Fibonacci number, otherwise * false - * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification + * @link ... */ public static boolean isFibonacciNumber(long number) { long value1 = 5 * number * number + 4; diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index df27516367b2..d92ad8a49b85 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -2,14 +2,14 @@ /** * 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. - * + *

* Example usage: *

  * int result1 = GCD.gcd(48, 18);
diff --git a/src/main/java/com/thealgorithms/maths/GCDRecursion.java b/src/main/java/com/thealgorithms/maths/GCDRecursion.java
index e95ce97c8a04..6c251654f27b 100644
--- a/src/main/java/com/thealgorithms/maths/GCDRecursion.java
+++ b/src/main/java/com/thealgorithms/maths/GCDRecursion.java
@@ -1,7 +1,7 @@
 package com.thealgorithms.maths;
 
 /**
- * @author https://github.com/shellhub/
+ * @author ...
  */
 public final class GCDRecursion {
     private GCDRecursion() {
diff --git a/src/main/java/com/thealgorithms/maths/Gaussian.java b/src/main/java/com/thealgorithms/maths/Gaussian.java
index 1e02579757cc..b3095437cd1f 100644
--- a/src/main/java/com/thealgorithms/maths/Gaussian.java
+++ b/src/main/java/com/thealgorithms/maths/Gaussian.java
@@ -9,7 +9,7 @@ private Gaussian() {
 
     public static ArrayList gaussian(int matSize, List matrix) {
         int i;
-        int j = 0;
+        int j;
 
         double[][] mat = new double[matSize + 1][matSize + 1];
         double[][] x = new double[matSize][matSize + 1];
@@ -21,14 +21,15 @@ public static ArrayList gaussian(int matSize, List matrix) {
             }
         }
 
-        mat = gaussianElimination(matSize, i, mat);
+        mat = gaussianElimination(matSize, mat);
         return valueOfGaussian(matSize, x, mat);
     }
 
     // Perform Gaussian elimination
-    public static double[][] gaussianElimination(int matSize, int i, double[][] mat) {
-        int step = 0;
+    public static double[][] gaussianElimination(int matSize, double[][] mat) {
+        int step;
         for (step = 0; step < matSize - 1; step++) {
+            int i;
             for (i = step; i < matSize - 1; i++) {
                 double a = (mat[i + 1][step] / mat[step][step]);
 
diff --git a/src/main/java/com/thealgorithms/maths/GenericRoot.java b/src/main/java/com/thealgorithms/maths/GenericRoot.java
index e13efe5a77e0..89e9d0653385 100644
--- a/src/main/java/com/thealgorithms/maths/GenericRoot.java
+++ b/src/main/java/com/thealgorithms/maths/GenericRoot.java
@@ -8,7 +8,7 @@
  * then 1 + 5 = 6, so the generic root is 6.
  * 

* Reference: - * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/ + * ... */ public final class GenericRoot { diff --git a/src/main/java/com/thealgorithms/maths/GoldbachConjecture.java b/src/main/java/com/thealgorithms/maths/GoldbachConjecture.java index 4e962722ba88..4d48d0750467 100644 --- a/src/main/java/com/thealgorithms/maths/GoldbachConjecture.java +++ b/src/main/java/com/thealgorithms/maths/GoldbachConjecture.java @@ -5,8 +5,8 @@ /** * This is a representation of the unsolved problem of Goldbach's Projection, according to which every * even natural number greater than 2 can be written as the sum of 2 prime numbers - * More info: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture - * @author Vasilis Sarantidis (https://github.com/BILLSARAN) + * More info: ... + * @author Vasilis Sarantidis (...) */ public final class GoldbachConjecture { diff --git a/src/main/java/com/thealgorithms/maths/HappyNumber.java b/src/main/java/com/thealgorithms/maths/HappyNumber.java index bfe746953b33..835d08b91410 100644 --- a/src/main/java/com/thealgorithms/maths/HappyNumber.java +++ b/src/main/java/com/thealgorithms/maths/HappyNumber.java @@ -38,7 +38,7 @@ public static boolean isHappy(int n) { /** * Calculates the sum of squares of the digits of a number. - * + *

* Example: * num = 82 → 8² + 2² = 64 + 4 = 68 * diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java index 98d839011a7f..c34207503e2a 100644 --- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java +++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java @@ -24,7 +24,8 @@ private JosephusProblem() { /** * Find the Winner of the Circular Game. * - * @param number of friends, n, and an integer k + * @param n number of friends + * @param k an integer * @return return the winner of the game */ diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index 99842e2f4f5e..7206905becf7 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -25,7 +25,7 @@ * * @see Kaprekar Number * - Wikipedia - * @author TheAlgorithms (https://github.com/TheAlgorithms) + * @author TheAlgorithms (...) */ public final class KaprekarNumbers { private KaprekarNumbers() { diff --git a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java index 9ec11e9b3220..5b9f94c1b7f2 100644 --- a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java +++ b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java @@ -3,7 +3,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 { @@ -30,12 +30,14 @@ public static int lcm(int num1, int num2) { num3 = num2; } - while (num1 != 0) { - if (high % num1 == 0 && high % num2 == 0) { - cmv = high; - break; + if (num1 != 0) { + while (true) { + if (high % num1 == 0 && high % num2 == 0) { + cmv = high; + break; + } + high += num3; } - high += num3; } return cmv; } diff --git a/src/main/java/com/thealgorithms/maths/LongDivision.java b/src/main/java/com/thealgorithms/maths/LongDivision.java index 45e97b1c14c3..6592a3682578 100644 --- a/src/main/java/com/thealgorithms/maths/LongDivision.java +++ b/src/main/java/com/thealgorithms/maths/LongDivision.java @@ -29,6 +29,23 @@ public static int divide(int dividend, int divisor) { return 0; } + StringBuilder answer = getStringBuilder(newDividend1, newDivisor1); + + if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) { + try { + return Integer.parseInt(answer.toString()) * (-1); + } catch (NumberFormatException e) { + return -2147483648; + } + } + try { + return Integer.parseInt(answer.toString()); + } catch (NumberFormatException e) { + return 2147483647; + } + } + + private static StringBuilder getStringBuilder(long newDividend1, long newDivisor1) { StringBuilder answer = new StringBuilder(); String dividendString = "" + newDividend1; @@ -37,7 +54,7 @@ public static int divide(int dividend, int divisor) { String remainder = ""; for (int i = 0; i < dividendString.length(); i++) { - String partV1 = remainder + "" + dividendString.substring(lastIndex, i + 1); + String partV1 = remainder + dividendString.substring(lastIndex, i + 1); long part1 = Long.parseLong(partV1); if (part1 > newDivisor1) { int quotient = 0; @@ -55,7 +72,7 @@ public static int divide(int dividend, int divisor) { answer.append(quotient); } else if (part1 == 0) { answer.append(0); - } else if (part1 < newDivisor1) { + } else { answer.append(0); } if (!(part1 == 0)) { @@ -66,18 +83,6 @@ public static int divide(int dividend, int divisor) { lastIndex++; } - - if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) { - try { - return Integer.parseInt(answer.toString()) * (-1); - } catch (NumberFormatException e) { - return -2147483648; - } - } - try { - return Integer.parseInt(answer.toString()); - } catch (NumberFormatException e) { - return 2147483647; - } + return answer; } } diff --git a/src/main/java/com/thealgorithms/maths/LuckyNumber.java b/src/main/java/com/thealgorithms/maths/LuckyNumber.java index 70308e1e0edd..24e3b0c9b98f 100644 --- a/src/main/java/com/thealgorithms/maths/LuckyNumber.java +++ b/src/main/java/com/thealgorithms/maths/LuckyNumber.java @@ -5,8 +5,8 @@ * This sieve is similar to the sieve of Eratosthenes that generates the primes, * but it eliminates numbers based on their position in the remaining set, * instead of their value (or position in the initial set of natural numbers). - * - * Wiki: https://en.wikipedia.org/wiki/Lucky_number + *

+ * Wihttps://en.wikipedia.org/wiki/Lucky_number */ public final class LuckyNumber { diff --git a/src/main/java/com/thealgorithms/maths/MathBuilder.java b/src/main/java/com/thealgorithms/maths/MathBuilder.java index 1cf3d8b7fc9a..5648c403a2f2 100644 --- a/src/main/java/com/thealgorithms/maths/MathBuilder.java +++ b/src/main/java/com/thealgorithms/maths/MathBuilder.java @@ -6,7 +6,7 @@ import java.util.function.Function; /** - * Author: Sadiul Hakim : https://github.com/sadiul-hakim + * Author: Sadiul Hakim : ... * Profession: Backend Engineer * Date: Oct 20, 2024 */ diff --git a/src/main/java/com/thealgorithms/maths/Means.java b/src/main/java/com/thealgorithms/maths/Means.java index d77eb1d3f661..2e90437675e6 100644 --- a/src/main/java/com/thealgorithms/maths/Means.java +++ b/src/main/java/com/thealgorithms/maths/Means.java @@ -1,8 +1,5 @@ package com.thealgorithms.maths; -import java.util.stream.StreamSupport; -import org.apache.commons.collections4.IterableUtils; - /** * Utility class for computing various types of statistical means. *

@@ -47,10 +44,15 @@ private Means() { * Mean */ public static Double arithmetic(final Iterable numbers) { - checkIfNotEmpty(numbers); - double sum = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + y); - int size = IterableUtils.size(numbers); - return sum / size; + checkNotNull(numbers); + double sum = 0.0; + int count = 0; + for (Double num : numbers) { + sum += num; + count++; + } + checkNotEmpty(count); + return sum / count; } /** @@ -74,10 +76,18 @@ public static Double arithmetic(final Iterable numbers) { * Mean */ public static Double geometric(final Iterable numbers) { - checkIfNotEmpty(numbers); - double product = StreamSupport.stream(numbers.spliterator(), false).reduce(1d, (x, y) -> x * y); - int size = IterableUtils.size(numbers); - return Math.pow(product, 1.0 / size); + checkNotNull(numbers); + double product = 1.0; + int count = 0; + for (Double num : numbers) { + if (num < 0) { + throw new IllegalArgumentException("Geometric mean requires non-negative numbers"); + } + product *= num; + count++; + } + checkNotEmpty(count); + return Math.pow(product, 1.0 / count); } /** @@ -101,10 +111,18 @@ public static Double geometric(final Iterable numbers) { * @see Harmonic Mean */ public static Double harmonic(final Iterable numbers) { - checkIfNotEmpty(numbers); - double sumOfReciprocals = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + 1d / y); - int size = IterableUtils.size(numbers); - return size / sumOfReciprocals; + checkNotNull(numbers); + double sumOfReciprocals = 0.0; + int count = 0; + for (Double num : numbers) { + if (num == 0.0) { + throw new IllegalArgumentException("Harmonic mean cannot contain zero values"); + } + sumOfReciprocals += 1.0 / num; + count++; + } + checkNotEmpty(count); + return count / sumOfReciprocals; } /** @@ -123,10 +141,15 @@ public static Double harmonic(final Iterable numbers) { * Mean */ public static Double quadratic(final Iterable numbers) { - checkIfNotEmpty(numbers); - double sumOfSquares = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + y * y); - int size = IterableUtils.size(numbers); - return Math.pow(sumOfSquares / size, 0.5); + checkNotNull(numbers); + double sumOfSquares = 0.0; + int count = 0; + for (Double num : numbers) { + sumOfSquares += num * num; + count++; + } + checkNotEmpty(count); + return Math.sqrt(sumOfSquares / count); } /** @@ -135,9 +158,15 @@ public static Double quadratic(final Iterable numbers) { * @param numbers the input numbers to validate * @throws IllegalArgumentException if the input is empty */ - private static void checkIfNotEmpty(final Iterable numbers) { - if (!numbers.iterator().hasNext()) { - throw new IllegalArgumentException("Empty list given for Mean computation."); + private static void checkNotNull(final Iterable numbers) { + if (numbers == null) { + throw new IllegalArgumentException("Input iterable must not be null"); + } + } + + private static void checkNotEmpty(final int count) { + if (count == 0) { + throw new IllegalArgumentException("Input iterable must not be empty"); } } } diff --git a/src/main/java/com/thealgorithms/maths/Neville.java b/src/main/java/com/thealgorithms/maths/Neville.java index ca45f2e8a042..96af22cbbaf1 100644 --- a/src/main/java/com/thealgorithms/maths/Neville.java +++ b/src/main/java/com/thealgorithms/maths/Neville.java @@ -10,7 +10,7 @@ * computes the value of this polynomial at a given point. * *

- * Wikipedia: https://en.wikipedia.org/wiki/Neville%27s_algorithm + * Wikipedia: ... * * @author Mitrajit Ghorui(KeyKyrios) */ 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 2da22c4c8696..1e46aff10612 100644 --- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java +++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java @@ -1,80 +1,207 @@ package com.thealgorithms.maths; -import static java.util.Collections.singletonList; - import java.util.ArrayList; -import java.util.Map; -import org.apache.commons.lang3.tuple.MutablePair; +import java.util.Collections; +import java.util.List; /** - * @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 + * Computes the n-th ugly number (sorted ascending) for a given set of base factors. + * + *

Ugly numbers are all positive integers expressible as a product of non-negative + * powers of the given base factors. For example: + *

    + *
  • Base [2, 3, 5] produces the 5-smooth numbers: 1, 2, 3, 4, 5, 6, 8, 9, 10, ... + * (see OEIS A051037)
  • + *
  • Base [2, 3, 5, 7] produces the 7-smooth numbers + * (see OEIS A002473)
  • + *
  • Base [2] produces non-negative powers of 2.
  • + *
+ * + *

Design notes (SOLID): + *

    + *
  • SRP: Candidate generation is isolated in {@link BaseFactorCursor}; + * caching/sequencing lives only in {@link UglyNumberCache}; + * this class is a thin public facade.
  • + *
  • OCP: The candidate-selection strategy is expressed through + * {@link CandidateSelector}, making it open for extension without modifying + * this class.
  • + *
  • DIP: No dependency on Apache Commons or any concrete library type; + * all collaborators are either JDK types or local abstractions.
  • + *
*/ public class NthUglyNumber { - private ArrayList uglyNumbers = new ArrayList<>(singletonList(1L)); - private ArrayList> positions = new ArrayList<>(); + + private final UglyNumberCache cache; /** - * @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 + * Constructs an instance for the given base factors. + * + * @param baseFactors non-empty array of positive integers that form the multiplication base + * @throws IllegalArgumentException if {@code baseFactors} is empty */ - NthUglyNumber(final int[] baseNumbers) { - if (baseNumbers.length == 0) { - throw new IllegalArgumentException("baseNumbers must be non-empty."); - } - - for (final var baseNumber : baseNumbers) { - this.positions.add(MutablePair.of(baseNumber, 0)); + public NthUglyNumber(final int[] baseFactors) { + if (baseFactors == null || baseFactors.length == 0) { + throw new IllegalArgumentException("baseFactors must be non-empty."); } + List cursors = buildCursors(baseFactors); + this.cache = new UglyNumberCache(cursors, new MinimalCandidateSelector()); } /** - * @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) + * Returns the n-th ugly number (zero-based index; index 0 returns 1). + * + * @param n zero-based index; must be non-negative + * @return the n-th ugly number + * @throws IllegalArgumentException if {@code n} is negative */ - public Long get(final int n) { + public long get(final int n) { if (n < 0) { throw new IllegalArgumentException("n must be non-negative."); } + return cache.get(n); + } - while (uglyNumbers.size() <= n) { - addUglyNumber(); + // ------------------------------------------------------------------------- + // Private factory helper + // ------------------------------------------------------------------------- + + private static List buildCursors(final int[] baseFactors) { + List cursors = new ArrayList<>(baseFactors.length); + for (int factor : baseFactors) { + cursors.add(new BaseFactorCursor(factor)); } + return Collections.unmodifiableList(cursors); + } + + // ========================================================================= + // SRP helper 1 — tracks one base factor and its current index in the cache + // ========================================================================= - return uglyNumbers.get(n); + /** + * Encapsulates a single base factor and a pointer into the ugly-number sequence. + * Knows how to compute its next candidate and advance its pointer. + */ + static final class BaseFactorCursor { + + private final int factor; + private int index; // points to the ugly number this cursor will multiply next + + BaseFactorCursor(final int factor) { + this.factor = factor; + this.index = 0; + } + + /** + * Computes the candidate produced by this cursor: factor × uglyNumbers[index]. + * + * @param uglyNumbers the current list of computed ugly numbers + * @return the candidate value + */ + long candidate(final List uglyNumbers) { + return (long) factor * uglyNumbers.get(index); + } + + /** + * Advances the internal pointer if the supplied value equals this cursor's + * current candidate, ensuring no duplicate ugly number is produced. + * + * @param lastAdded the value most recently appended to the ugly-number sequence + * @param uglyNumbers the current list of computed ugly numbers + */ + void advanceIfMatch(final long lastAdded, final List uglyNumbers) { + if (candidate(uglyNumbers) == lastAdded) { + index++; + } + } } - private void addUglyNumber() { - uglyNumbers.add(computeMinimalCandidate()); - updatePositions(); + // ========================================================================= + // SRP helper 2 — strategy abstraction for picking the next ugly number + // ========================================================================= + + /** + * Strategy for selecting the next ugly number from a set of cursors. + * Implement this interface to swap in alternative selection algorithms + * (e.g. a heap-based selector) without touching {@link UglyNumberCache}. + */ + interface CandidateSelector { + /** + * @param cursors current cursor state + * @param uglyNumbers accumulated ugly numbers so far + * @return the smallest candidate across all cursors + */ + long selectNext(List cursors, List uglyNumbers); } - private void updatePositions() { - final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1); - for (var entry : positions) { - if (computeCandidate(entry) == lastUglyNumber) { - entry.setValue(entry.getValue() + 1); + // ========================================================================= + // OCP — concrete selector; extend by providing a different CandidateSelector + // ========================================================================= + + /** + * Default {@link CandidateSelector} that performs a linear scan to find the + * minimum candidate. O(k) per step, where k is the number of base factors. + */ + static final class MinimalCandidateSelector implements CandidateSelector { + + @Override + public long selectNext(final List cursors, + final List uglyNumbers) { + long minimum = Long.MAX_VALUE; + for (BaseFactorCursor cursor : cursors) { + minimum = Math.min(minimum, cursor.candidate(uglyNumbers)); } + return minimum; } } - private long computeCandidate(final Map.Entry entry) { - return entry.getKey() * uglyNumbers.get(entry.getValue()); - } + // ========================================================================= + // SRP helper 3 — owns the cached sequence and the generation loop + // ========================================================================= + + /** + * Maintains the lazily-grown list of ugly numbers and delegates candidate + * selection to the injected {@link CandidateSelector}. + * + *

Responsibilities: caching, growth, and cursor synchronisation only. + * It does not know how to pick the next value; that belongs to the selector. + */ + static final class UglyNumberCache { - private long computeMinimalCandidate() { - long res = Long.MAX_VALUE; - for (final var entry : positions) { - res = Math.min(res, computeCandidate(entry)); + private final List uglyNumbers = new ArrayList<>(); + private final List cursors; + private final CandidateSelector selector; + + UglyNumberCache(final List cursors, + final CandidateSelector selector) { + this.cursors = cursors; + this.selector = selector; + uglyNumbers.add(1L); // 1 is always the first ugly number + } + + /** + * Returns the n-th ugly number, growing the cache as needed. + */ + long get(final int n) { + while (uglyNumbers.size() <= n) { + growByOne(); + } + return uglyNumbers.get(n); + } + + private void growByOne() { + long next = selector.selectNext(cursors, uglyNumbers); + uglyNumbers.add(next); + advanceMatchingCursors(next); + } + + /** + * Advances every cursor whose candidate equals the value just appended, + * which prevents duplicates in the sequence. + */ + private void advanceMatchingCursors(final long justAdded) { + for (BaseFactorCursor cursor : cursors) { + cursor.advanceIfMatch(justAdded, uglyNumbers); + } } - return res; } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index 9a9d4450cb98..5a8bffcf8480 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -9,7 +9,7 @@ private PascalTriangle() { *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 @@ -20,7 +20,7 @@ private PascalTriangle() { *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 + * li...ngle * *

* Example:- diff --git a/src/main/java/com/thealgorithms/maths/PerfectCube.java b/src/main/java/com/thealgorithms/maths/PerfectCube.java index 4104c6238580..1b6df9f2e93f 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectCube.java +++ b/src/main/java/com/thealgorithms/maths/PerfectCube.java @@ -1,7 +1,7 @@ package com.thealgorithms.maths; /** - * https://en.wikipedia.org/wiki/Cube_(algebra) + * ... */ public final class PerfectCube { private PerfectCube() { diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java index f299d08e5d27..3b101a3db035 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -5,8 +5,8 @@ * 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 + *

+ * l...mber */ public final class PerfectNumber { private PerfectNumber() { diff --git a/src/main/java/com/thealgorithms/maths/PerfectSquare.java b/src/main/java/com/thealgorithms/maths/PerfectSquare.java index aec43062121a..9e7c314bb3be 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectSquare.java +++ b/src/main/java/com/thealgorithms/maths/PerfectSquare.java @@ -1,7 +1,7 @@ package com.thealgorithms.maths; /** - * https://en.wikipedia.org/wiki/Perfect_square + * ... */ public final class PerfectSquare { private PerfectSquare() { diff --git a/src/main/java/com/thealgorithms/maths/PerrinNumber.java b/src/main/java/com/thealgorithms/maths/PerrinNumber.java index cee45a1c5538..563a9ec592cc 100644 --- a/src/main/java/com/thealgorithms/maths/PerrinNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerrinNumber.java @@ -5,7 +5,7 @@ * The Perrin Sequence is a sequence of integers defined by the recurrence relation: * P(n) = P(n-2) + P(n-3) with initial values P(0) = 3, P(1) = 0, P(2) = 2. * Example: 3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39, 51... - * + *

* Note: The Perrin Sequence uses the same recurrence relation as the Padovan Sequence * but has different initial values. * diff --git a/src/main/java/com/thealgorithms/maths/PiApproximation.java b/src/main/java/com/thealgorithms/maths/PiApproximation.java index 1be945d7ef24..4b4e5018c002 100644 --- a/src/main/java/com/thealgorithms/maths/PiApproximation.java +++ b/src/main/java/com/thealgorithms/maths/PiApproximation.java @@ -5,7 +5,7 @@ /** * Implementation to calculate an estimate of the number π (Pi). - * + *

* We take a random point P with coordinates (x, y) such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. * If x² + y² ≤ 1, then the point is inside the quarter disk of radius 1, * else the point is outside. We know that the probability of the point being @@ -25,8 +25,8 @@ private PiApproximation() { * where 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. */ static class Point { - double x; - double y; + final double x; + final double y; Point(double x, double y) { this.x = x; diff --git a/src/main/java/com/thealgorithms/maths/PowerOfFour.java b/src/main/java/com/thealgorithms/maths/PowerOfFour.java index e5fe6255821b..4d8b535b2f72 100644 --- a/src/main/java/com/thealgorithms/maths/PowerOfFour.java +++ b/src/main/java/com/thealgorithms/maths/PowerOfFour.java @@ -5,7 +5,7 @@ * A power of four is a number that can be expressed as 4^n where n is a non-negative integer. * This class provides a method to determine if a given integer is a power of four using bit manipulation. * - * @author krishna-medapati (https://github.com/krishna-medapati) + * @author krishna-medapati (...) */ public final class PowerOfFour { private PowerOfFour() { @@ -13,12 +13,12 @@ private PowerOfFour() { /** * Checks if the given integer is a power of four. - * + *

* A number is considered a power of four if: * 1. It is greater than zero * 2. It has exactly one '1' bit in its binary representation (power of two) * 3. The '1' bit is at an even position (0, 2, 4, 6, ...) - * + *

* The method uses the mask 0x55555555 (binary: 01010101010101010101010101010101) * to check if the set bit is at an even position. * diff --git a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java index 93c8252ab929..2618957311a7 100644 --- a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java +++ b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java @@ -2,7 +2,7 @@ /** * calculate Power using Recursion - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public final class PowerUsingRecursion { diff --git a/src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java b/src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java index debe3a214a32..489ce82417e3 100644 --- a/src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java +++ b/src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java @@ -9,8 +9,8 @@ private MillerRabinPrimalityCheck() { /** * Check whether the given number is prime or not * MillerRabin algorithm is probabilistic. There is also an altered version which is deterministic. - * https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - * https://cp-algorithms.com/algebra/primality_tests.html + * ... + * ... * * @param n Whole number which is tested on primality * @param k Number of iterations diff --git a/src/main/java/com/thealgorithms/maths/PythagoreanTriple.java b/src/main/java/com/thealgorithms/maths/PythagoreanTriple.java index 2780b113d904..6c49f90e5103 100644 --- a/src/main/java/com/thealgorithms/maths/PythagoreanTriple.java +++ b/src/main/java/com/thealgorithms/maths/PythagoreanTriple.java @@ -4,12 +4,12 @@ * Utility class to check if three integers form a Pythagorean triple. * A Pythagorean triple consists of three positive integers a, b, and c, * such that a² + b² = c². - * + *

* Common examples: * - (3, 4, 5) * - (5, 12, 13) - * - * Reference: https://en.wikipedia.org/wiki/Pythagorean_triple + *

+ * Refhttps://en.wikipedia.org/wiki/Pythagorean_triple */ public final class PythagoreanTriple { diff --git a/src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java b/src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java index cd654c5dc023..126b812a173f 100644 --- a/src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java +++ b/src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java @@ -4,8 +4,8 @@ * This class represents a complex number which has real and imaginary part */ class ComplexNumber { - Double real; - Double imaginary; + final Double real; + final Double imaginary; ComplexNumber(double real, double imaginary) { this.real = real; diff --git a/src/main/java/com/thealgorithms/maths/SecondMinMax.java b/src/main/java/com/thealgorithms/maths/SecondMinMax.java index e5a2d3b89085..8ad4cb79f217 100644 --- a/src/main/java/com/thealgorithms/maths/SecondMinMax.java +++ b/src/main/java/com/thealgorithms/maths/SecondMinMax.java @@ -8,7 +8,7 @@ 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 - * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) + * @author Bharath Sanjeevi ( ... ) */ private SecondMinMax() { @@ -35,7 +35,7 @@ private static int secondBest(final int[] arr, final int initialVal, final BiPre * @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 - * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) + * @author Bharath Sanjeevi ( ... ) */ public static int findSecondMin(final int[] arr) { diff --git a/src/main/java/com/thealgorithms/maths/SieveOfAtkin.java b/src/main/java/com/thealgorithms/maths/SieveOfAtkin.java index 780dd81dac7c..8e91e2b4a97b 100644 --- a/src/main/java/com/thealgorithms/maths/SieveOfAtkin.java +++ b/src/main/java/com/thealgorithms/maths/SieveOfAtkin.java @@ -6,7 +6,7 @@ /** * Implementation of the Sieve of Atkin, an optimized algorithm to generate * all prime numbers up to a given limit. - * + *

* The Sieve of Atkin uses quadratic forms and modular arithmetic to identify * prime candidates, then eliminates multiples of squares. It is more efficient * than the Sieve of Eratosthenes for large limits. @@ -54,7 +54,7 @@ public static List generatePrimes(int limit) { /** * Marks numbers in the sieve as prime candidates based on quadratic residues. - * + *

* This method iterates over all x and y up to sqrt(limit) and applies * the three quadratic forms used in the Sieve of Atkin. Numbers satisfying * the modulo conditions are toggled in the sieve array. @@ -104,7 +104,7 @@ private static void applyQuadraticForm(int n, int limit, boolean[] sieve, int mo /** * Toggles the sieve entry for a number if it satisfies the modulo condition and an additional boolean condition. - * + *

* This version is used for the quadratic form 3*x*x - y*y, which requires x > y. * * @param n the number to check @@ -121,7 +121,7 @@ private static void applyQuadraticForm(int n, int limit, boolean[] sieve, int mo /** * Eliminates numbers that are multiples of squares from the sieve. - * + *

* All numbers that are multiples of i*i (where i is marked as prime) are * marked non-prime to finalize the sieve. This ensures only actual primes remain. * diff --git a/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java index 5a15c4201a15..18f9d6140345 100644 --- a/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java @@ -6,7 +6,7 @@ /** * Sieve of Eratosthenes Algorithm * An efficient algorithm to find all prime numbers up to a given limit. - * + *

* Algorithm: * 1. Create a boolean array of size n+1, initially all true * 2. Mark 0 and 1 as not prime @@ -14,7 +14,7 @@ * - If i is still marked as prime * - Mark all multiples of i (starting from i²) as not prime * 4. Collect all numbers still marked as prime - * + *

* Time Complexity: O(n log log n) * Space Complexity: O(n) * diff --git a/src/main/java/com/thealgorithms/maths/SmithNumber.java b/src/main/java/com/thealgorithms/maths/SmithNumber.java index c06e0023d9bb..57057b5a8187 100644 --- a/src/main/java/com/thealgorithms/maths/SmithNumber.java +++ b/src/main/java/com/thealgorithms/maths/SmithNumber.java @@ -5,11 +5,11 @@ /** * In number theory, a smith number is a composite number for which, in a given number base, * the sum of its digits is equal to the sum of the digits in its prime factorization in the same base. - * + *

* For example, in base 10, 378 = 21 X 33 X 71 is a Smith number since 3 + 7 + 8 = 2 X 1 + 3 X 3 + 7 X 1, * and 22 = 21 X 111 is a Smith number, because 2 + 2 = 2 X 1 + (1 + 1) X 1. - * - * Wiki: https://en.wikipedia.org/wiki/Smith_number + *

+ Wiki: https://en.wikipedia.org/wiki/Smith_number */ public final class SmithNumber { diff --git a/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java b/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java index caa1abfc3203..75147a854f01 100644 --- a/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java +++ b/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java @@ -6,8 +6,8 @@ * 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} + /** + * For more information, go to Solovay–Strassen Primality Test */ final class SolovayStrassenPrimalityTest { diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 80d185c93785..8a09603d0e33 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -1,33 +1,17 @@ package com.thealgorithms.maths; -/* - *To learn about the method, visit the link below : - * https://en.wikipedia.org/wiki/Newton%27s_method - * - * To obtain the square root, no built-in functions should be used - * - * The formula to calculate the root is : root = 0.5(x + n/x), - * here, n is the no. whose square root has to be calculated and - * x has to be guessed such that, the calculation should result into - * the square root of n. - * And the root will be obtained when the error < 0.5 or the precision value can also - * be changed according to the user preference. - */ - -public final class SquareRootWithNewtonRaphsonMethod { - private SquareRootWithNewtonRaphsonMethod() { - } - - public static double squareRoot(int n) { - double x = n; // initially taking a guess that x = n. - double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. - - while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 - // is the precision value taken over here. - x = root; // decreasing the value of x to root, i.e. decreasing the guess. - root = 0.5 * (x + n / x); + public final class SquareRootWithNewtonRaphsonMethod { + private SquareRootWithNewtonRaphsonMethod() { + } + public static double squareRoot(int n) { + double x = n; // initially taking a guess that x = n. + double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. + while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 + // is the precision value taken over here. + x = root; // decreasing the value of x to root, i.e. decreasing the guess. + root = 0.5 * (x + n / x); + } + return root; } - - return root; } -} + diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTest.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTest.java new file mode 100644 index 000000000000..5e120acfffba --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTest.java @@ -0,0 +1,33 @@ +package com.thealgorithms.maths; + +/* + *To learn about the method, visit the link below : + * https://en.wikipedia.org/wiki/Newton%27s_method + * + * To obtain the square root, no built-in functions should be used + * + * The formula to calculate the root is : root = 0.5(x + n/x), + * here, n is the no. whose square root has to be calculated and + * x has to be guessed such that, the calculation should result into + * the square root of n. + * And the root will be obtained when the error < 0.5 or the precision value can also + * be changed according to the user preference. + */ + +public final class SquareRootWithNewtonRaphsonTest { + private SquareRootWithNewtonRaphsonTest() { + } + + public static double squareRoot(int n) { + double x = n; // initially taking a guess that x = n. + double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. + + while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 + // is the precision value taken over here. + x = root; // decreasing the value of x to root, i.e. decreasing the guess. + root = 0.5 * (x + n / x); + } + + return root; + } +} diff --git a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java index 315f0d3a7d28..c4899a23eba1 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java +++ b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java @@ -8,7 +8,7 @@ * difference of 2. * *

- * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression + * Wikipedia: ... */ public final class SumOfArithmeticSeries { private SumOfArithmeticSeries() { diff --git a/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java b/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java index c0a1e782659a..37b9a6429650 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java +++ b/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java @@ -2,8 +2,8 @@ /** * This program calculates the sum of the first n odd numbers. - * - * https://www.cuemath.com/algebra/sum-of-odd-numbers/ + *

* https://www.cuemath.com/algebra/sum-of-odd-numbers/ */ public final class SumOfOddNumbers { diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java index 5369182a0a94..7597a8a727bc 100644 --- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java +++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java @@ -5,7 +5,7 @@ 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 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..439108d815c6 100644 --- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java +++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java @@ -18,21 +18,21 @@ * 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 diff --git a/src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java b/src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java index 13e795a91297..d3f3edf21af4 100644 --- a/src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java +++ b/src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java @@ -3,7 +3,7 @@ /** * This class provides methods to compute the inverse of a square matrix * using Gaussian elimination. For more details, refer to: - * https://en.wikipedia.org/wiki/Invertible_matrix + * ... */ public final class InverseOfMatrix { private InverseOfMatrix() { diff --git a/src/main/java/com/thealgorithms/matrix/LUDecomposition.java b/src/main/java/com/thealgorithms/matrix/LUDecomposition.java index e41aaa201338..f42d51adc6c7 100644 --- a/src/main/java/com/thealgorithms/matrix/LUDecomposition.java +++ b/src/main/java/com/thealgorithms/matrix/LUDecomposition.java @@ -8,9 +8,9 @@ * where: * - l is a lower triangular matrix with 1s on its diagonal * - u is an upper triangular matrix - * - * Reference: - * https://en.wikipedia.org/wiki/lu_decomposition + *

+ * Reference:* https://en.wikipedia.org/wiki/lu_decomposition */ public final class LUDecomposition { @@ -21,8 +21,8 @@ private LUDecomposition() { * A helper class to store both l and u matrices */ public static class LU { - double[][] l; - double[][] u; + final double[][] l; + final double[][] u; LU(double[][] l, double[][] u) { this.l = l; diff --git a/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java b/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java index 6467a438577b..627313ff3e5b 100644 --- a/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java +++ b/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java @@ -8,8 +8,8 @@ * matrix multiplication. * *

For more details: - * https://www.geeksforgeeks.org/java/java-program-to-multiply-two-matrices-of-any-size/ - * https://en.wikipedia.org/wiki/Matrix_multiplication + * ... + * ... * *

Time Complexity: O(n^3) – where n is the dimension of the matrices * (assuming square matrices for simplicity). diff --git a/src/main/java/com/thealgorithms/matrix/MatrixRank.java b/src/main/java/com/thealgorithms/matrix/MatrixRank.java index 6692b6c37c60..336b16cee264 100644 --- a/src/main/java/com/thealgorithms/matrix/MatrixRank.java +++ b/src/main/java/com/thealgorithms/matrix/MatrixRank.java @@ -52,7 +52,7 @@ public static int computeRank(double[][] matrix) { } private static boolean isZero(double value) { - return Math.abs(value) < EPSILON; + return !(Math.abs(value) < EPSILON); } private static double[][] deepCopy(double[][] matrix) { @@ -80,7 +80,7 @@ private static double[][] deepCopy(double[][] matrix) { private static int findPivotRow(double[][] matrix, boolean[] rowMarked, int colIndex) { int numRows = matrix.length; for (int pivotRow = 0; pivotRow < numRows; ++pivotRow) { - if (!rowMarked[pivotRow] && !isZero(matrix[pivotRow][colIndex])) { + if (!rowMarked[pivotRow] && isZero(matrix[pivotRow][colIndex])) { return pivotRow; } } @@ -115,7 +115,7 @@ private static void eliminateRows(double[][] matrix, int pivotRow, int colIndex) int numRows = matrix.length; int numColumns = matrix[0].length; for (int otherRow = 0; otherRow < numRows; ++otherRow) { - if (otherRow != pivotRow && !isZero(matrix[otherRow][colIndex])) { + if (otherRow != pivotRow && isZero(matrix[otherRow][colIndex])) { for (int col2 = colIndex + 1; col2 < numColumns; ++col2) { matrix[otherRow][col2] -= matrix[pivotRow][col2] * matrix[otherRow][colIndex]; } diff --git a/src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java b/src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java index 1ec977af07c6..dea97d5aeb7d 100644 --- a/src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java +++ b/src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java @@ -5,8 +5,8 @@ import java.util.List; /** - * Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116) - * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * Median of Matrix (...) + * Author: Bama Charan Chhandogi (...) */ public final class MedianOfMatrix { diff --git a/src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java b/src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java index 4ae5970a9574..f729fef24e1d 100644 --- a/src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java +++ b/src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java @@ -12,7 +12,7 @@ * clockwise. *

* - * @author Sadiul Hakim (https://github.com/sadiul-hakim) + * @author Sadiul Hakim (...) */ public class PrintAMatrixInSpiralOrder { diff --git a/src/main/java/com/thealgorithms/matrix/StochasticMatrix.java b/src/main/java/com/thealgorithms/matrix/StochasticMatrix.java index 8b071113f9cc..28b9906ff799 100644 --- a/src/main/java/com/thealgorithms/matrix/StochasticMatrix.java +++ b/src/main/java/com/thealgorithms/matrix/StochasticMatrix.java @@ -4,7 +4,7 @@ * Utility class to check whether a matrix is stochastic. * A matrix is stochastic if all its elements are non-negative * and the sum of each row or column is equal to 1. - *Reference: https://en.wikipedia.org/wiki/Stochastic_matrix + *Reference: ... */ public final class StochasticMatrix { diff --git a/src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java index 85852713b9ba..449e8038c5da 100644 --- a/src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java @@ -4,8 +4,8 @@ import java.math.BigDecimal; /** - * @author Anirudh Buvanesh (https://github.com/anirudhb11) For more information - * see https://www.geeksforgeeks.org/matrix-exponentiation/ + * @author Anirudh Buvanesh (...) For more information + * see ... * */ public final class Fibonacci { diff --git a/src/main/java/com/thealgorithms/misc/MapReduce.java b/src/main/java/com/thealgorithms/misc/MapReduce.java index d98b2ee2dd03..5d9bb49770d3 100644 --- a/src/main/java/com/thealgorithms/misc/MapReduce.java +++ b/src/main/java/com/thealgorithms/misc/MapReduce.java @@ -13,8 +13,8 @@ * It consists of two main phases: * - Map: the input data is split into smaller chunks and processed in parallel. * - Reduce: the results from the Map phase are aggregated to produce the final output. - * - * See also: https://en.wikipedia.org/wiki/MapReduce + *

+ * See alhttps://en.wikipedia.org/wiki/MapReduce */ public final class MapReduce { diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java index 95f86f63f720..95418f90bbcd 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java @@ -7,7 +7,7 @@ * A generic abstract class to compute the median of a dynamically growing stream of numbers. * * @param the number type, must extend Number and be Comparable - * + *

* Usage: * Extend this class and implement {@code calculateAverage(T a, T b)} to define how averaging is done. */ diff --git a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java index c81476eaec32..691f305b5ee5 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java @@ -6,9 +6,9 @@ * 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/ + *

+ * See more:* https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ */ @SuppressWarnings("rawtypes") public final class PalindromeSinglyLinkedList { @@ -66,7 +66,7 @@ public static boolean isPalindromeOptimised(Node head) { return true; } static class Node { - int val; + final int val; Node next; Node(int val) { this.val = val; diff --git a/src/main/java/com/thealgorithms/misc/ShuffleArray.java b/src/main/java/com/thealgorithms/misc/ShuffleArray.java index e07c8df771d3..76f9ee238eb6 100644 --- a/src/main/java/com/thealgorithms/misc/ShuffleArray.java +++ b/src/main/java/com/thealgorithms/misc/ShuffleArray.java @@ -11,10 +11,10 @@ * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) - * + *

* This class provides a static method to shuffle an array in place. * - * @author Rashi Dashore (https://github.com/rashi07dashore) + * @author Rashi Dasho(https://github.com/rashi07dashore) */ public final class ShuffleArray { diff --git a/src/main/java/com/thealgorithms/misc/Sparsity.java b/src/main/java/com/thealgorithms/misc/Sparsity.java index 4a919e0e55c6..a2f38f6598dd 100644 --- a/src/main/java/com/thealgorithms/misc/Sparsity.java +++ b/src/main/java/com/thealgorithms/misc/Sparsity.java @@ -4,10 +4,10 @@ * Utility class for calculating the sparsity of a matrix. * A matrix is considered sparse if a large proportion of its elements are zero. * Typically, if more than 2/3 of the elements are zero, the matrix is considered sparse. - * + *

* Sparsity is defined as: * sparsity = (number of zero elements) / (total number of elements) - * + *

* This can lead to significant computational optimizations. */ public final class Sparsity { diff --git a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java index 8ef10758ef80..4a78a3643666 100644 --- a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java @@ -35,8 +35,8 @@ public List> bruteForce(int[] nums, int target) { public List> twoPointer(int[] nums, int target) { Arrays.sort(nums); List> arr = new ArrayList>(); - int start = 0; - int end = 0; + int start; + int end; int i = 0; while (i < nums.length - 1) { start = i + 1; diff --git a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java index 2fc4ed09a792..063d448fd8c3 100644 --- a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java @@ -14,7 +14,7 @@ private TwoSumProblem() { * @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 - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public static Optional> twoSum(final int[] values, final int target) { diff --git a/src/main/java/com/thealgorithms/others/ArrayRightRotation.java b/src/main/java/com/thealgorithms/others/ArrayRightRotation.java index 125edadb6e73..4cd1a915a758 100644 --- a/src/main/java/com/thealgorithms/others/ArrayRightRotation.java +++ b/src/main/java/com/thealgorithms/others/ArrayRightRotation.java @@ -4,8 +4,8 @@ * 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 * + *

* https://en.wikipedia.org/wiki/Right_rotation * */ public final class ArrayRightRotation { private ArrayRightRotation() { diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index 5abf633a1c12..819391d62909 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -1,164 +1,126 @@ package com.thealgorithms.others; - -import java.util.Scanner; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * This file contains an implementation of BANKER'S ALGORITHM 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. * - * @author AMRITESH ANAND (https://github.com/amritesh19) + * @author AMRIANAND (https://github.com/amritesh19) */ public final class BankersAlgorithm { private BankersAlgorithm() { } /** - * This method finds the need of each process - */ - static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) { - for (int i = 0; i < totalProcess; i++) { - for (int j = 0; j < totalResources; j++) { - needArray[i][j] = maxArray[i][j] - allocationArray[i][j]; - } - } - } - - /** - * 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 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 + * Checks whether the system is in a safe state. * - * @return boolean if the system is in safe state or not + * @param available available instances of each resource + * @param max maximum demand of each process + * @param allocation currently allocated resources to each process + * @return SafetyResult indicating safe state and the safe sequence (if any) + * @throws IllegalArgumentException if input is invalid */ - static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) { - int[][] needArray = new int[totalProcess][totalResources]; - - calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); - - boolean[] finishProcesses = new boolean[totalProcess]; - - int[] safeSequenceArray = new int[totalProcess]; - - int[] workArray = new int[totalResources]; - System.arraycopy(availableArray, 0, workArray, 0, totalResources); - - int count = 0; - - // While all processes are not finished or system is not in safe state. - while (count < totalProcess) { - boolean foundSafeSystem = false; - for (int m = 0; m < totalProcess; m++) { - if (!finishProcesses[m]) { - int j; - - for (j = 0; j < totalResources; j++) { - if (needArray[m][j] > workArray[j]) { + public static SafetyResult isSafe(int[] available, int[][] max, int[][] allocation) { + validateInput(available, max, allocation); + int totalProcesses = allocation.length; + int totalResources = available.length; + + int[][] need = calculateNeed(max, allocation); + + boolean[] finished = new boolean[totalProcesses]; + int[] work = Arrays.copyOf(available, totalResources); + List safeSequence = new ArrayList<>(); + // While not all processes are finished, look for a process whose needs can be satisfied + while (safeSequence.size() < totalProcesses) { + boolean found = false; + for (int p = 0; p < totalProcesses; p++) { + if (!finished[p]) { + boolean canAllocate = true; + for (int r = 0; r < totalResources; r++) { + if (need[p][r] > work[r]) { + canAllocate = false; break; } } - - if (j == totalResources) { - for (int k = 0; k < totalResources; k++) { - workArray[k] += allocationArray[m][k]; + if (canAllocate) { + // Process can finish; release its allocated resources + for (int r = 0; r < totalResources; r++) { + work[r] += allocation[p][r]; } - - safeSequenceArray[count++] = m; - - finishProcesses[m] = true; - - foundSafeSystem = true; + finished[p] = true; + safeSequence.add(p); + found = true; } } } - - // If we could not find a next process in safe sequence. - if (!foundSafeSystem) { - System.out.print("The system is not in the safe state because lack of resources"); - return false; + if (!found) { + return new SafetyResult(false, List.of(), + "The system is not in a safe state because of lack of resources."); } } + return new SafetyResult(true, safeSequence, "The system is in a safe state."); + } - System.out.print("The system is in safe sequence and the sequence is as follows: "); - for (int i = 0; i < totalProcess; i++) { - System.out.print("P" + safeSequenceArray[i] + " "); + private static int[][] calculateNeed(int[][] max, int[][] allocation) { + int processes = max.length; + int resources = max[0].length; + int[][] need = new int[processes][resources]; + for (int i = 0; i < processes; i++) { + for (int j = 0; j < resources; j++) { + need[i][j] = max[i][j] - allocation[i][j]; + } } - - return true; + return need; } - /** - * This is main method of Banker's Algorithm - */ - public static void main(String[] args) { - int numberOfProcesses; - int numberOfResources; - - Scanner sc = new Scanner(System.in); - - System.out.println("Enter total number of processes"); - numberOfProcesses = sc.nextInt(); - - System.out.println("Enter total number of resources"); - numberOfResources = sc.nextInt(); - - int[] processes = new int[numberOfProcesses]; - for (int i = 0; i < numberOfProcesses; i++) { - processes[i] = i; + private static void validateInput(int[] available, int[][] max, int[][] allocation) { + if (available == null || max == null || allocation == null) { + throw new IllegalArgumentException("Arguments must not be null."); } - - System.out.println("--Enter the availability of--"); - - int[] availableArray = new int[numberOfResources]; - for (int i = 0; i < numberOfResources; i++) { - System.out.println("resource " + i + ": "); - availableArray[i] = sc.nextInt(); + int processes = allocation.length; + if (max.length != processes) { + throw new IllegalArgumentException("max and allocation must have the same number of processes."); } - - System.out.println("--Enter the maximum matrix--"); - - int[][] maxArray = new int[numberOfProcesses][numberOfResources]; - for (int i = 0; i < numberOfProcesses; i++) { - System.out.println("For process " + i + ": "); - for (int j = 0; j < numberOfResources; j++) { - System.out.println("Enter the maximum instances of resource " + j); - maxArray[i][j] = sc.nextInt(); + if (processes == 0) { + throw new IllegalArgumentException("At least one process is required."); + } + int resources = available.length; + if (resources == 0) { + throw new IllegalArgumentException("At least one resource is required."); + } + for (int i = 0; i < processes; i++) { + if (max[i].length != resources || allocation[i].length != resources) { + throw new IllegalArgumentException("Resource count mismatch in max/allocation for process " + i); + } + for (int j = 0; j < resources; j++) { + if (max[i][j] < 0 || allocation[i][j] < 0) { + throw new IllegalArgumentException("Negative values not allowed."); + } + if (allocation[i][j] > max[i][j]) { + throw new IllegalArgumentException( + "Process " + i + " has allocated more than maximum for resource " + j); + } } } - - System.out.println("--Enter the allocation matrix--"); - - int[][] allocationArray = new int[numberOfProcesses][numberOfResources]; - for (int i = 0; i < numberOfProcesses; i++) { - System.out.println("For process " + i + ": "); - for (int j = 0; j < numberOfResources; j++) { - System.out.println("Allocated instances of resource " + j); - allocationArray[i][j] = sc.nextInt(); + for(int j = 0; j < resources; j++) { + if (available[j] < 0) { + throw new IllegalArgumentException("Available resources cannot be negative."); } } - - checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources); - - sc.close(); } } /* diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithmDemo.java b/src/main/java/com/thealgorithms/others/BankersAlgorithmDemo.java new file mode 100644 index 000000000000..f9a4eb553cdc --- /dev/null +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithmDemo.java @@ -0,0 +1,57 @@ +package com.thealgorithms.others; +import java.util.Scanner; + +public class BankersAlgorithmDemo { + private BankersAlgorithmDemo() {} + + public static void main(String[] args) { + try (Scanner scanner = new Scanner(System.in)) { + System.out.print("Enter total number of processes: "); + int numProcesses = scanner.nextInt(); + + System.out.print("Enter total number of resources: "); + int numResources = scanner.nextInt(); + + // Available resources + int[] available = new int[numResources]; + System.out.println("Enter available instances of each resource:"); + for (int j = 0; j < numResources; j++) { + System.out.print("Resource " + j + ": "); + available[j] = scanner.nextInt(); + } + + // Maximum matrix + int[][] max = new int[numProcesses][numResources]; + System.out.println("Enter maximum demand matrix:"); + for (int i = 0; i < numProcesses; i++) { + System.out.println("Process " + i + ":"); + for (int j = 0; j < numResources; j++) { + System.out.print(" Max of resource " + j + ": "); + max[i][j] = scanner.nextInt(); + } + } + + // Allocation matrix + int[][] allocation = new int[numProcesses][numResources]; + System.out.println("Enter allocation matrix:"); + for (int i = 0; i < numProcesses; i++) { + System.out.println("Process " + i + ":"); + for (int j = 0; j < numResources; j++) { + System.out.print(" Allocated of resource " + j + ": "); + allocation[i][j] = scanner.nextInt(); + } + } + + // Run algorithm and display result + SafetyResult result = BankersAlgorithm.isSafe(available, max, allocation); + System.out.println(result.getMessage()); + if (result.isSafe()) { + System.out.print("Safe sequence: "); + for (int p : result.getSequence()) { + System.out.print("P" + p + " "); + } + System.out.println(); + } + } + } +} diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 3fb97724b5ac..fc719997d649 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -5,9 +5,9 @@ * 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 + *

+ * For more information on the algorithm, refer to:* https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ public final class BoyerMoore { private BoyerMoore() { diff --git a/src/main/java/com/thealgorithms/others/CRC32.java b/src/main/java/com/thealgorithms/others/CRC32.java index 180936ed46c1..0e6c256b49e1 100644 --- a/src/main/java/com/thealgorithms/others/CRC32.java +++ b/src/main/java/com/thealgorithms/others/CRC32.java @@ -28,6 +28,6 @@ public static int crc32(byte[] data) { } } crc32 = Integer.reverse(crc32); // result reflect - return crc32 ^ 0xFFFFFFFF; // final xor value + return ~crc32; // final xor value } } diff --git a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java index 2d0be15e0a7b..71e7f4a03e9d 100644 --- a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java @@ -18,17 +18,17 @@ public class CRCAlgorithm { private int wrongMessNotCaught; - private int messSize; + private final int messSize; - private double ber; + private final double ber; private boolean messageChanged; private ArrayList message; - private ArrayList p; + private final ArrayList p; - private Random randomGenerator; + private final Random randomGenerator; /** * The algorithm's main constructor. The most significant variables, used in diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java index a379100a2f3b..02107406ce74 100644 --- a/src/main/java/com/thealgorithms/others/Dijkstra.java +++ b/src/main/java/com/thealgorithms/others/Dijkstra.java @@ -16,7 +16,7 @@ * *

* Original source of code: - * https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of the + * ... Also most of the * comments are from RosettaCode. */ public final class Dijkstra { diff --git a/src/main/java/com/thealgorithms/others/GaussLegendre.java b/src/main/java/com/thealgorithms/others/GaussLegendre.java index acf76ae3b192..a8cde026d2f0 100644 --- a/src/main/java/com/thealgorithms/others/GaussLegendre.java +++ b/src/main/java/com/thealgorithms/others/GaussLegendre.java @@ -2,7 +2,7 @@ /** * Gauss Legendre Algorithm ref - * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm + * ...–Legendre_algorithm * * @author AKS1996 */ diff --git a/src/main/java/com/thealgorithms/others/IterativeFloodFill.java b/src/main/java/com/thealgorithms/others/IterativeFloodFill.java index 3f685f418a3d..6bbf420ca572 100644 --- a/src/main/java/com/thealgorithms/others/IterativeFloodFill.java +++ b/src/main/java/com/thealgorithms/others/IterativeFloodFill.java @@ -93,10 +93,6 @@ private static class Point { */ private static boolean shouldSkipPixel(final int[][] image, final int x, final int y, final int oldColor) { - if (x < 0 || x >= image.length || y < 0 || y >= image[0].length || image[x][y] != oldColor) { - return true; - } - - return false; + return x < 0 || x >= image.length || y < 0 || y >= image[0].length || image[x][y] != oldColor; } } diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index 10986aabec4f..80e273664aee 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -20,9 +20,9 @@ * three segments of equal length. 2. draw an equilateral triangle that has the * middle segment from step 1 as its base and points outward. 3. remove the line * segment that is the base of the triangle from step 2. (description adapted - * from https://en.wikipedia.org/wiki/Koch_snowflake ) (for a more detailed + * from ... ) (for a more detailed * explanation and an implementation in the Processing language, see - * https://natureofcode.com/book/chapter-8-fractals/ + * ... * #84-the-koch-curve-and-the-arraylist-technique ). */ public final class KochSnowflake { @@ -67,7 +67,7 @@ public static void main(String[] args) { try { ImageIO.write(image, "png", new File("KochSnowflake.png")); } catch (IOException e) { - e.printStackTrace(); + throw new RuntimeException("Failed to save image", e); } } @@ -120,7 +120,7 @@ public static BufferedImage getKochSnowflake(int imageWidth, int steps) { * Loops through each pair of adjacent vectors. Each line between two * adjacent vectors is divided into 4 segments by adding 3 additional * vectors in-between the original two vectors. The vector in the middle is - * constructed through a 60 degree rotation so it is bent outwards. + * constructed through a 60-degree rotation so it is bent outwards. * * @param vectors The vectors composing the shape to which the algorithm is * applied. @@ -138,7 +138,7 @@ private static ArrayList iterationStep(List vectors) { newVectors.add(startVector.add(differenceVector.multiply(2))); } - newVectors.add(vectors.get(vectors.size() - 1)); + newVectors.add(vectors.getLast()); return newVectors; } @@ -179,8 +179,8 @@ private static BufferedImage getImage(ArrayList vectors, int imageWidth */ private static class Vector2 { - double x; - double y; + final double x; + final double y; Vector2(double x, double y) { this.x = x; @@ -229,7 +229,7 @@ public Vector2 multiply(double scalar) { } /** - * Vector rotation (see https://en.wikipedia.org/wiki/Rotation_matrix) + * Vector rotation (see ...) * * @param angleInDegrees The angle by which to rotate the vector. * @return The rotated vector. @@ -243,4 +243,4 @@ public Vector2 rotate(double angleInDegrees) { return new Vector2(x, y); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java index b7db964c98d0..2b183465e65a 100644 --- a/src/main/java/com/thealgorithms/others/LineSweep.java +++ b/src/main/java/com/thealgorithms/others/LineSweep.java @@ -7,13 +7,13 @@ * 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 + *

+ * Reference* - https://en.wikipedia.org/wiki/Sweep_line_algorit* - https://en.wikipedia.org/wiki/De_Morgan%27s_laws */ public final class LineSweep { private LineSweep() { diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 600128a7725b..34aa2f3fa675 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -109,7 +109,7 @@ private record CreditCard(int[] digits) { */ public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); - String trimmedCardNumber = cardNumber.replaceAll(" ", ""); + String trimmedCardNumber = cardNumber.replace(" ", ""); if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); } diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 6d7588090ba8..7040f6612248 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -19,8 +19,8 @@ * the Mandelbrot set exhibit an elaborate and infinitely complicated boundary * that reveals progressively ever-finer recursive detail at increasing * magnifications, making the boundary of the Mandelbrot set a fractal curve. - * (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) (see - * also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set + * (description adapted from ... ) (see + * also ... * ) */ public final class Mandelbrot { @@ -50,7 +50,7 @@ public static void main(String[] args) { try { ImageIO.write(coloredImage, "png", new File("Mandelbrot.png")); } catch (IOException e) { - e.printStackTrace(); + throw new RuntimeException("Failed to save image", e); } } @@ -140,20 +140,14 @@ private static Color colorCodedColorMap(double distance) { int q = (int) (val * (1 - f * saturation)); int t = (int) (val * (1 - (1 - f) * saturation)); - switch (hi) { - case 0: - return new Color(v, t, p); - case 1: - return new Color(q, v, p); - case 2: - return new Color(p, v, t); - case 3: - return new Color(p, q, v); - case 4: - return new Color(t, p, v); - default: - return new Color(v, p, q); - } + return switch (hi) { + case 0 -> new Color(v, t, p); + case 1 -> new Color(q, v, p); + case 2 -> new Color(p, v, t); + case 3 -> new Color(p, q, v); + case 4 -> new Color(t, p, v); + default -> new Color(v, p, q); + }; } } @@ -163,7 +157,7 @@ private static Color colorCodedColorMap(double distance) { * of the Mandelbrot set do not diverge so their distance is 1. * * @param figureX The x-coordinate within the figure. - * @param figureX The y-coordinate within the figure. + * @param figureY The y-coordinate within the figure. * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ diff --git a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java index dec813dd3213..9bfdc0d27f50 100644 --- a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java +++ b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java @@ -6,14 +6,14 @@ /** * Algorithm to find the maximum sum of a subarray of size K with all distinct * elements. - * + *

* This implementation uses a sliding window approach with a hash map to * efficiently * track element frequencies within the current window. The algorithm maintains * a window * of size K and slides it across the array, ensuring all elements in the window * are distinct. - * + *

* Time Complexity: O(n) where n is the length of the input array * Space Complexity: O(k) for storing elements in the hash map * @@ -21,7 +21,7 @@ * Algorithm * @see Sliding * Window - * @author Swarga-codes (https://github.com/Swarga-codes) + * @author Swarga(https://github.com/Swarga-codes) */ public final class MaximumSumOfDistinctSubarraysWithLengthK { private MaximumSumOfDistinctSubarraysWithLengthK() { @@ -30,7 +30,7 @@ private MaximumSumOfDistinctSubarraysWithLengthK() { /** * Finds the maximum sum of a subarray of size K consisting of distinct * elements. - * + *

* The algorithm uses a sliding window technique with a frequency map to track * the count of each element in the current window. A window is valid only if * all K elements are distinct (frequency map size equals K). diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index 40a5f6a7a767..966cd28a587b 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -61,8 +61,8 @@ 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 process: the size of the process. + * @param blockSizes: the array with the available memory blocks. + * @param processSize: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ @@ -119,8 +119,8 @@ 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 process: the size of the process. + * @param blockSizes: the array with the available memory blocks. + * @param processSize: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ @@ -177,8 +177,8 @@ 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 process: the size of the process. + * @param blockSizes: the array with the available memory blocks. + * @param processSize: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ @@ -233,8 +233,8 @@ 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 process: the size of the process. + * @param blockSizes: the array with the available memory blocks. + * @param processSize: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index 28dc980034f3..6fac35a188b3 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -27,7 +27,7 @@ * GeeksforGeeks - Minimax Algorithm * * - * @author aitofi (https://github.com/aitorfi) + * @author aitofi (...) */ public final class MiniMaxAlgorithm { @@ -61,7 +61,7 @@ public MiniMaxAlgorithm() { * 2 */ public MiniMaxAlgorithm(int[] scores) { - if (!isPowerOfTwo(scores.length)) { + if (isPowerOfTwo(scores.length)) { throw new IllegalArgumentException("The number of scores must be a power of 2."); } this.scores = Arrays.copyOf(scores, scores.length); @@ -167,7 +167,7 @@ private int log2(int n) { * @return True if n is a power of 2, false otherwise. */ private boolean isPowerOfTwo(int n) { - return n > 0 && (n & (n - 1)) == 0; + return n <= 0 || (n & (n - 1)) != 0; } /** @@ -178,7 +178,7 @@ private boolean isPowerOfTwo(int n) { * 2 */ public void setScores(int[] scores) { - if (!isPowerOfTwo(scores.length)) { + if (isPowerOfTwo(scores.length)) { throw new IllegalArgumentException("The number of scores must be a power of 2."); } this.scores = Arrays.copyOf(scores, scores.length); diff --git a/src/main/java/com/thealgorithms/others/MosAlgorithm.java b/src/main/java/com/thealgorithms/others/MosAlgorithm.java index 2d2778339a7a..efbe1a881a41 100644 --- a/src/main/java/com/thealgorithms/others/MosAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MosAlgorithm.java @@ -5,12 +5,12 @@ /** * Mo's Algorithm (Square Root Decomposition) for offline range queries - * + *

* Mo's Algorithm is used to answer range queries efficiently when: * 1. Queries can be processed offline (all queries known beforehand) * 2. We can efficiently add/remove elements from current range * 3. The problem has optimal substructure for range operations - * + *

* Time Complexity: O((N + Q) * sqrt(N)) where N = array size, Q = number of queries * Space Complexity: O(N + Q) * diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java index 2899b80bcee8..72522164fee5 100644 --- a/src/main/java/com/thealgorithms/others/PageRank.java +++ b/src/main/java/com/thealgorithms/others/PageRank.java @@ -30,8 +30,8 @@ public final class PageRank { private static final double DEFAULT_DAMPING_FACTOR = 0.85; private static final int DEFAULT_ITERATIONS = 2; - private int[][] adjacencyMatrix; - private double[] pageRankValues; + private final int[][] adjacencyMatrix; + private final double[] pageRankValues; private int nodeCount; /** diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java index b43110d4d3ff..fdd3cd2892e0 100644 --- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java +++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java @@ -13,7 +13,7 @@ * that are added first are the first to be removed. New elements are added to * the back/rear of the queue. * - * @author sahilb2 (https://www.github.com/sahilb2) + * @author sahilb2 (...) */ public class QueueUsingTwoStacks { private final Stack inStack; diff --git a/src/main/java/com/thealgorithms/others/SafetyResult.java b/src/main/java/com/thealgorithms/others/SafetyResult.java new file mode 100644 index 000000000000..38c2f28be41e --- /dev/null +++ b/src/main/java/com/thealgorithms/others/SafetyResult.java @@ -0,0 +1,26 @@ +package com.thealgorithms.others; +import java.util.Collections; +import java.util.List; +public class SafetyResult { + private final boolean safe; + private final List sequence; // safe sequence; empty if not safe + private final String message; + + SafetyResult(boolean safe, List sequence, String message) { + this.safe = safe; + this.sequence = Collections.unmodifiableList(sequence); + this.message = message; + } + + public boolean isSafe() { + return safe; + } + + public List getSequence() { + return sequence; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/com/thealgorithms/others/SkylineProblem.java b/src/main/java/com/thealgorithms/others/SkylineProblem.java index e84a5c5b585b..b413d32fde38 100644 --- a/src/main/java/com/thealgorithms/others/SkylineProblem.java +++ b/src/main/java/com/thealgorithms/others/SkylineProblem.java @@ -113,8 +113,8 @@ public ArrayList mergeSkyline(ArrayList sky1, ArrayList - * Link: https://www.geeksforgeeks.org/two-pointers-technique/ + * Link: ... */ public final class TwoPointers { diff --git a/src/main/java/com/thealgorithms/physics/ElasticCollision2D.java b/src/main/java/com/thealgorithms/physics/ElasticCollision2D.java index d096e0a8d7cd..958caf1b1745 100644 --- a/src/main/java/com/thealgorithms/physics/ElasticCollision2D.java +++ b/src/main/java/com/thealgorithms/physics/ElasticCollision2D.java @@ -13,12 +13,12 @@ private ElasticCollision2D() { } public static class Body { - public double x; - public double y; + public final double x; + public final double y; public double vx; public double vy; - public double mass; - public double radius; + public final double mass; + public final double radius; public Body(double x, double y, double vx, double vy, double mass, double radius) { this.x = x; diff --git a/src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java b/src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java index a8d7ac63a186..574b114a58f7 100644 --- a/src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java +++ b/src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java @@ -2,7 +2,7 @@ /** * Ground to ground projectile motion calculator - * + *

* Ground to ground projectile motion is when a projectile's trajectory * starts at the ground, reaches the apex, then falls back on the ground. * diff --git a/src/main/java/com/thealgorithms/physics/Relativity.java b/src/main/java/com/thealgorithms/physics/Relativity.java index ed823c2cc879..8cc5031bf509 100644 --- a/src/main/java/com/thealgorithms/physics/Relativity.java +++ b/src/main/java/com/thealgorithms/physics/Relativity.java @@ -51,7 +51,7 @@ public static double lengthContraction(double length, double v) { /** * Calculates the time that has passed in the moving frame. * - * @param length The time that has passed in the object's own frame (s). + * @param time The time that has passed in the object's own frame (s). * @param v The velocity of the object (m/s). * @return The time that has passed in the laboratory frame (s). */ diff --git a/src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java b/src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java index 6de69c103b5a..f19a3dfb1c14 100644 --- a/src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java +++ b/src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java @@ -41,10 +41,8 @@ public SimplePendulumRK4(double length, double g) { */ private double[] derivatives(double[] state) { double theta = state[0]; - double omega = state[1]; - double dtheta = omega; double domega = -(g / length) * Math.sin(theta); - return new double[] {dtheta, domega}; + return new double[] {state[1], domega}; } /** diff --git a/src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java b/src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java index ca1430f744ab..b51d6a045d93 100644 --- a/src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java +++ b/src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java @@ -11,115 +11,138 @@ public final class WordBoggle { private WordBoggle() { } + /** - * O(nm * 8^s + ws) time where n = width of boggle board, m = height of + * O(nm * 8^s + ws) time, where n = width of boggle board, m = height of * boggle board, s = length of longest word in string array, w = length of * string array, 8 is due to 8 explorable neighbours O(nm + ws) space. */ public static List boggleBoard(char[][] board, String[] words) { Trie trie = new Trie(); for (String word : words) { - trie.add(word); + trie.insert(word); } - Set finalWords = new HashSet<>(); - boolean[][] visited = new boolean[board.length][board.length]; - for (int i = 0; i < board.length; i++) { - for (int j = 0; j < board[i].length; j++) { - explore(i, j, board, trie.root, visited, finalWords); + + Set foundWords = new HashSet<>(); + // Bug fix: columns are board[0].length, not board.length (board need not be square). + boolean[][] visited = new boolean[board.length][board[0].length]; + + for (int row = 0; row < board.length; row++) { + for (int col = 0; col < board[row].length; col++) { + explore(row, col, board, trie.getRoot(), visited, foundWords); } } - return new ArrayList<>(finalWords); + + return new ArrayList<>(foundWords); } - public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, Set finalWords) { - if (visited[i][j]) { + // Private: this is an implementation detail of boggleBoard, not part of the public API. + private static void explore(int row, int col, char[][] board, TrieNode node, boolean[][] visited, Set foundWords) { + if (visited[row][col]) { return; } - char letter = board[i][j]; - if (!trieNode.children.containsKey(letter)) { + char letter = board[row][col]; + TrieNode nextNode = node.getChild(letter); + if (nextNode == null) { return; } - visited[i][j] = true; - trieNode = trieNode.children.get(letter); - if (trieNode.children.containsKey('*')) { - finalWords.add(trieNode.word); + + visited[row][col] = true; + + if (nextNode.isEndOfWord()) { + foundWords.add(nextNode.getWord()); } - List neighbors = getNeighbors(i, j, board); - for (Integer[] neighbor : neighbors) { - explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords); + for (Position neighbor : getNeighbors(row, col, board)) { + explore(neighbor.row(), neighbor.col(), board, nextNode, visited, foundWords); } - visited[i][j] = false; + visited[row][col] = false; } - public static List getNeighbors(int i, int j, char[][] board) { - List neighbors = new ArrayList<>(); - if (i > 0 && j > 0) { - neighbors.add(new Integer[] {i - 1, j - 1}); - } - - if (i > 0 && j < board[0].length - 1) { - neighbors.add(new Integer[] {i - 1, j + 1}); + // Private: neighbor geometry is an internal concern of the search, not a public utility. + private static List getNeighbors(int row, int col, char[][] board) { + List neighbors = new ArrayList<>(); + int rows = board.length; + int cols = board[0].length; + + for (int deltaRow = -1; deltaRow <= 1; deltaRow++) { + for (int deltaCol = -1; deltaCol <= 1; deltaCol++) { + if (deltaRow == 0 && deltaCol == 0) { + continue; + } + int newRow = row + deltaRow; + int newCol = col + deltaCol; + if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { + neighbors.add(new Position(newRow, newCol)); + } + } } - if (i < board.length - 1 && j < board[0].length - 1) { - neighbors.add(new Integer[] {i + 1, j + 1}); - } + return neighbors; + } - if (i < board.length - 1 && j > 0) { - neighbors.add(new Integer[] {i + 1, j - 1}); - } + // Named coordinate pair instead of Integer[]: self-documenting, no autoboxing ambiguity. + private record Position(int row, int col) { + } +} - if (i > 0) { - neighbors.add(new Integer[] {i - 1, j}); - } +/** + * A trie node. All state is private; callers interact only through the methods below, + * so the "end of word" marker is an explicit flag rather than a magic sentinel key. + */ +final class TrieNode { - if (i < board.length - 1) { - neighbors.add(new Integer[] {i + 1, j}); - } + private final Map children = new HashMap<>(); + private boolean endOfWord; + private String word = ""; - if (j > 0) { - neighbors.add(new Integer[] {i, j - 1}); - } + TrieNode getChild(char letter) { + return children.get(letter); + } - if (j < board[0].length - 1) { - neighbors.add(new Integer[] {i, j + 1}); - } + void addChild(char letter, TrieNode node) { + children.put(letter, node); + } - return neighbors; + boolean isEndOfWord() { + return endOfWord; } -} -// Trie used to optimize string search -class TrieNode { + void markEndOfWord(String word) { + this.endOfWord = true; + this.word = word; + } - Map children = new HashMap<>(); - String word = ""; + String getWord() { + return word; + } } -class Trie { +/** + * Trie used to optimize string search. Owns its root and construction logic + * so callers (WordBoggle) never need to know how nodes are wired together. + */ +final class Trie { - TrieNode root; - char endSymbol; + private final TrieNode root = new TrieNode(); - Trie() { - this.root = new TrieNode(); - this.endSymbol = '*'; + TrieNode getRoot() { + return root; } - public void add(String str) { - TrieNode node = this.root; - for (int i = 0; i < str.length(); i++) { - char letter = str.charAt(i); - if (!node.children.containsKey(letter)) { - TrieNode newNode = new TrieNode(); - node.children.put(letter, newNode); + void insert(String word) { + TrieNode node = root; + for (int i = 0; i < word.length(); i++) { + char letter = word.charAt(i); + TrieNode child = node.getChild(letter); + if (child == null) { + child = new TrieNode(); + node.addChild(letter, child); } - node = node.children.get(letter); + node = child; } - node.children.put(this.endSymbol, null); - node.word = str; + node.markEndOfWord(word); } -} +} \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/randomized/KargerMinCut.java b/src/main/java/com/thealgorithms/randomized/KargerMinCut.java index 14f1f97450a0..5f3a8528d57c 100644 --- a/src/main/java/com/thealgorithms/randomized/KargerMinCut.java +++ b/src/main/java/com/thealgorithms/randomized/KargerMinCut.java @@ -114,7 +114,7 @@ void union(int u, int v) { } boolean inSameSet(int u, int v) { - return find(u) == find(v); + return find(u) != find(v); } /* @@ -159,14 +159,14 @@ KargerOutput findMinCut() { while (dsu.setCount > 2) { int[] e = workingEdges.get(rand.nextInt(workingEdges.size())); - if (!dsu.inSameSet(e[0], e[1])) { + if (dsu.inSameSet(e[0], e[1])) { dsu.union(e[0], e[1]); } } int cutEdges = 0; for (int[] e : edges) { - if (!dsu.inSameSet(e[0], e[1])) { + if (dsu.inSameSet(e[0], e[1])) { cutEdges++; } } diff --git a/src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java b/src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java index 616f7fb7d7cf..2a1b8d44b837 100644 --- a/src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java +++ b/src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java @@ -9,11 +9,11 @@ /** * Randomized Closest Pair of Points Algorithm - * + *

* Use Case: * - Efficiently finds the closest pair of points in a 2D plane. * - Applicable in computational geometry, clustering, and graphics. - * + *

* Time Complexity: * - Expected: O(n log n) using randomized divide and conquer * diff --git a/src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java b/src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java index b5ac7076bfd6..8c30b523308a 100644 --- a/src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java +++ b/src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java @@ -10,9 +10,9 @@ private RandomizedMatrixMultiplicationVerification() { /** * Verifies whether A × B == C using Freivalds' algorithm. - * @param A Left matrix - * @param B Right matrix - * @param C Product matrix to verify + * @param a Left matrix + * @param b Right matrix + * @param c Product matrix to verify * @param iterations Number of randomized checks * @return true if likely A×B == C; false if definitely not */ diff --git a/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java b/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java index 05e70f635055..9f75ddf35980 100644 --- a/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java +++ b/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java @@ -6,11 +6,11 @@ /** * Reservoir Sampling Algorithm - * + *

* Use Case: * - Efficient for selecting k random items from a stream of unknown size * - Used in streaming systems, big data, and memory-limited environments - * + *

* Time Complexity: O(n) * Space Complexity: O(k) * diff --git a/src/main/java/com/thealgorithms/recursion/DiceThrower.java b/src/main/java/com/thealgorithms/recursion/DiceThrower.java index f46d82213aaa..cf880f19e1d7 100644 --- a/src/main/java/com/thealgorithms/recursion/DiceThrower.java +++ b/src/main/java/com/thealgorithms/recursion/DiceThrower.java @@ -5,10 +5,10 @@ /** * DiceThrower - Generates all possible dice roll combinations that sum to a target - * + *

* This algorithm uses recursive backtracking to find all combinations of dice rolls * (faces 1-6) that sum to a given target value. - * + *

* Example: If target = 4, possible combinations include: * - "1111" (1+1+1+1 = 4) * - "13" (1+3 = 4) diff --git a/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java b/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java index 1e5512be9edd..f1b90bcb01a4 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. * @@ -16,7 +16,7 @@ public final class AgingScheduling { static class Task { - String name; + final String name; int waitTime; int priority; diff --git a/src/main/java/com/thealgorithms/scheduling/EDFScheduling.java b/src/main/java/com/thealgorithms/scheduling/EDFScheduling.java index 5ba79cdbb73a..cf7bdf96ef9c 100644 --- a/src/main/java/com/thealgorithms/scheduling/EDFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/EDFScheduling.java @@ -56,9 +56,9 @@ public List scheduleProcesses() { * The Process class represents a process with an ID, burst time, deadline, waiting time, and turnaround time. */ public static class Process { - private String processId; - private int burstTime; - private int deadline; + private final String processId; + private final int burstTime; + private final int deadline; private int waitingTime; private int turnAroundTime; diff --git a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java index b22e81fe560e..8e1de74a7108 100644 --- a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java @@ -5,11 +5,11 @@ /** * Non-pre-emptive First Come First Serve scheduling. This can be understood here - - * https://www.scaler.com/topics/first-come-first-serve/ + * ... */ public class FCFSScheduling { - private List processes; + private final List processes; FCFSScheduling(final List processes) { this.processes = processes; diff --git a/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java b/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java index 776fc59c0c4d..40f8465d79d3 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. * @@ -16,7 +16,7 @@ public final class FairShareScheduling { static class User { - String name; + final String name; int allocatedResources; int totalWeight; diff --git a/src/main/java/com/thealgorithms/scheduling/GangScheduling.java b/src/main/java/com/thealgorithms/scheduling/GangScheduling.java index ac1ce8ddd6ae..a43b2baf7578 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. * @@ -17,8 +17,8 @@ public final class GangScheduling { static class Gang { - String name; - List tasks; + final String name; + final List tasks; Gang(String name) { this.name = name; diff --git a/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java b/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java index 8ed689698557..934e8a1477eb 100644 --- a/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java @@ -30,9 +30,9 @@ private HighestResponseRatioNextScheduling() { * Represents a process in the scheduling algorithm. */ private static class Process { - String name; - int arrivalTime; - int burstTime; + final String name; + final int arrivalTime; + final int burstTime; int turnAroundTime; boolean finished; diff --git a/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java b/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java index 49638d39fc2a..e42c15932d0b 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,15 +18,15 @@ 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. */ static class Job { - int jobId; - int arrivalTime; - int deadline; - int profit; + final int jobId; + final int arrivalTime; + final int deadline; + final int profit; /** * Constructs a Job instance with the specified job ID, arrival time, deadline, and profit. @@ -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 diff --git a/src/main/java/com/thealgorithms/scheduling/LotteryScheduling.java b/src/main/java/com/thealgorithms/scheduling/LotteryScheduling.java index cea0c793d340..ad8a08f5f158 100644 --- a/src/main/java/com/thealgorithms/scheduling/LotteryScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/LotteryScheduling.java @@ -98,9 +98,9 @@ private Process selectProcessByTicket(int winningTicket) { * lottery selection), waiting time, and turnaround time. */ public static class Process { - private String processId; - private int burstTime; - private int tickets; + private final String processId; + private final int burstTime; + private final int tickets; private int waitingTime; private int turnAroundTime; diff --git a/src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java b/src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java index 75840a5cbdcf..dc0f2f0351c8 100644 --- a/src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java +++ b/src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java @@ -11,8 +11,8 @@ * between queues depending on their CPU burst behavior. */ public class MLFQScheduler { - private List> queues; // Multi-level feedback queues - private int[] timeQuantum; // Time quantum for each queue level + private final List> queues; // Multi-level feedback queues + private final int[] timeQuantum; // Time quantum for each queue level private int currentTime; // Current time in the system /** @@ -104,10 +104,10 @@ public int getCurrentTime() { * algorithm. */ class Process { - int pid; - int burstTime; + final int pid; + final int burstTime; int remainingTime; - int arrivalTime; + final int arrivalTime; int priority; /** diff --git a/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java b/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java index 113b1691dec1..ff05edf543a9 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 @@ -17,8 +17,8 @@ public class MultiAgentScheduling { static class Agent { - String name; - List tasks; + final String name; + final List tasks; Agent(String name) { this.name = name; diff --git a/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java b/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java index 414de4b24e36..7a396efc75fd 100644 --- a/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java @@ -20,11 +20,11 @@ private NonPreemptivePriorityScheduling() { * Represents a process with an ID, burst time, priority, arrival time, and start time. */ static class Process implements Comparable { - int id; - int arrivalTime; + final int id; + final int arrivalTime; int startTime; - int burstTime; - int priority; + final int burstTime; + final int priority; /** * Constructs a Process instance with the specified parameters. diff --git a/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java b/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java index fd78dc571819..a13575fe29c5 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. * @@ -16,8 +16,8 @@ public final class ProportionalFairScheduling { static class Process { - String name; - int weight; + final String name; + final int weight; int allocatedResources; Process(String name, int weight) { diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java index 05efe1d59141..6fe60e3abaff 100644 --- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java @@ -10,12 +10,12 @@ * @author Md Asif Joardar * The Round-robin scheduling algorithm is a kind of preemptive First come, First Serve CPU * Scheduling algorithm. This can be understood here - - * https://www.scaler.com/topics/round-robin-scheduling-in-os/ + * ... */ public class RRScheduling { - private List processes; - private int quantumTime; + private final List processes; + private final int quantumTime; RRScheduling(final List processes, int quantumTime) { this.processes = processes; diff --git a/src/main/java/com/thealgorithms/scheduling/RandomScheduling.java b/src/main/java/com/thealgorithms/scheduling/RandomScheduling.java index b7e863b5cfd8..6f0920959635 100644 --- a/src/main/java/com/thealgorithms/scheduling/RandomScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RandomScheduling.java @@ -11,7 +11,7 @@ * It doesn't consider priority, deadlines, or burst times, making it * inefficient but useful in scenarios where fairness or unpredictability * is required (e.g., load balancing in distributed systems). - * + *

* Use Case: Distributed systems where randomness helps avoid task starvation. * * @author Hardvan diff --git a/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java b/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java index 99214fff20c4..3edad1477c95 100644 --- a/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java @@ -14,11 +14,11 @@ * P2 | 2 ms | 1 ms * In this example, P1 will be executed at time = 0 until time = 1 when P2 arrives. At time = 2, P2 will be executed until time = 4. At time 4, P2 is done, and P1 is executed again to be done. * That's a simple example of how the algorithm works. - * More information you can find here -> https://en.wikipedia.org/wiki/Shortest_remaining_time + * More information you can find here -> ... */ public class SRTFScheduling { protected List processes; - protected List ready; + protected final List ready; /** * Constructor diff --git a/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java b/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java index 15159a07d2d4..5d8b43529494 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. * @@ -16,7 +16,7 @@ public final class SelfAdjustingScheduling { private static class Task implements Comparable { - String name; + final String name; int waitTime; int priority; diff --git a/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java b/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java index bbfd36f0f660..7c77f2324c16 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 @@ -16,9 +16,9 @@ public class SlackTimeScheduling { static class Task { - String name; - int executionTime; - int deadline; + final String name; + final int executionTime; + final int deadline; Task(String name, int executionTime, int deadline) { this.name = name; diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java index 2230ecaf35a6..e292b527603a 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java @@ -17,7 +17,7 @@ */ public class CircularLookScheduling { private int currentPosition; - private boolean movingUp; + private final boolean movingUp; private final int maxCylinder; public CircularLookScheduling(int startPosition, boolean movingUp, int maxCylinder) { diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java index a31c3d99a89e..bd7200c34c5e 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java @@ -15,7 +15,7 @@ */ public class CircularScanScheduling { private int currentPosition; - private boolean movingUp; + private final boolean movingUp; private final int diskSize; public CircularScanScheduling(int startPosition, boolean movingUp, int diskSize) { diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java index beba69b05eca..0b2a8ef2ffc6 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java @@ -5,7 +5,7 @@ import java.util.List; /** - * https://en.wikipedia.org/wiki/LOOK_algorithm + * ... * Look Scheduling algorithm implementation. * The Look algorithm moves the disk arm to the closest request in the current direction, * and once it processes all requests in that direction, it reverses the direction. diff --git a/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java b/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java index 261c1a388393..222cdd7ce92e 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 + *... * 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..42d490420ae2 100644 --- a/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java @@ -5,23 +5,23 @@ import java.util.List; /** - * https://en.wikipedia.org/wiki/Elevator_algorithm + * ... * SCAN Scheduling algorithm implementation. * 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 */ public class ScanScheduling { - private int headPosition; - private int diskSize; - private boolean movingUp; + private final int headPosition; + private final int diskSize; + private final boolean movingUp; public ScanScheduling(int headPosition, boolean movingUp, int diskSize) { this.headPosition = headPosition; diff --git a/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java b/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java index aeddc591b32b..dc610fb41ef1 100644 --- a/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java +++ b/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java @@ -10,15 +10,15 @@ * 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) + * @author Prayas Kumar (...) */ class Movie { - int docId; // Unique identifier for the movie - String name; // Movie name - double imdbRating; // IMDb rating of the movie - int releaseYear; // Year the movie was released - String content; // Full text content (could be the description or script) + final int docId; // Unique identifier for the movie + final String name; // Movie name + final double imdbRating; // IMDb rating of the movie + final int releaseYear; // Year the movie was released + final String content; // Full text content (could be the description or script) /** * Constructor for the Movie class. @@ -53,8 +53,8 @@ public String toString() { } class SearchResult { - int docId; // Unique identifier of the movie document - double relevanceScore; // Relevance score based on the BM25 algorithm + final int docId; // Unique identifier of the movie document + final double relevanceScore; // Relevance score based on the BM25 algorithm /** * Constructor for SearchResult class. @@ -99,8 +99,8 @@ public double getRelevanceScore() { } public final class BM25InvertedIndex { - private Map> index; // Inverted index mapping terms to document id and frequency - private Map movies; // Mapping of movie document IDs to Movie objects + private final Map> index; // Inverted index mapping terms to document id and frequency + private final Map movies; // Mapping of movie document IDs to Movie objects private int totalDocuments; // Total number of movies/documents private double avgDocumentLength; // Average length of documents (number of words) private static final double K = 1.5; // BM25 tuning parameter, controls term frequency saturation diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index ca873fc6eafa..090bf94b9a59 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -30,8 +30,8 @@ * array[2]=5 (5 < 7, search right half) Step 4: left=3, right=3, mid=3, array[3]=7 (Found! * Return index 3) * - * @author Varun Upadhyay (https://github.com/varunu28) - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Varun Upadhyay (...) + * @author Podshivalov Nikita (...) * @see SearchAlgorithm * @see IterativeBinarySearch */ diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index aa938447b864..aecbd60868e0 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 diff --git a/src/main/java/com/thealgorithms/searches/BoyerMoore.java b/src/main/java/com/thealgorithms/searches/BoyerMoore.java index 6998021503cc..0f5da9e7fd86 100644 --- a/src/main/java/com/thealgorithms/searches/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/searches/BoyerMoore.java @@ -3,17 +3,17 @@ /** * Boyer-Moore string search algorithm. * Efficient algorithm for substring search. - * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm + * ... */ public class BoyerMoore { - private final int radix; // Radix (number of possible characters) private final int[] right; // Bad character rule table private final String pattern; public BoyerMoore(String pat) { this.pattern = pat; - this.radix = 256; + // Radix (number of possible characters) + int radix = 256; this.right = new int[radix]; for (int c = 0; c < radix; c++) { diff --git a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java index 781768d8049e..312ed587cc20 100644 --- a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java @@ -8,7 +8,7 @@ /** * @author: caos321 * @date: 31 October 2021 (Sunday) - * @wiki: https://en.wikipedia.org/wiki/Depth-first_search + * @wiki: ... */ public class DepthFirstSearch { diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java index 52dbc0b7e2c5..b019a3dabe23 100644 --- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java +++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java @@ -17,7 +17,7 @@ * This search algorithm requires the input array to be sorted. *

* - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) */ class InterpolationSearch { diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java index 8bf2754ff8f7..04cd03c1ee94 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -25,7 +25,6 @@ int kmpSearch(String pat, String txt) { System.out.println("Found pattern " + "at index " + (i - j)); int index = (i - j); - j = lps[j - 1]; return index; } // mismatch after j matches diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java index c5f6e6ba9776..72a3f238a0c2 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearch.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java @@ -7,7 +7,7 @@ * Linear Search is a simple searching algorithm that checks * each element of the array sequentially until the target * value is found or the array ends. - * + *

* It works for both sorted and unsorted arrays. * *

How it works step-by-step: @@ -38,7 +38,7 @@ * - Best case: O(1) - target is the first element * - Average case: O(n) - target is somewhere in the middle * - Worst case: O(n) - target is last or not present - * + *

* Space Complexity: O(1) * * @author Varun Upadhyay diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index 5a1401edd3c2..d3feb13b126b 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -16,7 +16,7 @@ * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * - * @author Pratik Padalia (https://github.com/15pratik) + * @author Pratik Padalia (...) * @see SearchAlgorithm * @see BinarySearch */ diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index aa74398b708b..4d0da8e3ca82 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -8,9 +8,9 @@ /** * 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 + *

+ * See mohttps://en.wikipedia.org/wiki/Monte_Carlo_tree_search,* https://www.baeldung.com/java-monte-carlo-tree-search */ public class MonteCarloTreeSearch { @@ -63,7 +63,7 @@ public Node monteCarloTreeSearch(Node rootNode) { promisingNode = getPromisingNode(rootNode); // Expand the promising node. - if (promisingNode.childNodes.size() == 0) { + if (promisingNode.childNodes.isEmpty()) { addChildNodes(promisingNode, 10); } @@ -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. @@ -95,7 +95,7 @@ public Node getPromisingNode(Node rootNode) { Node promisingNode = rootNode; // Iterate until a node that hasn't been expanded is found. - while (promisingNode.childNodes.size() != 0) { + while (!promisingNode.childNodes.isEmpty()) { double uctIndex = Double.MIN_VALUE; int nodeIndex = 0; diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index 81e16dbbbf07..a0fd1fa75fc4 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -35,7 +35,7 @@ public static int search(String pattern, String text, int primeNumber) { and pattern. If the hash values match then only check for characters one by one*/ - int j = 0; + int j; if (hashForPattern == hashForText) { /* Check for characters one by one */ for (j = 0; j < patternLength; j++) { diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index ecdcd36adf21..003523e801e4 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -8,7 +8,7 @@ * {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/SearchInARowAndColWiseSortedMatrix.java b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java index b53c7e5256ca..e7e1c25dafcc 100644 --- a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java +++ b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java @@ -6,7 +6,7 @@ public class SearchInARowAndColWiseSortedMatrix { * * @param matrix matrix to be searched * @param value Key being searched for - * @author Sadiul Hakim : https://github.com/sadiul-hakim + * @author Sadiul Hakim : ... */ public int[] search(int[][] matrix, int value) { int n = matrix.length; diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index 4d9f55ea9917..e78c2f990e69 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -13,7 +13,7 @@ * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) * @see SearchAlgorithm * @see IterativeBinarySearch */ 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..8491ba838740 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -16,7 +16,7 @@ * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * - * @author Pratik Padalia (https://github.com/15pratik) + * @author Pratik Padalia (...) * @see SearchAlgorithm * @see BinarySearch */ diff --git a/src/main/java/com/thealgorithms/slidingwindow/CountNiceSubarrays.java b/src/main/java/com/thealgorithms/slidingwindow/CountNiceSubarrays.java index 46f8deeb58dd..bd62c7ad1e3c 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/CountNiceSubarrays.java +++ b/src/main/java/com/thealgorithms/slidingwindow/CountNiceSubarrays.java @@ -3,12 +3,12 @@ /** * Counts the number of "nice subarrays". * A nice subarray is a contiguous subarray that contains exactly k odd numbers. - * + *

* This implementation uses the sliding window technique. - * - * Reference: - * https://leetcode.com/problems/count-number-of-nice-subarrays/ - * + *

+ * Refere* https://leetcode.com/problems/count-number-of-nice-subarrays/ + *

* Time Complexity: O(n) * Space Complexity: O(n) */ diff --git a/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java b/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java index 55c3f709b467..595c04991747 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java +++ b/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java @@ -10,7 +10,7 @@ * Average performance O(n) * Worst-case space complexity O(1) * - * @author https://github.com/Chiefpatwal + * @author ... */ public final class LongestSubarrayWithSumLessOrEqualToK { diff --git a/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java index 0641730d8b09..ce3ec9378d1a 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java +++ b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java @@ -12,7 +12,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 (...) */ public final class LongestSubstringWithoutRepeatingCharacters { diff --git a/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java b/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java index 7e8095e08a0b..30d392e02141 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java +++ b/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java @@ -10,7 +10,7 @@ * Average performance O(n) * Worst-case space complexity O(1) * - * @author Your Name (https://github.com/Chiefpatwal) + * @author Your Name (...) */ public final class MaxSumKSizeSubarray { diff --git a/src/main/java/com/thealgorithms/slidingwindow/MaximumSlidingWindow.java b/src/main/java/com/thealgorithms/slidingwindow/MaximumSlidingWindow.java index f52ba28fd8b5..2d7fda280e21 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/MaximumSlidingWindow.java +++ b/src/main/java/com/thealgorithms/slidingwindow/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 */ diff --git a/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java b/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java index 40a5441fa7a0..549c673666f3 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java +++ b/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java @@ -8,11 +8,11 @@ * 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. * - * @author Rashi Dashore (https://github.com/rashi07dashore) + * @author Rashi Dasho(https://github.com/rashi07dashore) */ public final class MinSumKSizeSubarray { diff --git a/src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java b/src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java index c1a5ac067ab5..350fe123ff5c 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java +++ b/src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java @@ -4,13 +4,13 @@ /** * Finds the minimum window substring in 's' that contains all characters of 't'. - * + *

* Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * - * @author https://github.com/Chiefpatwal + * @authttps://github.com/Chiefpatwal */ public final class MinimumWindowSubstring { // Prevent instantiation diff --git a/src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java b/src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java index b99f7ca7d62f..d13f34dc1c2f 100644 --- a/src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java +++ b/src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java @@ -99,8 +99,8 @@ private static void remove(DoubleStack front, DoubleStack back) { * DoubleStack serves as a collection of two stacks. One is a normal stack called 'stack', the other 'values' stores gcd-s up until some index. */ private static class DoubleStack { - LinkedList stack; - LinkedList values; + final LinkedList stack; + final LinkedList values; DoubleStack() { values = new LinkedList<>(); diff --git a/src/main/java/com/thealgorithms/sorts/BogoSort.java b/src/main/java/com/thealgorithms/sorts/BogoSort.java index 7a1f7b216437..b4404692a42f 100644 --- a/src/main/java/com/thealgorithms/sorts/BogoSort.java +++ b/src/main/java/com/thealgorithms/sorts/BogoSort.java @@ -3,7 +3,7 @@ import java.util.Random; /** - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) * @see SortAlgorithm */ public class BogoSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSort.java b/src/main/java/com/thealgorithms/sorts/BubbleSort.java index d2eca3506c2d..9b83cdc14630 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSort.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSort.java @@ -1,20 +1,20 @@ package com.thealgorithms.sorts; /** - * @author Varun Upadhyay (https://github.com/varunu28) - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Varun Upadhyay (...) + * @author Podshivalov Nikita (...) * @see SortAlgorithm */ class BubbleSort implements SortAlgorithm { /** * Implements generic bubble sort algorithm. - * + *

* Time Complexity: * - Best case: O(n) – array is already sorted. * - Average case: O(n^2) * - Worst case: O(n^2) - * + *

* Space Complexity: O(1) – in-place sorting. * * @param array the array to be sorted. diff --git a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java index 600ae8d3efc9..166828803c8d 100644 --- a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java +++ b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java @@ -6,8 +6,8 @@ * through it back and forth, progressively moving the largest elements * to the end and the smallest elements to the beginning. * - * @author Mateus Bizzo (https://github.com/MattBizzo) - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Mateus Bizzo (...) + * @author Podshivalov Nikita (...) */ class CocktailShakerSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/CombSort.java b/src/main/java/com/thealgorithms/sorts/CombSort.java index cd12a5b2853c..fe71402585d8 100644 --- a/src/main/java/com/thealgorithms/sorts/CombSort.java +++ b/src/main/java/com/thealgorithms/sorts/CombSort.java @@ -10,8 +10,8 @@ *

* Comb sort improves on bubble sort. * - * @author Sandeep Roy (https://github.com/sandeeproy99) - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Sandeep Roy (...) + * @author Podshivalov Nikita (...) * @see BubbleSort * @see SortAlgorithm */ diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 5d54205032d4..a9d1b5c2b030 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -7,9 +7,9 @@ * 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. * diff --git a/src/main/java/com/thealgorithms/sorts/CycleSort.java b/src/main/java/com/thealgorithms/sorts/CycleSort.java index 4ef051419cbb..304dc21760fa 100644 --- a/src/main/java/com/thealgorithms/sorts/CycleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CycleSort.java @@ -3,7 +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) + * @author Podshivalov Nikita (...) */ class CycleSort implements SortAlgorithm { /** diff --git a/src/main/java/com/thealgorithms/sorts/DarkSort.java b/src/main/java/com/thealgorithms/sorts/DarkSort.java index 4887d7d124ba..b2af96062c1a 100644 --- a/src/main/java/com/thealgorithms/sorts/DarkSort.java +++ b/src/main/java/com/thealgorithms/sorts/DarkSort.java @@ -2,7 +2,7 @@ /** * Dark Sort algorithm implementation. - * + *

* Dark Sort uses a temporary array to count occurrences of elements and * reconstructs the sorted array based on the counts. */ diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java index ada745acd25a..f925a6200ca5 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -3,7 +3,7 @@ /** * Dual Pivot Quick Sort Algorithm * - * @author Debasish Biswas (https://github.com/debasishbsws) * + * @author Debasish Biswas (...) * * @see SortAlgorithm */ public class DualPivotQuickSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java index f7e12da06568..b3bce8e0ef25 100644 --- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java +++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java @@ -7,7 +7,7 @@ * middle is given, this implementation will use a value from the given Array. This value is the one * positioned in the arrays' middle if the arrays' length is odd. If the arrays' length is even, the * value left to the middle will be used. More information and Pseudocode: - * https://en.wikipedia.org/wiki/Dutch_national_flag_problem + * ... */ public class DutchNationalFlagSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/ExchangeSort.java b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java index a58caaf1031a..2b5397a34385 100644 --- a/src/main/java/com/thealgorithms/sorts/ExchangeSort.java +++ b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java @@ -14,7 +14,7 @@ *

* *

- * Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort + * Reference: ... *

* * @author 555vedant (Vedant Kasar) diff --git a/src/main/java/com/thealgorithms/sorts/FlashSort.java b/src/main/java/com/thealgorithms/sorts/FlashSort.java index e8dbf8c42742..430ac8078890 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 diff --git a/src/main/java/com/thealgorithms/sorts/GnomeSort.java b/src/main/java/com/thealgorithms/sorts/GnomeSort.java index b074c271404d..cc5b95986447 100644 --- a/src/main/java/com/thealgorithms/sorts/GnomeSort.java +++ b/src/main/java/com/thealgorithms/sorts/GnomeSort.java @@ -3,7 +3,7 @@ /** * Implementation of gnome sort * - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) * @since 2018-04-10 */ public class GnomeSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/HeapSort.java b/src/main/java/com/thealgorithms/sorts/HeapSort.java index 5e3b20f43e10..78de8d3cfa7a 100644 --- a/src/main/java/com/thealgorithms/sorts/HeapSort.java +++ b/src/main/java/com/thealgorithms/sorts/HeapSort.java @@ -2,15 +2,15 @@ /** * Heap Sort algorithm implementation. - * + *

* Heap sort converts the array into a max-heap and repeatedly extracts the maximum * element to sort the array in increasing order. - * + *

* Time Complexity: * - Best case: O(n log n) * - Average case: O(n log n) * - Worst case: O(n log n) - * + *

* Space Complexity: O(1) – in-place sorting * * @see Heap Sort Algorithm diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index 1e42f2a61271..91f29004f23c 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -2,18 +2,18 @@ /** * Generic Insertion Sort algorithm. - * + *

* Standard insertion sort iterates through the array and inserts each element into its * correct position in the sorted portion of the array. - * + *

* Sentinel sort is a variation that first places the minimum element at index 0 to * avoid redundant comparisons in subsequent passes. - * + *

* Time Complexity: * - Best case: O(n) – array is already sorted (sentinel sort can improve slightly) * - Average case: O(n^2) * - Worst case: O(n^2) – array is reverse sorted - * + *

* Space Complexity: O(1) – in-place sorting * * @see SortAlgorithm diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java index d8fd76a86236..102b28a1ae6e 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -8,24 +8,21 @@ public class LinkListSort { public static boolean isSorted(int[] p, int option) { - int[] a = p; // Array is taken as input from test class - int[] b = p; // array similar to a - int ch = option; // Choice is choosed as any number from 1 to 3 (So the linked list will be // sorted by Merge sort technique/Insertion sort technique/Heap sort technique) - switch (ch) { + switch (option) { case 1: Task nm = new Task(); Node start = null; Node prev = null; Node fresh; Node ptr; - for (int i = 0; i < a.length; i++) { + for (int i = 0; i < p.length; i++) { // New nodes are created and values are added fresh = new Node(); // Node class is called - fresh.val = a[i]; // Node val is stored + fresh.val = p[i]; // Node val is stored if (start == null) { start = fresh; } else { @@ -37,13 +34,13 @@ public static boolean isSorted(int[] p, int option) { // method is being called int i = 0; for (ptr = start; ptr != null; ptr = ptr.next) { - a[i++] = ptr.val; + p[i++] = ptr.val; // storing the sorted values in the array } - Arrays.sort(b); + Arrays.sort(p); // array b is sorted and it will return true when checked with sorted list LinkListSort uu = new LinkListSort(); - return uu.compare(a, b); + return uu.compare(p, p); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed case 2: @@ -51,10 +48,10 @@ public static boolean isSorted(int[] p, int option) { Node prev1 = null; Node fresh1; Node ptr1; - for (int i1 = 0; i1 < a.length; i1++) { + for (int i1 = 0; i1 < p.length; i1++) { // New nodes are created and values are added fresh1 = new Node(); // New node is created - fresh1.val = a[i1]; // Value is stored in the value part of the node + fresh1.val = p[i1]; // Value is stored in the value part of the node if (start1 == null) { start1 = fresh1; } else { @@ -67,12 +64,12 @@ public static boolean isSorted(int[] p, int option) { // method is being called int i1 = 0; for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { - a[i1++] = ptr1.val; + p[i1++] = ptr1.val; // storing the sorted values in the array } LinkListSort uu1 = new LinkListSort(); // array b is not sorted and it will return false when checked with sorted list - return uu1.compare(a, b); + return uu1.compare(p, p); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed case 3: @@ -81,10 +78,10 @@ public static boolean isSorted(int[] p, int option) { Node prev2 = null; Node fresh2; Node ptr2; - for (int i2 = 0; i2 < a.length; i2++) { + for (int i2 = 0; i2 < p.length; i2++) { // New nodes are created and values are added fresh2 = new Node(); // Node class is created - fresh2.val = a[i2]; // Value is stored in the value part of the Node + fresh2.val = p[i2]; // Value is stored in the value part of the Node if (start2 == null) { start2 = fresh2; } else { @@ -96,13 +93,13 @@ public static boolean isSorted(int[] p, int option) { // method is being called int i3 = 0; for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { - a[i3++] = ptr2.val; + p[i3++] = ptr2.val; // storing the sorted values in the array } - Arrays.sort(b); + Arrays.sort(p); // array b is sorted and it will return true when checked with sorted list LinkListSort uu2 = new LinkListSort(); - return uu2.compare(a, b); + return uu2.compare(p, p); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed default: @@ -208,9 +205,7 @@ void task1(int[] n, int s, int m, int e) { while (j <= e) { b[k++] = n[j++]; } - for (int p = s; p <= e; p++) { - a[p] = b[p - s]; - } + if (e + 1 - s >= 0) System.arraycopy(b, s - s, a, s, e + 1 - s); } // The method task and task1 is used to sort the linklist using merge sort } diff --git a/src/main/java/com/thealgorithms/sorts/MergeSort.java b/src/main/java/com/thealgorithms/sorts/MergeSort.java index 5db9c48b4f61..6a6503249bf1 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSort.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSort.java @@ -14,12 +14,12 @@ class MergeSort implements SortAlgorithm { /** * Generic merge sort algorithm. - * + *

* Time Complexity: * - Best case: O(n log n) * - Average case: O(n log n) * - Worst case: O(n log n) - * + *

* Space Complexity: O(n) – requires auxiliary array for merging. * * @see SortAlgorithm diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java index 910157b83231..252bc934726b 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java @@ -5,7 +5,7 @@ public class MergeSortRecursive { - List arr; + final List arr; public MergeSortRecursive(List arr) { this.arr = arr; @@ -43,18 +43,22 @@ private static List sort(List unsortedA, List unsorte if (unsortedB.isEmpty()) { return unsortedA; } + List newAl; if (unsortedA.get(0) <= unsortedB.get(0)) { - List newAl = new ArrayList() { - { add(unsortedA.get(0)); } + newAl = new ArrayList() { + { + add(unsortedA.get(0)); + } }; newAl.addAll(sort(unsortedA.subList(1, unsortedA.size()), unsortedB)); - return newAl; } else { - List newAl = new ArrayList() { - { add(unsortedB.get(0)); } + newAl = new ArrayList() { + { + add(unsortedB.get(0)); + } }; newAl.addAll(sort(unsortedA, unsortedB.subList(1, unsortedB.size()))); - return newAl; } + return newAl; } } diff --git a/src/main/java/com/thealgorithms/sorts/PancakeSort.java b/src/main/java/com/thealgorithms/sorts/PancakeSort.java index 6522aefd7ae3..8c3c06083359 100644 --- a/src/main/java/com/thealgorithms/sorts/PancakeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PancakeSort.java @@ -3,7 +3,7 @@ /** * Implementation of pancake sort * - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) * @since 2018-04-10 */ public class PancakeSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java index 2d1814441701..393f896c6ad5 100644 --- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java +++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java @@ -3,12 +3,12 @@ public class SelectionSort implements SortAlgorithm { /** * Generic Selection Sort algorithm. - * + *

* Time Complexity: * - Best case: O(n^2) * - Average case: O(n^2) * - Worst case: O(n^2) - * + *

* Space Complexity: O(1) – in-place sorting. * * @see SortAlgorithm diff --git a/src/main/java/com/thealgorithms/sorts/SlowSort.java b/src/main/java/com/thealgorithms/sorts/SlowSort.java index 38a5fa458778..25470e58647c 100644 --- a/src/main/java/com/thealgorithms/sorts/SlowSort.java +++ b/src/main/java/com/thealgorithms/sorts/SlowSort.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; /** - * @author Amir Hassan (https://github.com/ahsNT) + * @author Amir Hassan (...) * @see SortAlgorithm */ public class SlowSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java index 72b046d12861..534fdd4a780a 100644 --- a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java +++ b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java @@ -6,7 +6,7 @@ /** * The common interface of most sorting algorithms * - * @author Podshivalov Nikita (https://github.com/nikitap492) + * @author Podshivalov Nikita (...) */ @SuppressWarnings("rawtypes") public interface SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/StoogeSort.java b/src/main/java/com/thealgorithms/sorts/StoogeSort.java index 2a6e04ce29c7..00acb14a8f60 100644 --- a/src/main/java/com/thealgorithms/sorts/StoogeSort.java +++ b/src/main/java/com/thealgorithms/sorts/StoogeSort.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; /** - * @author Amir Hassan (https://github.com/ahsNT) + * @author Amir Hassan (...) * @see SortAlgorithm */ public class StoogeSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index 382ddde9a6f2..9e6add067ca9 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -10,17 +10,17 @@ * 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. - * + *

* Time Complexity: O(V + E) * - V: number of vertices * - E: number of edges - * + *

* Space Complexity: O(V + E) * - adjacency list and recursion stack in DFS - * - * Reference: https://en.wikipedia.org/wiki/Topological_sorting - * - * Author: Jonathan Taylor (https://github.com/Jtmonument) + *

+ *...ical_sorting + *

+ * Author: JTaylor (https://github.com/Jtmonument) * Based on Introduction to Algorithms 3rd Edition */ public final class TopologicalSort { diff --git a/src/main/java/com/thealgorithms/sorts/TournamentSort.java b/src/main/java/com/thealgorithms/sorts/TournamentSort.java index ec51a1e2c0a9..1502f4fe2f72 100644 --- a/src/main/java/com/thealgorithms/sorts/TournamentSort.java +++ b/src/main/java/com/thealgorithms/sorts/TournamentSort.java @@ -4,16 +4,16 @@ /** * Tournament Sort algorithm implementation. - * + *

* Tournament sort builds a winner tree (a complete binary tree storing the index * of the smallest element in each subtree). It then repeatedly extracts the * winner (minimum) and updates the path from the removed leaf to the root. - * + *

* Time Complexity: * - Best case: O(n log n) * - Average case: O(n log n) * - Worst case: O(n log n) - * + *

* Space Complexity: O(n) – additional winner-tree storage * * @see Tournament Sort Algorithm diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index 6f4e5509489d..1ab12d294cea 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -11,11 +11,11 @@ *

* 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 + *

+ * Referenhttps://en.wikipedia.org/wiki/Tree_sort *

* - * @author Madhur Panwar (https://github.com/mdrpanwar) + * @author Madhur Panw(https://github.com/mdrpanwar) */ public class TreeSort implements SortAlgorithm { diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java index c272b820d07a..2686080e595d 100644 --- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java +++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java @@ -8,9 +8,9 @@ /** * A wiggle sort implementation based on John L.s' answer in - * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity + * ... * Also have a look at: - * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 + * ... * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable * arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2, * 2]. diff --git a/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java b/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java index be9d0099d38b..81be930c80c6 100644 --- a/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java +++ b/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java @@ -8,12 +8,12 @@ * 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 + *

+ * Problhttps://www.baeldung.com/cs/stack-constant-time */ public class GreatestElementConstantTime { - private Stack mainStack; // initialize a mainStack - private Stack maxStack; // initialize a maxStack + private final Stack mainStack; // initialize a mainStack + private final Stack maxStack; // initialize a maxStack /** * Constructs two empty stacks 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..fa05814f6961 100644 --- a/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java +++ b/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java @@ -6,11 +6,11 @@ * 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/ + *

+ * Referenhttps://www.geeksforgeeks.org/check-whether-the-given-string-is-palindrome-using-stack/ */ public class PalindromeWithStack { - private LinkedList stack; + private final LinkedList stack; /** * Constructs an empty stack that stores characters. diff --git a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java index a8f98ac53e5d..047c92f5f0bc 100644 --- a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java @@ -4,10 +4,10 @@ /** * 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. * @@ -32,7 +32,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/PrefixToInfix.java b/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java index 41eb974b0e5b..3065bc313fed 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. diff --git a/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java b/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java index 9864ef9b0f97..e9d215c068e3 100644 --- a/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java +++ b/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java @@ -8,12 +8,12 @@ * 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 + *

+ * Problhttps://www.baeldung.com/cs/stack-constant-time */ public class SmallestElementConstantTime { - private Stack mainStack; // initialize a mainStack - private Stack minStack; // initialize a minStack + private final Stack mainStack; // initialize a mainStack + private final Stack minStack; // initialize a minStack /** * Constructs two empty stacks diff --git a/src/main/java/com/thealgorithms/stacks/SortStack.java b/src/main/java/com/thealgorithms/stacks/SortStack.java index d07d1a5f1dc3..7c0e3984f450 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,7 +39,7 @@ 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. diff --git a/src/main/java/com/thealgorithms/stacks/TrappingRainwater.java b/src/main/java/com/thealgorithms/stacks/TrappingRainwater.java index 072665061b8e..5485a82ccfc2 100644 --- a/src/main/java/com/thealgorithms/stacks/TrappingRainwater.java +++ b/src/main/java/com/thealgorithms/stacks/TrappingRainwater.java @@ -3,15 +3,15 @@ * Trapping Rainwater Problem * Given an array of non-negative integers representing the height of bars, * compute how much water it can trap after raining. - * + *

* Example: * Input: [4,2,0,3,2,5] * Output: 9 - * + *

* Time Complexity: O(n) * Space Complexity: O(1) - * - * Reference: https://en.wikipedia.org/wiki/Trapping_rain_water + *

+ *...g_rain_water */ public final class TrappingRainwater { diff --git a/src/main/java/com/thealgorithms/stacks/ValidParentheses.java b/src/main/java/com/thealgorithms/stacks/ValidParentheses.java index 2cc616a38826..d40e0b4053cb 100644 --- a/src/main/java/com/thealgorithms/stacks/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/stacks/ValidParentheses.java @@ -6,25 +6,25 @@ /** * Valid Parentheses Problem - * + *

* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', * determine if the input string is valid. - * + *

* An input string is valid if: * 1. Open brackets must be closed by the same type of brackets. * 2. Open brackets must be closed in the correct order. * 3. Every close bracket has a corresponding open bracket of the same type. - * + *

* Examples: * Input: "()" * Output: true - * + *

* Input: "()[]{}" * Output: true - * + *

* Input: "(]" * Output: false - * + *

* Input: "([)]" * Output: false * diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 7bd84d47508f..eec46c498be6 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -8,7 +8,7 @@ * typically using all the original letters exactly once. * For example, the word anagram itself can be rearranged into nag a ram, * also the word binary into brainy and the word adobe into abode. - * Reference from https://en.wikipedia.org/wiki/Anagram + * Reference from ... */ public final class Anagrams { private Anagrams() { diff --git a/src/main/java/com/thealgorithms/strings/CheckVowels.java b/src/main/java/com/thealgorithms/strings/CheckVowels.java index 21b536b5c7d5..4d426836e299 100644 --- a/src/main/java/com/thealgorithms/strings/CheckVowels.java +++ b/src/main/java/com/thealgorithms/strings/CheckVowels.java @@ -5,7 +5,7 @@ /** * Vowel Count is a system whereby character strings are placed in order based * on the position of the characters in the conventional ordering of an - * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order + * alphabet. Wikipedia: ... */ public final class CheckVowels { private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u'); diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index d9187cbf66c4..16853bbe9be8 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -98,7 +98,7 @@ private static int firstOccurrence(String pattern, String text, boolean caseSens shiftValues = calcShiftValues(pattern); // build the bad symbol table comparisons = 0; // reset comparisons - if (pattern.length() == 0) { // return failure, if pattern empty + if (pattern.isEmpty()) { // return failure, if pattern empty return -1; } diff --git a/src/main/java/com/thealgorithms/strings/Isogram.java b/src/main/java/com/thealgorithms/strings/Isogram.java index b37f085b075d..a8efb40eaad3 100644 --- a/src/main/java/com/thealgorithms/strings/Isogram.java +++ b/src/main/java/com/thealgorithms/strings/Isogram.java @@ -7,7 +7,7 @@ * An isogram (also called heterogram or nonpattern word) is a word in which no * letter of the word occurs more than once. Each character appears exactly * once. - * + *

* For example, the word "uncopyrightable" is the longest common English isogram * with 15 unique letters. Other examples include "dermatoglyphics" (15 * letters), @@ -17,13 +17,13 @@ * appear multiple times ('l' appears twice in "hello", while 'r', 'm', 'g' * repeat * in "programming"). - * + *

* Isograms are particularly valuable in creating substitution ciphers and are * studied in recreational linguistics. A perfect pangram, which uses all 26 * letters * of the alphabet exactly once, is a special type of isogram. - * - * Reference from https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms + *

+ * Reffrom https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms */ public final class Isogram { /** @@ -34,7 +34,7 @@ private Isogram() { /** * Checks if a string is an isogram using boolean array approach. - * + *

* Time Complexity: O(n) * Space Complexity: O(1) * diff --git a/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java b/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java index 51e8dc6b02c3..d721cc69a5a8 100644 --- a/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java @@ -12,10 +12,10 @@ private LongestNonRepetitiveSubstring() { /** * Finds the length of the longest substring without repeating characters. - * + *

* Uses the sliding window technique with a HashMap to track * the last seen index of each character. - * + *

* Time Complexity: O(n), where n is the length of the input string. * Space Complexity: O(min(n, m)), where m is the size of the character set. * diff --git a/src/main/java/com/thealgorithms/strings/Manacher.java b/src/main/java/com/thealgorithms/strings/Manacher.java index 34c303822bee..c3485138f007 100644 --- a/src/main/java/com/thealgorithms/strings/Manacher.java +++ b/src/main/java/com/thealgorithms/strings/Manacher.java @@ -1,7 +1,7 @@ package com.thealgorithms.strings; /** - * Wikipedia: https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm + * Wikipedia: ...'s_algorithm */ public final class Manacher { diff --git a/src/main/java/com/thealgorithms/strings/MoveHashToEnd.java b/src/main/java/com/thealgorithms/strings/MoveHashToEnd.java index bd686a0c5ba0..70149dafd2db 100644 --- a/src/main/java/com/thealgorithms/strings/MoveHashToEnd.java +++ b/src/main/java/com/thealgorithms/strings/MoveHashToEnd.java @@ -3,15 +3,15 @@ /** * Moves all '#' characters to the end of the given string while preserving * the order of the other characters. - * + *

* Example: * Input : "h#e#l#llo" * Output : "helllo###" - * + *

* The algorithm works by iterating through the string and collecting * all non-# characters first, then filling the remaining positions * with '#'. - * + *

* Time Complexity: O(n) * Space Complexity: O(n) * diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java index 92de4039a582..c2bced334872 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/Palindrome.java b/src/main/java/com/thealgorithms/strings/Palindrome.java index 3567a371d70e..6b74d04298ee 100644 --- a/src/main/java/com/thealgorithms/strings/Palindrome.java +++ b/src/main/java/com/thealgorithms/strings/Palindrome.java @@ -1,7 +1,7 @@ package com.thealgorithms.strings; /** - * Wikipedia: https://en.wikipedia.org/wiki/Palindrome + * Wikipedia: ... */ final class Palindrome { private Palindrome() { diff --git a/src/main/java/com/thealgorithms/strings/Pangram.java b/src/main/java/com/thealgorithms/strings/Pangram.java index a92c282d7e52..f283f562551f 100644 --- a/src/main/java/com/thealgorithms/strings/Pangram.java +++ b/src/main/java/com/thealgorithms/strings/Pangram.java @@ -3,7 +3,7 @@ import java.util.HashSet; /** - * Wikipedia: https://en.wikipedia.org/wiki/Pangram + * Wikipedia: ... */ public final class Pangram { private Pangram() { diff --git a/src/main/java/com/thealgorithms/strings/RabinKarp.java b/src/main/java/com/thealgorithms/strings/RabinKarp.java index be17f87c3656..341b0cf90463 100644 --- a/src/main/java/com/thealgorithms/strings/RabinKarp.java +++ b/src/main/java/com/thealgorithms/strings/RabinKarp.java @@ -4,8 +4,8 @@ import java.util.List; /** - * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) - * + * @author Prateek Kumar Oraon (...) + *

* An implementation of Rabin-Karp string matching algorithm * Program will simply end if there is no match */ @@ -30,8 +30,8 @@ public static List search(String text, String pattern, int q) { int t = 0; int p = 0; int h = 1; - int j = 0; - int i = 0; + int j; + int i; if (m > n) { return new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java b/src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java index 84d4fd8f72ce..49cdd758247b 100644 --- a/src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java +++ b/src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java @@ -1,7 +1,7 @@ package com.thealgorithms.strings; /** - * @author Varun Upadhyay (https://github.com/varunu28) + * @author Varun Upadhyay (...) */ public final class RemoveDuplicateFromString { private RemoveDuplicateFromString() { diff --git a/src/main/java/com/thealgorithms/strings/RemoveStars.java b/src/main/java/com/thealgorithms/strings/RemoveStars.java index 816311e9da84..fb800ea4d12f 100644 --- a/src/main/java/com/thealgorithms/strings/RemoveStars.java +++ b/src/main/java/com/thealgorithms/strings/RemoveStars.java @@ -3,7 +3,7 @@ /** * Removes characters affected by '*' in a string. * Each '*' deletes the closest non-star character to its left. - * + *

* Example: * Input: leet**cod*e * Output: lecoe @@ -19,7 +19,7 @@ public static String removeStars(String s) { for (char c : s.toCharArray()) { if (c == '*') { - if (result.length() > 0) { + if (!result.isEmpty()) { result.deleteCharAt(result.length() - 1); } } else { diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java index 85bc0e4db641..3051013fdfef 100644 --- a/src/main/java/com/thealgorithms/strings/StringCompression.java +++ b/src/main/java/com/thealgorithms/strings/StringCompression.java @@ -1,9 +1,9 @@ package com.thealgorithms.strings; /** - * References : https://en.wikipedia.org/wiki/Run-length_encoding + * References : ... * String compression algorithm deals with encoding the string, that is, shortening the size of the string - * @author Swarga-codes (https://github.com/Swarga-codes) + * @author Swarga-codes (...) */ public final class StringCompression { private StringCompression() { diff --git a/src/main/java/com/thealgorithms/strings/SuffixArray.java b/src/main/java/com/thealgorithms/strings/SuffixArray.java index dbcac147b658..a2cdf6865b43 100644 --- a/src/main/java/com/thealgorithms/strings/SuffixArray.java +++ b/src/main/java/com/thealgorithms/strings/SuffixArray.java @@ -5,9 +5,9 @@ /** * Suffix Array implementation in Java. * Builds an array of indices that represent all suffixes of a string in sorted order. - * Wikipedia Reference: https://en.wikipedia.org/wiki/Suffix_array + * Wikipedia Reference: ... * Author: Nithin U. - * Github: https://github.com/NithinU2802 + * Github: ... */ public final class SuffixArray { diff --git a/src/main/java/com/thealgorithms/strings/TopKFrequentWords.java b/src/main/java/com/thealgorithms/strings/TopKFrequentWords.java index 106de304cf40..77307fe07674 100644 --- a/src/main/java/com/thealgorithms/strings/TopKFrequentWords.java +++ b/src/main/java/com/thealgorithms/strings/TopKFrequentWords.java @@ -13,7 +13,7 @@ * words are ranked in lexicographical ascending order. * *

Reference: - * https://en.wikipedia.org/wiki/Top-k_problem + * ... * */ public final class TopKFrequentWords { diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java index 177163b09ca1..09da281e45d8 100644 --- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java +++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java @@ -13,7 +13,7 @@ void testForFirstCase() { int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}}; int source = 2; int destination = 3; - List> list2 = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); + List> list2; List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); @@ -25,7 +25,7 @@ void testForSecondCase() { int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}, {1, 4}, {3, 4}, {2, 4}}; int source = 0; int destination = 4; - List> list2 = List.of(List.of(0, 1, 3, 4), List.of(0, 1, 4), List.of(0, 2, 1, 3, 4), List.of(0, 2, 1, 4), List.of(0, 2, 4), List.of(0, 3, 4)); + List> list2; List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); @@ -37,7 +37,7 @@ void testForThirdCase() { int[][] a = {{1, 0}, {2, 3}, {0, 4}, {1, 5}, {4, 3}, {0, 2}, {0, 3}, {1, 2}, {0, 5}, {3, 4}, {2, 5}, {2, 4}}; int source = 1; int destination = 5; - List> list2 = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); + List> list2; List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); @@ -49,7 +49,7 @@ void testForFourthcase() { int[][] a = {{0, 1}, {0, 2}, {1, 2}}; int source = 0; int destination = 2; - List> list2 = List.of(List.of(0, 1, 2), List.of(0, 2)); + List> list2; List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); diff --git a/src/test/java/com/thealgorithms/backtracking/MColoringTest.java b/src/test/java/com/thealgorithms/backtracking/MColoringTest.java index f3f25933b7a1..98d6d1052848 100644 --- a/src/test/java/com/thealgorithms/backtracking/MColoringTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MColoringTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; /** - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class MColoringTest { diff --git a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java index 54747e5e73a1..77af68c912bf 100644 --- a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java @@ -1,12 +1,11 @@ package com.thealgorithms.backtracking; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class PermutationTest { @Test @@ -24,7 +23,7 @@ void testSingleElement() { @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})); + assertArrayEquals(result.get(0), new Integer[]{1, 2}); + assertArrayEquals(result.get(1), new Integer[]{2, 1}); } } diff --git a/src/test/java/com/thealgorithms/backtracking/RatInAMazeTest.java b/src/test/java/com/thealgorithms/backtracking/RatInAMazeTest.java index ecd1f3c4dfae..ad0495e9d7c5 100644 --- a/src/test/java/com/thealgorithms/backtracking/RatInAMazeTest.java +++ b/src/test/java/com/thealgorithms/backtracking/RatInAMazeTest.java @@ -1,12 +1,10 @@ package com.thealgorithms.backtracking; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.List; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + class RatInAMazeTest { @Test @@ -14,7 +12,7 @@ void testMultiplePathsExist() { int[][] maze = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {0, 1, 1, 1}}; List paths = RatInAMaze.findPaths(maze); - assertTrue(paths.size() >= 1); + assertFalse(paths.isEmpty()); for (String path : paths) { assertTrue(path.chars().allMatch(c -> "DLRU".indexOf(c) >= 0)); } @@ -91,7 +89,7 @@ void testAllCellsOpen() { void testLargerMazeWithPath() { int[][] maze = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 1, 0, 1}, {0, 1, 1, 1}}; List paths = RatInAMaze.findPaths(maze); - assertTrue(paths.size() >= 1); + assertFalse(paths.isEmpty()); for (String path : paths) { assertTrue(path.chars().allMatch(c -> "DLRU".indexOf(c) >= 0), "Path contains invalid characters: " + path); } diff --git a/src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java b/src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java index c8e7cd0af0dd..162fdfd46e3e 100644 --- a/src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java @@ -24,7 +24,7 @@ void testUniquePermutationsAbc() { @Test void testEmptyString() { - List expected = Arrays.asList(""); + List expected = List.of(""); List result = UniquePermutation.generateUniquePermutations(""); assertEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java index 532f06f79ab3..33b450a61219 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java @@ -8,7 +8,7 @@ /** * Test case for Highest Set Bit - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class HighestSetBitTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java index 9bf804373438..c67befb62e6d 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java @@ -6,7 +6,7 @@ /** * Test case for Index Of Right Most SetBit - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class IndexOfRightMostSetBitTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java index ffd9e4ef176d..43dae8053b2c 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java @@ -10,7 +10,7 @@ /** * Test case for IsPowerTwo class - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public class IsPowerTwoTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java index 4c4d33640ad4..e812d73484b1 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java @@ -6,7 +6,7 @@ /** * Test case for Lowest Set Bit - * @author Prayas Kumar (https://github.com/prayas7102) + * @author Prayas Kumar (...) */ public class LowestSetBitTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java index fe2136fd7f04..16b65107db9c 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java @@ -11,7 +11,7 @@ * This test class validates the functionality of the * NonRepeatingNumberFinder by checking various scenarios. * - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class NonRepeatingNumberFinderTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java index 0e90ed79f587..5e265f9ff54a 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java @@ -10,7 +10,7 @@ /** * Test case for Highest Set Bit - * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma) + * @author Abhinay Verma(...) */ public class OnesComplementTest { diff --git a/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java index 578acc7af18c..2f74426cbcb5 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java @@ -7,7 +7,7 @@ /** * Test case for Highest Set Bit - * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma) + * @author Abhinay Verma(...) */ public class TwosComplementTest { diff --git a/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java b/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java index 52ecff7cdeee..59c3ec346ea2 100644 --- a/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java +++ b/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java @@ -6,7 +6,7 @@ class AutokeyCipherTest { - Autokey autokeyCipher = new Autokey(); + final Autokey autokeyCipher = new Autokey(); @Test void autokeyEncryptTest() { diff --git a/src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java b/src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java index bb1ae5a7e4c2..48d84b8aaad1 100644 --- a/src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java @@ -6,7 +6,7 @@ class BaconianCipherTest { - BaconianCipher baconianCipher = new BaconianCipher(); + final BaconianCipher baconianCipher = new BaconianCipher(); @Test void baconianCipherEncryptTest() { diff --git a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java index ef5e634f781b..d60028d7ebbb 100644 --- a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java +++ b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java @@ -6,7 +6,7 @@ class BlowfishTest { - Blowfish blowfish = new Blowfish(); + final Blowfish blowfish = new Blowfish(); @Test void testEncrypt() { diff --git a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java index 7aa41c4cf423..9c7eb8e3e135 100644 --- a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java +++ b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java @@ -6,7 +6,7 @@ class CaesarTest { - Caesar caesar = new Caesar(); + final Caesar caesar = new Caesar(); @Test void caesarEncryptTest() { diff --git a/src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java b/src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java index 8deae45099d6..706fcece6422 100644 --- a/src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java @@ -32,7 +32,7 @@ public void testDecryption() { String encryptedText = ColumnarTranspositionCipher.encrypt(plaintext, keyword); String decryptedText = ColumnarTranspositionCipher.decrypt(); - assertEquals(plaintext.replaceAll(" ", ""), decryptedText.replaceAll(" ", ""), "The decrypted text should match the original plaintext, ignoring spaces."); + assertEquals(plaintext.replace(" ", ""), decryptedText.replace(" ", ""), "The decrypted text should match the original plaintext, ignoring spaces."); assertEquals(encryptedText, ColumnarTranspositionCipher.encrypt(plaintext, keyword), "The encrypted text should be the same when encrypted again."); } @@ -41,7 +41,7 @@ public void testLongPlainText() { String longText = "This is a significantly longer piece of text to test the encryption and decryption capabilities of the Columnar Transposition Cipher. It should handle long strings gracefully."; String encryptedText = ColumnarTranspositionCipher.encrypt(longText, keyword); String decryptedText = ColumnarTranspositionCipher.decrypt(); - assertEquals(longText.replaceAll(" ", ""), decryptedText.replaceAll(" ", ""), "The decrypted text should match the original long plaintext, ignoring spaces."); + assertEquals(longText.replace(" ", ""), decryptedText.replace(" ", ""), "The decrypted text should match the original long plaintext, ignoring spaces."); assertEquals(encryptedText, ColumnarTranspositionCipher.encrypt(longText, keyword), "The encrypted text should be the same when encrypted again."); } } diff --git a/src/test/java/com/thealgorithms/ciphers/ECCTest.java b/src/test/java/com/thealgorithms/ciphers/ECCTest.java index b78ba51f7c3e..a75b44eaa552 100644 --- a/src/test/java/com/thealgorithms/ciphers/ECCTest.java +++ b/src/test/java/com/thealgorithms/ciphers/ECCTest.java @@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.math.BigInteger; + +import org.jspecify.annotations.NonNull; import org.junit.jupiter.api.Test; /** @@ -14,7 +16,7 @@ * @author xuyang */ public class ECCTest { - ECC ecc = new ECC(256); // Generate a 256-bit ECC key pair. Calls generateKeys(bits) to create keys including privateKey and publicKey. + final ECC ecc = new ECC(256); // Generate a 256-bit ECC key pair. Calls generateKeys(bits) to create keys including privateKey and publicKey. /** * Test the encryption functionality: convert plaintext to ciphertext and output relevant encryption data. @@ -55,18 +57,10 @@ void testDecryptWithKnownValues() { BigInteger knownPrivateKey = new BigInteger("28635978664199231399690075483195602260051035216440375973817268759912070302603"); // 2. Define the known elliptic curve parameters - BigInteger a = new BigInteger("64505295837372135469230827475895976532873592609649950000895066186842236488761"); // Replace with known a value - BigInteger b = new BigInteger("89111668838830965251111555638616364203833415376750835901427122343021749874324"); // Replace with known b value - BigInteger p = new BigInteger("107276428198310591598877737561885175918069075479103276920057092968372930219921"); // Replace with known p value - ECC.ECPoint basePoint = new ECC.ECPoint(new BigInteger("4"), new BigInteger("8")); // Replace with known base point coordinates - - // 3. Create the elliptic curve object - ECC.EllipticCurve curve = new ECC.EllipticCurve(a, b, p, basePoint); + ECC.EllipticCurve curve = getEllipticCurve(); // 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 = getEcPoints(); // 5. Create an ECC instance and set the private key and curve parameters ecc.setPrivateKey(knownPrivateKey); // Use setter method to set the private key @@ -80,6 +74,22 @@ void testDecryptWithKnownValues() { assertEquals(expectedMessage, decryptedMessage); } + private static ECC.ECPoint @NonNull [] getEcPoints() { + ECC.ECPoint rPoint = new ECC.ECPoint(new BigInteger("103077584019003058745849614420912636617007257617156724481937620119667345237687"), new BigInteger("68193862907937248121971710522760893811582068323088661566426323952783362061817")); + ECC.ECPoint sPoint = new ECC.ECPoint(new BigInteger("31932232426664380635434632300383525435115368414929679432313910646436992147798"), new BigInteger("77299754382292904069123203569944908076819220797512755280123348910207308129766")); + return new ECC.ECPoint[] {rPoint, sPoint}; + } + + private static ECC.@NonNull EllipticCurve getEllipticCurve() { + BigInteger a = new BigInteger("64505295837372135469230827475895976532873592609649950000895066186842236488761"); // Replace with known a value + BigInteger b = new BigInteger("89111668838830965251111555638616364203833415376750835901427122343021749874324"); // Replace with known b value + BigInteger p = new BigInteger("107276428198310591598877737561885175918069075479103276920057092968372930219921"); // Replace with known p value + ECC.ECPoint basePoint = new ECC.ECPoint(new BigInteger("4"), new BigInteger("8")); // Replace with known base point coordinates + + // 3. Create the elliptic curve object + return new ECC.EllipticCurve(a, b, p, basePoint); + } + /** * Test that encrypting the same plaintext with ECC produces different ciphertexts. */ diff --git a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java index 8121b6177aa9..2ce2edba41d9 100644 --- a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java @@ -6,7 +6,7 @@ class HillCipherTest { - HillCipher hillCipher = new HillCipher(); + final HillCipher hillCipher = new HillCipher(); @Test void hillCipherEncryptTest() { diff --git a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java index f593a07d89b7..c39809644595 100644 --- a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java @@ -6,7 +6,7 @@ class SimpleSubCipherTest { - SimpleSubCipher simpleSubCipher = new SimpleSubCipher(); + final SimpleSubCipher simpleSubCipher = new SimpleSubCipher(); @Test void simpleSubCipherEncryptTest() { diff --git a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java index 7f94e5731989..a6d8bbff4b5a 100644 --- a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java +++ b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java @@ -7,7 +7,7 @@ class VigenereTest { - Vigenere vigenere = new Vigenere(); + final Vigenere vigenere = new Vigenere(); @Test void testVigenereEncryptDecrypt() { diff --git a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java index 6ef478f95358..7e57f9ab55d2 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java @@ -11,7 +11,7 @@ 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 = { + final byte[] sessionKeyBytes = { 58, (byte) 139, (byte) 184, @@ -23,7 +23,7 @@ class LFSRTest { }; // Represents 11 1010 1011 0011 1100 1011 - byte[] frameCounterBytes = {(byte) 203, (byte) 179, 58}; + final byte[] frameCounterBytes = {(byte) 203, (byte) 179, 58}; @Test void initialize() { diff --git a/src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java b/src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java index b6e10e0d796d..778fc89b9684 100644 --- a/src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java +++ b/src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java @@ -110,8 +110,8 @@ public void testBWTResultHelpers() { assertEquals(res1, res1); assertEquals(res1, res2); - assertNotEquals(res1, null); // obj == null - assertNotEquals(res1, new Object()); // different class + assertNotEquals(null, res1); // obj == null + assertNotEquals(new Object(), res1); // different class assertNotEquals(res1, res3); // different transformed assertNotEquals(res1, res4); // different originalIndex diff --git a/src/test/java/com/thealgorithms/compression/LZ78Test.java b/src/test/java/com/thealgorithms/compression/LZ78Test.java index da1fd8d23318..350231197383 100644 --- a/src/test/java/com/thealgorithms/compression/LZ78Test.java +++ b/src/test/java/com/thealgorithms/compression/LZ78Test.java @@ -1,12 +1,11 @@ package com.thealgorithms.compression; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + class LZ78Test { @Test @@ -153,7 +152,7 @@ void testDictionaryBuilding() { // Verify first few tokens // Expected pattern: (0,a)(1,b)(2,a)(3,b) building dictionary 1:a, 2:ab, 3:aa, 4:aab - assertTrue(compressed.size() > 0); + assertFalse(compressed.isEmpty()); assertEquals(0, compressed.getFirst().index()); // First char always has index 0 } diff --git a/src/test/java/com/thealgorithms/conversions/Base64Test.java b/src/test/java/com/thealgorithms/conversions/Base64Test.java index fbc220c0ca95..a81e4e958bcc 100644 --- a/src/test/java/com/thealgorithms/conversions/Base64Test.java +++ b/src/test/java/com/thealgorithms/conversions/Base64Test.java @@ -10,9 +10,9 @@ /** * Test cases for Base64 encoding and decoding. - * + *

* Author: Nithin U. - * Github: https://github.com/NithinU2802 + * Githhttps://github.com/NithinU2802 */ class Base64Test { diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java index 69af422e7175..058478adb6ac 100644 --- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java +++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java @@ -156,8 +156,7 @@ void testInterleavedPutAndGet() { void testRepeatedNullInsertionThrows() { CircularBuffer buffer = new CircularBuffer<>(5); for (int i = 0; i < 3; i++) { - int finalI = i; - org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> buffer.put(null), "Iteration: " + finalI); + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> buffer.put(null), "Iteration: " + i); } } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java index 5f250e6ca3fd..5542df0607c0 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java @@ -210,7 +210,7 @@ void testReturnsCorrectStrategyInstance() { void testDefaultStrategyIsImmediateEvictionStrategy() { FIFOCache newCache = new FIFOCache.Builder(5).defaultTTL(1000).build(); - Assertions.assertTrue(newCache.getEvictionStrategy() instanceof FIFOCache.ImmediateEvictionStrategy, "Default strategy should be ImmediateEvictionStrategyStrategy"); + Assertions.assertInstanceOf(FIFOCache.ImmediateEvictionStrategy.class, newCache.getEvictionStrategy(), "Default strategy should be ImmediateEvictionStrategyStrategy"); } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java index 100c73ea2a5b..f5ca7285bc5f 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java @@ -210,7 +210,7 @@ void testReturnsCorrectStrategyInstance() { void testDefaultStrategyIsNoEviction() { RRCache newCache = new RRCache.Builder(5).defaultTTL(1000).build(); - Assertions.assertTrue(newCache.getEvictionStrategy() instanceof RRCache.PeriodicEvictionStrategy, "Default strategy should be NoEvictionStrategy"); + Assertions.assertInstanceOf(RRCache.PeriodicEvictionStrategy.class, newCache.getEvictionStrategy(), "Default strategy should be NoEvictionStrategy"); } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java index aa8e6beeb3db..d8a777ed7b83 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java @@ -12,7 +12,7 @@ /** * 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. diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java index 7291cd6c319c..5c2ccd8c9e2e 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java @@ -10,17 +10,16 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({"unchecked"}) public class KruskalTest { private Kruskal kruskal; - private HashSet[] graph; @BeforeEach public void setUp() { kruskal = new Kruskal(); int n = 7; - graph = new HashSet[n]; + HashSet[] graph = new HashSet[n]; for (int i = 0; i < n; i++) { graph[i] = new HashSet<>(); } diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java index 8d8c4e1db6bd..4e4cebf1729b 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java @@ -6,7 +6,7 @@ /** * Tests for {@link IndexedPriorityQueue}. - * + *

* Notes: * - We mainly use a Node class with a mutable "prio" field to test changeKey/decreaseKey/increaseKey. * - The queue is a min-heap, so smaller "prio" means higher priority. @@ -37,7 +37,7 @@ public String toString() { /** Same as Node but overrides equals/hashCode to simulate "duplicate-equals" scenario. */ static class NodeWithEquals { final String id; - int prio; + final int prio; NodeWithEquals(String id, int prio) { this.id = id; diff --git a/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java index 4e86f317c2e8..323470bc7917 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java @@ -8,7 +8,7 @@ /** * Test cases for QuickSortLinkedList. * Author: Prabhat-Kumar-42 - * GitHub: https://github.com/Prabhat-Kumar-42 + * GitHub: ... */ public class QuickSortLinkedListTest { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java index 76b7ab063de4..4d245de9bb9d 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java @@ -7,7 +7,7 @@ /** * Test cases for Reverse K Group LinkedList - * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * Author: Bama Charan Chhandogi (...) */ public class ReverseKGroupTest { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java index c476ad1b0203..1d098f7c0d66 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java @@ -7,7 +7,7 @@ /** * Test cases for RotateSinglyLinkedLists. - * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * Author: Bama Charan Chhandogi (...) */ public class RotateSinglyLinkedListsTest { diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java index fde52b982385..daf9d8b31a98 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java @@ -14,7 +14,6 @@ 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 */ private SinglyLinkedList createSampleList(int length) { @@ -112,11 +111,10 @@ void reverseList() { // Reversing the LinkedList using reverseList() method and storing the head of the reversed // linkedlist in a head node The reversed linkedlist will be 4->3->2->1->null - SinglyLinkedListNode head = list.reverseListIter(list.getHead()); // Recording the Nodes after reversing the LinkedList - SinglyLinkedListNode firstNode = head; // 4 - SinglyLinkedListNode secondNode = firstNode.next; // 3 + // 4 + SinglyLinkedListNode secondNode = list.reverseListIter(list.getHead()).next; // 3 SinglyLinkedListNode thirdNode = secondNode.next; // 2 SinglyLinkedListNode fourthNode = thirdNode.next; // 1 @@ -125,7 +123,7 @@ void reverseList() { assertEquals(1, fourthNode.value); assertEquals(2, thirdNode.value); assertEquals(3, secondNode.value); - assertEquals(4, firstNode.value); + assertEquals(4, list.reverseListIter(list.getHead()).value); } // Test to check whether implemented reverseList() method handles NullPointer Exception for @@ -151,10 +149,9 @@ void reverseListTest() { // Reversing the LinkedList using reverseList() method and storing the head of the reversed // linkedlist in a head node - SinglyLinkedListNode head = list.reverseListIter(list.getHead()); // Storing the head in a temp variable, so that we cannot loose the track of head - SinglyLinkedListNode temp = head; + SinglyLinkedListNode temp = list.reverseListIter(list.getHead()); int i = 20; // This is for the comparison of values of nodes of the reversed linkedlist // Checking whether the reverseList() method performed its task diff --git a/src/test/java/com/thealgorithms/datastructures/queues/ThreadSafeQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/ThreadSafeQueueTest.java index 4c038c05b167..a9e6dc7ecb6a 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/ThreadSafeQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/ThreadSafeQueueTest.java @@ -7,6 +7,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; + +import org.jspecify.annotations.NonNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -144,6 +146,17 @@ public void testMultipleProducersSingleConsumer() throws InterruptedException { }); } + Thread consumerThread = getThread(results, totalItems, queue); + + Assertions.assertTrue(doneLatch.await(10, TimeUnit.SECONDS)); + consumerThread.join(5000); + + Assertions.assertEquals(totalItems, results.size()); + executor.shutdown(); + Assertions.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } + + private static @NonNull Thread getThread(List results, int totalItems, ThreadSafeQueue queue) { Thread consumerThread = new Thread(() -> { try { while (results.size() < totalItems) { @@ -159,13 +172,7 @@ public void testMultipleProducersSingleConsumer() throws InterruptedException { } }); consumerThread.start(); - - Assertions.assertTrue(doneLatch.await(10, TimeUnit.SECONDS)); - consumerThread.join(5000); - - Assertions.assertEquals(totalItems, results.size()); - executor.shutdown(); - Assertions.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + return consumerThread; } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java b/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java index 8a89382211ba..5f1247c63acd 100644 --- a/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java +++ b/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java @@ -1,13 +1,11 @@ package com.thealgorithms.datastructures.stacks; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + class NodeStackTest { private NodeStack intStack; @@ -244,7 +242,7 @@ void testToString() { String stackString = intStack.toString(); // Basic check that toString doesn't throw exception and returns something - assertTrue(stackString != null, "toString should not return null"); - assertTrue(stackString.length() > 0, "toString should return non-empty string"); + assertNotNull(stackString, "toString should not return null"); + assertFalse(stackString.isEmpty(), "toString should return non-empty string"); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java index 5ec0080c5fb8..33a15ba2db84 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java @@ -11,9 +11,9 @@ /** * Unit tests for BSTRecursiveGeneric class. * Covers insertion, deletion, search, traversal, sorting, and display. - * + *

* Author: Udaya Krishnan M - * GitHub: https://github.com/UdayaKrishnanM/ + * GitHhttps://github.com/UdayaKrishnanM/ */ class BSTRecursiveGenericTest { diff --git a/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java index 62b86da214db..d7427b9ea898 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; public class QuadTreeTest { - int quadTreeCapacity = 4; - BoundingBox boundingBox = new BoundingBox(new Point(0, 0), 500); - QuadTree quadTree = new QuadTree(boundingBox, quadTreeCapacity); + final int quadTreeCapacity = 4; + final BoundingBox boundingBox = new BoundingBox(new Point(0, 0), 500); + final QuadTree quadTree = new QuadTree(boundingBox, quadTreeCapacity); @Test public void testNullPointInsertIntoQuadTree() { diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java index 1ec45a863e1a..36ca5128f561 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java @@ -6,7 +6,7 @@ class StrassenMatrixMultiplicationTest { - StrassenMatrixMultiplication smm = new StrassenMatrixMultiplication(); + final StrassenMatrixMultiplication smm = new StrassenMatrixMultiplication(); // Strassen Matrix Multiplication can only be allplied to matrices of size 2^n // and has to be a Square Matrix diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java index e26606ef98a9..ab4ea8d64039 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java @@ -19,7 +19,7 @@ void testMaxSumWithPositiveValues() { void testMaxSumWithMixedValues() { // Test with mixed positive and negative numbers int[] input = {1, -2, 3, 4, -1, 2, 1, -5, 4}; - int expectedMaxSum = 3 + 4 + -1 + 2 + 1; // max subarray is [3, 4, -1, 2, 1] + int expectedMaxSum = 9; // max subarray is [3, 4, -1, 2, 1] assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum)); } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java index 3545eb2667ed..5225961bd382 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java @@ -6,7 +6,7 @@ public class KnapsackMemoizationTest { - KnapsackMemoization knapsackMemoization = new KnapsackMemoization(); + final KnapsackMemoization knapsackMemoization = new KnapsackMemoization(); @Test void test1() { diff --git a/src/test/java/com/thealgorithms/graph/HierholzerEulerianPathTest.java b/src/test/java/com/thealgorithms/graph/HierholzerEulerianPathTest.java index 612d09561b7b..0edf88769e30 100644 --- a/src/test/java/com/thealgorithms/graph/HierholzerEulerianPathTest.java +++ b/src/test/java/com/thealgorithms/graph/HierholzerEulerianPathTest.java @@ -10,7 +10,7 @@ /** * Unit tests for {@link HierholzerEulerianPath}. - * + *

* This test suite validates Hierholzer's Algorithm implementation * for finding Eulerian Paths and Circuits in directed graphs. * diff --git a/src/test/java/com/thealgorithms/graph/StoerWagnerTest.java b/src/test/java/com/thealgorithms/graph/StoerWagnerTest.java index 894d99687d1d..a83737ad7c6f 100644 --- a/src/test/java/com/thealgorithms/graph/StoerWagnerTest.java +++ b/src/test/java/com/thealgorithms/graph/StoerWagnerTest.java @@ -6,7 +6,7 @@ /** * Unit tests for the StoerWagner global minimum cut algorithm. - * + *

* These tests verify correctness of the implementation across * several graph configurations: simple, complete, disconnected, * and small edge cases. diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java index 893ca02ed8a3..9d8c84753e38 100644 --- a/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java +++ b/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java @@ -6,7 +6,7 @@ public class BinaryAdditionTest { - BinaryAddition binaryAddition = new BinaryAddition(); + final BinaryAddition binaryAddition = new BinaryAddition(); @Test public void testEqualLengthNoCarry() { diff --git a/src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java b/src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java index 064f71a17c12..c7e9f19bf089 100644 --- a/src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java +++ b/src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java @@ -15,7 +15,7 @@ class CohenSutherlandTest { // Define the clipping window (1.0, 1.0) to (10.0, 10.0) - CohenSutherland cs = new CohenSutherland(1.0, 1.0, 10.0, 10.0); + final CohenSutherland cs = new CohenSutherland(1.0, 1.0, 10.0, 10.0); @Test void testLineCompletelyInside() { diff --git a/src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java b/src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java index 1c48cd106572..7a86c07165b1 100644 --- a/src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java +++ b/src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java @@ -14,7 +14,7 @@ */ class LiangBarskyTest { - LiangBarsky lb = new LiangBarsky(1.0, 1.0, 10.0, 10.0); + final LiangBarsky lb = new LiangBarsky(1.0, 1.0, 10.0, 10.0); @Test void testLineCompletelyInside() { diff --git a/src/test/java/com/thealgorithms/maths/EulerMethodTest.java b/src/test/java/com/thealgorithms/maths/EulerMethodTest.java index 5ae5ac70b1df..97d770c0aea0 100644 --- a/src/test/java/com/thealgorithms/maths/EulerMethodTest.java +++ b/src/test/java/com/thealgorithms/maths/EulerMethodTest.java @@ -14,11 +14,11 @@ class EulerMethodTest { private static class EulerFullTestCase { - double[] params; - BiFunction equation; - int expectedSize; - double[] expectedFirstPoint; - double[] expectedLastPoint; + final double[] params; + final BiFunction equation; + final int expectedSize; + final double[] expectedFirstPoint; + final double[] expectedLastPoint; EulerFullTestCase(double[] params, BiFunction equation, int expectedSize, double[] expectedFirstPoint, double[] expectedLastPoint) { this.params = params; diff --git a/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java b/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java index 5cfb304ae471..69fb60648e8c 100644 --- a/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java +++ b/src/test/java/com/thealgorithms/maths/FibonacciJavaStreamsTest.java @@ -66,6 +66,6 @@ private static void checkElement(BigDecimal index, BigDecimal expected) { // then Assertions.assertTrue(result.isPresent()); - Assertions.assertEquals(result.get(), expected); + Assertions.assertEquals(expected, result.get()); } } diff --git a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java index a3cd7500b30c..ce020041dbd9 100644 --- a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java @@ -138,7 +138,7 @@ void testKaprekarNumbersInLargeRange() { @Test void testKaprekarNumbersInSingleElementRange() { List result = KaprekarNumbers.kaprekarNumberInRange(9, 9); - List expected = Arrays.asList(9L); + List expected = List.of(9L); assertEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/maths/MeansTest.java b/src/test/java/com/thealgorithms/maths/MeansTest.java index 853fdbea3963..b3d558c56fba 100644 --- a/src/test/java/com/thealgorithms/maths/MeansTest.java +++ b/src/test/java/com/thealgorithms/maths/MeansTest.java @@ -37,7 +37,7 @@ void testArithmeticMeanThrowsExceptionForEmptyList() { @Test void testArithmeticMeanSingleNumber() { - List numbers = Arrays.asList(2.5); + List numbers = List.of(2.5); assertEquals(2.5, Means.arithmetic(numbers), EPSILON); } @@ -88,7 +88,7 @@ void testGeometricMeanThrowsExceptionForEmptyList() { @Test void testGeometricMeanSingleNumber() { - Set numbers = new LinkedHashSet<>(Arrays.asList(2.5)); + Set numbers = new LinkedHashSet<>(List.of(2.5)); assertEquals(2.5, Means.geometric(numbers), EPSILON); } @@ -135,7 +135,7 @@ void testHarmonicMeanThrowsExceptionForEmptyList() { @Test void testHarmonicMeanSingleNumber() { - LinkedHashSet numbers = new LinkedHashSet<>(Arrays.asList(2.5)); + LinkedHashSet numbers = new LinkedHashSet<>(List.of(2.5)); assertEquals(2.5, Means.harmonic(numbers), EPSILON); } @@ -155,7 +155,7 @@ void testHarmonicMeanMultipleNumbers() { @Test void testHarmonicMeanThreeNumbers() { List numbers = Arrays.asList(1.0, 2.0, 4.0); - double expected = 3.0 / (1.0 / 1.0 + 1.0 / 2.0 + 1.0 / 4.0); + double expected = 3.0 / (1.0 + 1.0 / 2.0 + 1.0 / 4.0); assertEquals(expected, Means.harmonic(numbers), EPSILON); } @@ -183,7 +183,7 @@ void testQuadraticMeanThrowsExceptionForEmptyList() { @Test void testQuadraticMeanSingleNumber() { - LinkedHashSet numbers = new LinkedHashSet<>(Arrays.asList(2.5)); + LinkedHashSet numbers = new LinkedHashSet<>(List.of(2.5)); assertEquals(2.5, Means.quadratic(numbers), EPSILON); } diff --git a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java index 705cc6672818..14e946d40c6b 100644 --- a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java @@ -6,7 +6,7 @@ /** * Test case for Power using Recursion - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ class PowerUsingRecursionTest { diff --git a/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java b/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java index 5d491a493ee7..172b862dc9e0 100644 --- a/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java +++ b/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java @@ -29,7 +29,7 @@ void testPrimesUpTo30() { @Test void testPrimesUpTo2() { - List expected = Arrays.asList(2); + List expected = List.of(2); assertEquals(expected, SieveOfEratosthenes.findPrimes(2)); } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java index 067b68962bdb..2be52072c6b0 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java @@ -6,17 +6,17 @@ public class SquareRootWithNewtonRaphsonTestMethod { @Test - void testfor1() { + void test_for_one() { Assertions.assertEquals(1, SquareRootWithNewtonRaphsonMethod.squareRoot(1)); } @Test - void testfor2() { + void test_for_two() { Assertions.assertEquals(1.414213562373095, SquareRootWithNewtonRaphsonMethod.squareRoot(2)); } @Test - void testfor625() { + void test_for_six_hundred_twenty_five() { Assertions.assertEquals(25.0, SquareRootWithNewtonRaphsonMethod.squareRoot(625)); } -} +} \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java index 1eab73c67642..dcd5f628457a 100644 --- a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java +++ b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test; public class SumWithoutArithmeticOperatorsTest { - SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators(); + final SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators(); @Test void addZerotoZero() { diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java index c4a74af0ba8b..f63eef86bc2d 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -7,7 +7,7 @@ /** * Test case for Median Of Running Array Problem. - * @author Ansh Shah (https://github.com/govardhanshah456) + * @author Ansh Shah (...) */ public class MedianOfRunningArrayTest { diff --git a/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java b/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java index 86e73ac0547c..48cf84c4c2bb 100644 --- a/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java +++ b/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java @@ -8,7 +8,7 @@ /** * Test case for Two sum Problem. - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Bama Charan Chhandogi (...) */ public class TwoSumProblemTest { diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java index 296cf1ca1c04..483a99266c0e 100644 --- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java @@ -15,7 +15,7 @@ class BestFitCPUTest { int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); ArrayList testMemAllocation; - MemoryManagementAlgorithms bestFit = new BestFitCPU(); + final MemoryManagementAlgorithms bestFit = new BestFitCPU(); @Test void testFitForUseOfOneBlock() { diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java index 57b6e189b116..5e9e65e363ff 100644 --- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java @@ -15,7 +15,7 @@ class FirstFitCPUTest { int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); ArrayList testMemAllocation; - MemoryManagementAlgorithms firstFit = new FirstFitCPU(); + final MemoryManagementAlgorithms firstFit = new FirstFitCPU(); @Test void testFitForUseOfOneBlock() { diff --git a/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java b/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java index 1a42f1815a96..a6662495742c 100644 --- a/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java +++ b/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java @@ -10,7 +10,7 @@ /** * Test class for {@link MaximumSumOfDistinctSubarraysWithLengthK}. - * + *

* This class contains comprehensive test cases to verify the correctness of the * maximum subarray sum algorithm with distinct elements constraint. */ @@ -31,7 +31,7 @@ void testMaximumSubarraySum(long expected, int k, int[] arr) { /** * Provides test cases for the parameterized test. - * + *

* Test cases cover: * - Normal cases with distinct and duplicate elements * - Edge cases (empty array, k = 0, k > array length) diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java index 75fb3ab7c261..f14b81806e19 100644 --- a/src/test/java/com/thealgorithms/others/NextFitTest.java +++ b/src/test/java/com/thealgorithms/others/NextFitTest.java @@ -15,7 +15,7 @@ class NextFitCPUTest { int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); ArrayList testMemAllocation; - MemoryManagementAlgorithms nextFit = new NextFit(); + final MemoryManagementAlgorithms nextFit = new NextFit(); @Test void testFitForUseOfOneBlock() { diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java index 4dcdf6b9cf4f..8e7409c0b263 100644 --- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java +++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java @@ -1,11 +1,9 @@ package com.thealgorithms.others; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class PasswordGenTest { @Test @@ -30,7 +28,7 @@ public void failGenerationWithMinLengthSmallerThanMaxLengthTest() { @Test public void generatePasswordNonEmptyTest() { String tempPassword = PasswordGen.generatePassword(8, 16); - assertTrue(tempPassword.length() != 0); + assertFalse(tempPassword.isEmpty()); } @Test diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java index eb69f6056132..104fd1eae6ce 100644 --- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java @@ -15,7 +15,7 @@ class WorstFitCPUTest { int[] sizeOfProcesses; ArrayList memAllocation = new ArrayList<>(); ArrayList testMemAllocation; - MemoryManagementAlgorithms worstFit = new WorstFitCPU(); + final MemoryManagementAlgorithms worstFit = new WorstFitCPU(); @Test void testFitForUseOfOneBlock() { diff --git a/src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java b/src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java index 9d7e11777983..bfa80be4e6b0 100644 --- a/src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java +++ b/src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java @@ -8,7 +8,7 @@ /** * JUnit test class for GroundToGroundProjectileMotion - * + *

* Contains unit tests for projectile motion calculations using JUnit 5 */ public class GroundToGroundProjectileMotionTest { diff --git a/src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java b/src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java index 0804e9bfff25..d1ff1634c0ad 100644 --- a/src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java +++ b/src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java @@ -1,14 +1,12 @@ package com.thealgorithms.recursion; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + /** * Test class for DiceThrower * @@ -76,7 +74,7 @@ void testTargetSix() { void testTargetSeven() { List result = DiceThrower.getDiceCombinations(7); // Should include combinations like 61, 52, 43, 331, 322, 2221, etc. - assertTrue(result.size() > 0); + assertFalse(result.isEmpty()); assertTrue(result.contains("61")); assertTrue(result.contains("16")); assertTrue(result.contains("52")); @@ -86,7 +84,7 @@ void testTargetSeven() { @Test void testLargerTarget() { List result = DiceThrower.getDiceCombinations(10); - assertTrue(result.size() > 0); + assertFalse(result.isEmpty()); // All results should sum to 10 for (String combination : result) { int sum = 0; @@ -212,7 +210,7 @@ void testEdgeCaseTargetFive() { @Test void testTargetGreaterThanSix() { List result = DiceThrower.getDiceCombinations(8); - assertTrue(result.size() > 0); + assertFalse(result.isEmpty()); // Verify some expected combinations assertTrue(result.contains("62")); diff --git a/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java index d28dcfeaaea3..738dcc15762c 100644 --- a/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java @@ -12,7 +12,7 @@ public void testCalculateAverageWaitingTime() { 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 + double expectedAvgWaitingTime = ( 5 + 15) / 3.0; // Waiting times: 0 for P2, 5 for P1, 15 for P3 double actualAvgWaitingTime = NonPreemptivePriorityScheduling.calculateAverageWaitingTime(processes, executionOrder); assertEquals(expectedAvgWaitingTime, actualAvgWaitingTime, 0.01, "Average waiting time should be calculated correctly."); diff --git a/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java b/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java index 2017c11dfb3c..a1babc031f6f 100644 --- a/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java +++ b/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java @@ -10,7 +10,7 @@ /** * Test Cases for Inverted Index with BM25 - * @author Prayas Kumar (https://github.com/prayas7102) + * @author Prayas Kumar (...) */ class BM25InvertedIndexTest { diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index dec2c86de9c7..3a5b5a2c6d3a 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -101,7 +101,7 @@ public void binarySearch2dArrayTestOneRow() { int target = 2; // Assert that the requirement, that the array only has one row, is fulfilled. - assertEquals(arr.length, 1); + assertEquals(1, arr.length); int[] ans = BinarySearch2dArray.binarySearch(arr, target); System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); diff --git a/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java b/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java index 8638a707a3e2..e95200a00198 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 (...) */ public class LongestSubstringWithoutRepeatingCharactersTest { diff --git a/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java b/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java index aa3c2eae3294..bea81b497070 100644 --- a/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java +++ b/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java @@ -7,7 +7,7 @@ /** * Unit tests for the MaxSumKSizeSubarray class. * - * @author Your Name (https://github.com/Chiefpatwal) + * @author Your Name (...) */ class MaxSumKSizeSubarrayTest { diff --git a/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java b/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java index 4656c8baf327..68b22a4a03f8 100644 --- a/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java +++ b/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java @@ -7,7 +7,7 @@ /** * Unit tests for the MinSumKSizeSubarray class. * - * @author Rashi Dashore (https://github.com/rashi07dashore) + * @author Rashi Dashore (...) */ class MinSumKSizeSubarrayTest { diff --git a/src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java b/src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java index 2c1534f4bfe6..6b0d9a140b50 100644 --- a/src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java +++ b/src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java @@ -6,11 +6,7 @@ /** * Finds the minimum window substring in {@code s} that contains all characters of {@code t}. - * - * @param s The input string to search within - * @param t The string with required characters - * @return The minimum window substring, or empty string if not found - * @author (https://github.com/Chiefpatwal) + * @author (...) */ public class MinimumWindowSubstringTest { diff --git a/src/test/java/com/thealgorithms/sorts/AdaptiveMergeSortTest.java b/src/test/java/com/thealgorithms/sorts/AdaptiveMergeSortTest.java index 8cb401802c4b..5d7163b03e41 100644 --- a/src/test/java/com/thealgorithms/sorts/AdaptiveMergeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/AdaptiveMergeSortTest.java @@ -92,8 +92,8 @@ public void testSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java index dc4f9e1c25bb..6a2697d8c736 100644 --- a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java @@ -7,7 +7,7 @@ public class BogoSortTest { - private BogoSort bogoSort = new BogoSort(); + private final BogoSort bogoSort = new BogoSort(); @Test public void bogoSortEmptyArray() { @@ -101,8 +101,8 @@ public void bogoSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java index 3b99dca13b06..a9a0b7462686 100644 --- a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java @@ -6,12 +6,12 @@ import org.junit.jupiter.api.Test; /** - * @author Aitor Fidalgo (https://github.com/aitorfi) + * @author Aitor Fidalgo (...) * @see BubbleSort */ public class BubbleSortTest { - private BubbleSort bubbleSort = new BubbleSort(); + private final BubbleSort bubbleSort = new BubbleSort(); @Test public void bubbleSortEmptyArray() { @@ -129,8 +129,8 @@ public void bubbleSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java b/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java index 1d875d1fad0d..960483898fcf 100644 --- a/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java @@ -9,7 +9,7 @@ public class GnomeSortTest { - private GnomeSort gnomeSort = new GnomeSort(); + private final GnomeSort gnomeSort = new GnomeSort(); @Test @DisplayName("GnomeSort empty Array") @@ -122,8 +122,8 @@ public void testSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java index 32a2a807295b..4ec5f0470916 100644 --- a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java @@ -149,8 +149,8 @@ public void testSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java index 09ef8014cec1..b5cee8a40963 100644 --- a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; /** - * @author Tabbygray (https://github.com/Tabbygray) + * @author Tabbygray (...) * @see OddEvenSort */ diff --git a/src/test/java/com/thealgorithms/sorts/QuickSortTest.java b/src/test/java/com/thealgorithms/sorts/QuickSortTest.java index fca57626b75f..f3bfec21263d 100644 --- a/src/test/java/com/thealgorithms/sorts/QuickSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/QuickSortTest.java @@ -1,7 +1,7 @@ package com.thealgorithms.sorts; /** - * @author Akshay Dubey (https://github.com/itsAkshayDubey) + * @author Akshay Dubey (...) * @see QuickSort */ class QuickSortTest extends SortingAlgorithmTest { diff --git a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java index 5fbdf8477092..6810639fddea 100644 --- a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java @@ -6,13 +6,13 @@ import org.junit.jupiter.api.Test; /** - * @author Rebecca Velez (https://github.com/rebeccavelez) + * @author Rebecca Velez (...) * @see SlowSort */ public class SlowSortTest { - private SlowSort slowSort = new SlowSort(); + private final SlowSort slowSort = new SlowSort(); @Test public void slowSortEmptyArray() { @@ -114,8 +114,8 @@ public void testSortMixedCaseStrings() { * Custom Comparable class for testing. **/ static class Person implements Comparable { - String name; - int age; + final String name; + final int age; Person(String name, int age) { this.name = name; diff --git a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java index 43de55018071..d1bb15b70fef 100644 --- a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java @@ -286,7 +286,7 @@ public void shouldHandleListWithNullValues() { } static class CustomObject implements Comparable { - int value; + final int value; CustomObject(int value) { this.value = value; diff --git a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java index 5fb4c18e953e..6f392e296305 100644 --- a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java @@ -5,12 +5,12 @@ import org.junit.jupiter.api.Test; /** - * @author Tabbygray (https://github.com/Tabbygray) + * @author Tabbygray (...) * @see TreeSort */ public class TreeSortTest { - private TreeSort treeSort = new TreeSort(); + private final TreeSort treeSort = new TreeSort(); @Test public void treeSortEmptyArray() { diff --git a/src/test/java/com/thealgorithms/stacks/SortStackTest.java b/src/test/java/com/thealgorithms/stacks/SortStackTest.java index 9747af5337e8..bf1f6bbf14dc 100644 --- a/src/test/java/com/thealgorithms/stacks/SortStackTest.java +++ b/src/test/java/com/thealgorithms/stacks/SortStackTest.java @@ -1,12 +1,11 @@ package com.thealgorithms.stacks; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.Stack; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class SortStackTest { private Stack stack; @@ -251,7 +250,7 @@ public void testOriginalStackIsModified() { SortStack.sortStack(stack); // Verify it's the same object reference - assertTrue(stack == originalReference); + assertSame(stack, originalReference); assertEquals(3, stack.size()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); diff --git a/src/test/java/com/thealgorithms/strings/CharactersSameTest.java b/src/test/java/com/thealgorithms/strings/CharactersSameTest.java index 98f822c4d345..ebb337a618fb 100644 --- a/src/test/java/com/thealgorithms/strings/CharactersSameTest.java +++ b/src/test/java/com/thealgorithms/strings/CharactersSameTest.java @@ -10,6 +10,6 @@ class CharactersSameTest { @ParameterizedTest @CsvSource({"aaa, true", "abc, false", "'1 1 1 1', false", "111, true", "'', true", "' ', true", "'. ', false", "'a', true", "' ', true", "'ab', false", "'11111', true", "'ababab', false", "' ', true", "'+++', true"}) void testIsAllCharactersSame(String input, boolean expected) { - assertEquals(CharactersSame.isAllCharactersSame(input), expected); + assertEquals(expected, CharactersSame.isAllCharactersSame(input)); } } diff --git a/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java b/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java index ba510aa8e995..65e189dbea19 100644 --- a/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java +++ b/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java @@ -10,6 +10,6 @@ class CheckVowelsTest { @ParameterizedTest @CsvSource({"'foo', true", "'bar', true", "'why', false", "'myths', false", "'', false", "'AEIOU', true", "'bcdfghjklmnpqrstvwxyz', false", "'AeIoU', true"}) void testHasVowels(String input, boolean expected) { - assertEquals(CheckVowels.hasVowels(input), expected); + assertEquals(expected, CheckVowels.hasVowels(input)); } }