diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 38d1471dcf13..ef45eef93278 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,7 +10,7 @@ jobs: steps: - uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.1.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d9d9ed1e54e9..b745dc43c04b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -24,13 +24,13 @@ jobs: uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.1.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.1 + uses: github/codeql-action/init@v4.39.4 with: languages: 'java-kotlin' @@ -38,7 +38,7 @@ jobs: run: mvn --batch-mode --update-snapshots verify - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.1 + uses: github/codeql-action/analyze@v4.39.4 with: category: "/language:java-kotlin" @@ -55,12 +55,12 @@ jobs: uses: actions/checkout@v7 - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.1 + uses: github/codeql-action/init@v4.39.4 with: languages: 'actions' - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.1 + uses: github/codeql-action/analyze@v4.39.4 with: category: "/language:actions" ... diff --git a/.github/workflows/infer.yml b/.github/workflows/infer.yml index 962c090ee699..86e076f15d07 100644 --- a/.github/workflows/infer.yml +++ b/.github/workflows/infer.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.1.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' diff --git a/pom.xml b/pom.xml index d7c7a0849fb8..f33ae0f435a7 100644 --- a/pom.xml +++ b/pom.xml @@ -48,7 +48,7 @@ org.apache.commons commons-lang3 - 3.21.0 + 3.22.0 org.apache.commons @@ -112,7 +112,7 @@ com.puppycrawl.tools checkstyle - 14.3.0 + 14.4.0 diff --git a/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java b/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java index 83cd30c7d50a..7266a5307798 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java @@ -2,7 +2,7 @@ /** * Gray code is a binary numeral system where two successive values differ in only one bit. - * This is a simple conversion between binary and Gray code. + * Each input and result is treated as a 32-bit pattern, including the sign bit. * Example: * 7 -> 0111 -> 0100 -> 4 * 4 -> 0100 -> 0111 -> 7 @@ -24,7 +24,7 @@ private GrayCodeConversion() { * @return The corresponding Gray code. */ public static int binaryToGray(int num) { - return num ^ (num >> 1); + return num ^ (num >>> 1); } /** @@ -35,8 +35,8 @@ public static int binaryToGray(int num) { */ public static int grayToBinary(int gray) { int binary = gray; - while (gray > 0) { - gray >>= 1; + while (gray != 0) { + gray >>>= 1; binary ^= gray; } return binary; diff --git a/src/main/java/com/thealgorithms/ciphers/ChaCha20.java b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java new file mode 100644 index 000000000000..5f9906d406d4 --- /dev/null +++ b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java @@ -0,0 +1,136 @@ +package com.thealgorithms.ciphers; + +import java.util.Objects; + +/** + * Implements the ChaCha20 stream cipher described in RFC 8439. + * + *

This implementation is intended for educational purposes and should not + * be used as a replacement for a vetted cryptographic library in production. + * + * @see RFC 8439 + */ +public final class ChaCha20 { + + private static final int BLOCK_SIZE = 64; + private static final long MAX_COUNTER = 0xFFFF_FFFFL; + private static final int[] CONSTANTS = {0x61707865, 0x3320646e, 0x79622d32, 0x6b206574}; + + private ChaCha20() { + // Utility class + } + + /** + * Encrypts bytes with ChaCha20. Decryption uses the same operation. + * + * @param input plaintext bytes; must not be {@code null} + * @param key 32-byte key + * @param nonce 12-byte nonce + * @param initialCounter unsigned 32-bit initial block counter + * @return encrypted bytes + * @throws NullPointerException if an argument is {@code null} + * @throws IllegalArgumentException if a key, nonce, or counter is invalid, + * or the counter would overflow while processing the input + */ + public static byte[] encrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) { + validateInputs(input, key, nonce, initialCounter); + + long blockCount = (input.length + (long) BLOCK_SIZE - 1) / BLOCK_SIZE; + if (blockCount > 0 && initialCounter > MAX_COUNTER - (blockCount - 1)) { + throw new IllegalArgumentException("Counter would overflow"); + } + + byte[] output = new byte[input.length]; + for (int offset = 0; offset < input.length; offset += BLOCK_SIZE) { + long counter = initialCounter + offset / BLOCK_SIZE; + byte[] keyStream = block(key, nonce, counter); + int bytesToProcess = Math.min(BLOCK_SIZE, input.length - offset); + + for (int i = 0; i < bytesToProcess; i++) { + output[offset + i] = (byte) (input[offset + i] ^ keyStream[i]); + } + } + return output; + } + + /** + * Decrypts bytes with ChaCha20. This is identical to encryption. + * + * @param input ciphertext bytes; must not be {@code null} + * @param key 32-byte key + * @param nonce 12-byte nonce + * @param initialCounter unsigned 32-bit initial block counter + * @return decrypted bytes + */ + public static byte[] decrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) { + return encrypt(input, key, nonce, initialCounter); + } + + private static void validateInputs(byte[] input, byte[] key, byte[] nonce, long counter) { + Objects.requireNonNull(input, "input must not be null"); + Objects.requireNonNull(key, "key must not be null"); + Objects.requireNonNull(nonce, "nonce must not be null"); + + if (key.length != 32) { + throw new IllegalArgumentException("Key must be 32 bytes"); + } + if (nonce.length != 12) { + throw new IllegalArgumentException("Nonce must be 12 bytes"); + } + if (counter < 0 || counter > MAX_COUNTER) { + throw new IllegalArgumentException("Counter must be an unsigned 32-bit value"); + } + } + + private static byte[] block(byte[] key, byte[] nonce, long counter) { + int[] state = new int[16]; + System.arraycopy(CONSTANTS, 0, state, 0, CONSTANTS.length); + + for (int i = 0; i < 8; i++) { + state[4 + i] = littleEndianInt(key, i * 4); + } + + state[12] = (int) counter; + state[13] = littleEndianInt(nonce, 0); + state[14] = littleEndianInt(nonce, 4); + state[15] = littleEndianInt(nonce, 8); + + int[] workingState = state.clone(); + for (int i = 0; i < 10; i++) { + quarterRound(workingState, 0, 4, 8, 12); + quarterRound(workingState, 1, 5, 9, 13); + quarterRound(workingState, 2, 6, 10, 14); + quarterRound(workingState, 3, 7, 11, 15); + + quarterRound(workingState, 0, 5, 10, 15); + quarterRound(workingState, 1, 6, 11, 12); + quarterRound(workingState, 2, 7, 8, 13); + quarterRound(workingState, 3, 4, 9, 14); + } + + byte[] output = new byte[BLOCK_SIZE]; + for (int i = 0; i < workingState.length; i++) { + int word = workingState[i] + state[i]; + output[i * 4] = (byte) word; + output[i * 4 + 1] = (byte) (word >>> 8); + output[i * 4 + 2] = (byte) (word >>> 16); + output[i * 4 + 3] = (byte) (word >>> 24); + } + return output; + } + + static void quarterRound(int[] state, int a, int b, int c, int d) { + state[a] += state[b]; + state[d] = Integer.rotateLeft(state[d] ^ state[a], 16); + state[c] += state[d]; + state[b] = Integer.rotateLeft(state[b] ^ state[c], 12); + state[a] += state[b]; + state[d] = Integer.rotateLeft(state[d] ^ state[a], 8); + state[c] += state[d]; + state[b] = Integer.rotateLeft(state[b] ^ state[c], 7); + } + + private static int littleEndianInt(byte[] bytes, int offset) { + return (bytes[offset] & 0xFF) | ((bytes[offset + 1] & 0xFF) << 8) | ((bytes[offset + 2] & 0xFF) << 16) | ((bytes[offset + 3] & 0xFF) << 24); + } +} diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index 01b1aeb8bc6c..db86340aa3cf 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -68,14 +68,22 @@ public String decrypt(String message, int[][] inverseKeyMatrix) { return plainText.toString(); } - // Validates that the determinant of the key matrix is not zero modulo 26 + // Validates that the key matrix is invertible modulo 26, which requires the + // determinant to be coprime with 26. Checking only for a zero determinant is not + // enough: a determinant of 2 or 13 (or any other non-unit) passes that check but + // has no inverse, so encryption collapses distinct plaintexts onto the same + // ciphertext and decryption becomes impossible. private void validateDeterminant(int[][] keyMatrix, int n) { - int det = determinant(keyMatrix, n) % 26; - if (det == 0) { - throw new IllegalArgumentException("Invalid key matrix. Determinant is zero modulo 26."); + int det = Math.floorMod(determinant(keyMatrix, n), 26); + if (gcd(det, 26) != 1) { + throw new IllegalArgumentException("Invalid key matrix. Determinant must be coprime with 26 to be invertible modulo 26."); } } + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + // Computes the determinant of a matrix recursively private int determinant(int[][] matrix, int n) { int det = 0; diff --git a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java index 76ceb6dbce31..3e29ea489dd8 100644 --- a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java @@ -6,7 +6,11 @@ public class PlayfairCipher { private String key; public PlayfairCipher(String key) { - this.key = key; + // Normalize the key the same way the plaintext is normalized in encrypt(): + // uppercase, J folded into I, and non-letters removed. Without this a + // lowercase or mixed-case key, a key containing J, or a key with + // punctuation silently produces a wrong matrix. + this.key = key.toUpperCase().replace("J", "I").replaceAll("[^A-Z]", ""); generateMatrix(); } diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java index d3a672d37424..ef696d305ee4 100644 --- a/src/main/java/com/thealgorithms/conversions/HexToOct.java +++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java @@ -14,6 +14,7 @@ private HexToOct() { * * @param hex The Hexadecimal number as a String. * @return The Decimal equivalent as an integer. + * @throws IllegalArgumentException if the string contains a character that is not a hexadecimal digit */ public static int hexToDecimal(String hex) { String hexDigits = "0123456789ABCDEF"; @@ -23,6 +24,9 @@ public static int hexToDecimal(String hex) { for (int i = 0; i < hex.length(); i++) { char hexChar = hex.charAt(i); int digitValue = hexDigits.indexOf(hexChar); + if (digitValue == -1) { + throw new IllegalArgumentException("Invalid hexadecimal digit: " + hexChar); + } decimalValue = 16 * decimalValue + digitValue; } diff --git a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java index a66db97633b4..caa8ca95c9f1 100644 --- a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java @@ -37,7 +37,7 @@ private OctalToBinary() { */ public static long convertOctalToBinary(int octalNumber) { long binaryNumber = 0; - int digitPosition = 1; + long digitPosition = 1; while (octalNumber != 0) { int octalDigit = octalNumber % 10; diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java index a1360b14dc5a..dd636104c560 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java @@ -100,12 +100,17 @@ public void print() { } /** - * Sorts the elements in the queue using heap sort. + * Sorts and returns the elements in the queue in ascending order using heap sort. + * + * @return an array containing all elements sorted in ascending order */ - public void heapSort() { - for (int i = 1; i <= this.size; i++) { - this.delete(); + public int[] heapSort() { + int initialSize = this.size; + int[] sorted = new int[initialSize]; + for (int i = 0; i < initialSize; i++) { + sorted[i] = this.delete(); } + return sorted; } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java new file mode 100644 index 000000000000..6bb965aad4d6 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java @@ -0,0 +1,56 @@ +package com.thealgorithms.datastructures.trees; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Given the root of a binary tree, returns the values of the nodes visible + * from the right side (the last node of each level in a level-order traversal). + * + *

Example: + *

+ *      1
+ *     / \
+ *    2   3
+ *     \   \
+ *      5   4
+ * Right side view: [1, 3, 4]
+ * 
+ * + *

Time complexity: O(n), Space complexity: O(n) + * + * @see LeetCode #199 + */ +public final class RightSideViewOfBinaryTree { + private RightSideViewOfBinaryTree() { + } + + public static List rightSideView(BinaryTree.Node root) { + List result = new ArrayList<>(); + if (root == null) { + return result; + } + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + for (int i = 0; i < levelSize; i++) { + BinaryTree.Node node = queue.poll(); + if (i == levelSize - 1) { + result.add(node.data); + } + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + } + return result; + } +} diff --git a/src/main/java/com/thealgorithms/maths/CatalanNumbers.java b/src/main/java/com/thealgorithms/maths/CatalanNumbers.java index 387756bdfa0c..2f304d1c2b3c 100644 --- a/src/main/java/com/thealgorithms/maths/CatalanNumbers.java +++ b/src/main/java/com/thealgorithms/maths/CatalanNumbers.java @@ -1,38 +1,43 @@ package com.thealgorithms.maths; +import java.math.BigInteger; + /** * Calculate Catalan Numbers */ public final class CatalanNumbers { + private static final int MAX_SUPPORTED_INDEX = 35; + private CatalanNumbers() { } /** - * Calculate the nth Catalan number using a recursive formula. + * Calculate the nth Catalan number using the factorial formula. * * @param n the index of the Catalan number to compute * @return the nth Catalan number + * @throws IllegalArgumentException if n is negative or exceeds the maximum supported index for long */ public static long catalan(final int n) { if (n < 0) { throw new IllegalArgumentException("Index must be non-negative"); } - return factorial(2 * n) / (factorial(n + 1) * factorial(n)); + if (n > MAX_SUPPORTED_INDEX) { + throw new IllegalArgumentException("Index exceeds maximum supported value for long"); + } + return factorial(2 * n).divide(factorial(n + 1).multiply(factorial(n))).longValueExact(); } /** - * Calculate the factorial of a number. + * Calculate the factorial of a number using BigInteger to prevent integer overflow. * * @param n the number to compute the factorial for - * @return the factorial of n + * @return the factorial of n as BigInteger */ - private static long factorial(final int n) { - if (n == 0 || n == 1) { - return 1; - } - long result = 1; + private static BigInteger factorial(final int n) { + BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) { - result *= i; + result = result.multiply(BigInteger.valueOf(i)); } return result; } diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index f7e2c7629551..b6c09c2cdb82 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -6,7 +6,7 @@ private DistanceFormula() { public static double euclideanDistance(double x1, double y1, double x2, double y2) { double dX = Math.pow(x2 - x1, 2); - double dY = Math.pow(y2 - x1, 2); + double dY = Math.pow(y2 - y1, 2); return Math.sqrt(dX + dY); } diff --git a/src/main/java/com/thealgorithms/maths/Pow.java b/src/main/java/com/thealgorithms/maths/Pow.java index 377b37ac4569..33dda5ba2ddc 100644 --- a/src/main/java/com/thealgorithms/maths/Pow.java +++ b/src/main/java/com/thealgorithms/maths/Pow.java @@ -22,6 +22,7 @@ private Pow() { * @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer. * @return the result of {@code a}{@code b} as a {@code long}. * @throws IllegalArgumentException if {@code b} is negative. + * @throws ArithmeticException if the result overflows a {@code long}. */ public static long pow(int a, int b) { if (b < 0) { @@ -29,7 +30,7 @@ public static long pow(int a, int b) { } long result = 1; for (int i = 1; i <= b; i++) { - result *= a; + result = Math.multiplyExact(result, (long) a); } return result; } diff --git a/src/main/java/com/thealgorithms/maths/SmithNumber.java b/src/main/java/com/thealgorithms/maths/SmithNumber.java index c06e0023d9bb..41d7bebed257 100644 --- a/src/main/java/com/thealgorithms/maths/SmithNumber.java +++ b/src/main/java/com/thealgorithms/maths/SmithNumber.java @@ -18,10 +18,9 @@ private SmithNumber() { private static int primeFactorDigitSum(int n) { int sum = 0; - int num = n; // Factorize the number using trial division - for (int i = 2; i * i <= num; i++) { + for (int i = 2; (long) i * i <= n; i++) { while (n % i == 0) { // while i divides n sum += SumOfDigits.sumOfDigits(i); // add sum of digits of factor n /= i; // divide n by the factor @@ -43,7 +42,7 @@ private static int primeFactorDigitSum(int n) { * @return {@code true} if {@code number} is a Smith number, otherwise false */ public static boolean isSmithNumber(int number) { - if (PrimeCheck.isPrime(number)) { + if (number <= 3 || PrimeCheck.isPrime(number)) { return false; // Smith numbers must be composite } diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java index 7154ba073136..1a46077e25f5 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java @@ -3,6 +3,8 @@ public final class MedianOfRunningArrayInteger extends MedianOfRunningArray { @Override public Integer calculateAverage(final Integer a, final Integer b) { - return (a + b) / 2; + // Widen to long so that summing values near Integer.MAX_VALUE does not overflow. + final long sum = (long) a + b; + return (int) (sum / 2); } } diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java index 1f138c6313fb..c7bf246d3523 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java @@ -1,8 +1,11 @@ package com.thealgorithms.misc; +import java.math.BigInteger; + public final class MedianOfRunningArrayLong extends MedianOfRunningArray { @Override public Long calculateAverage(final Long a, final Long b) { - return (a + b) / 2L; + // a + b overflows a long near its bounds and there is no wider primitive to widen to. + return BigInteger.valueOf(a).add(BigInteger.valueOf(b)).divide(BigInteger.TWO).longValueExact(); } } diff --git a/src/main/java/com/thealgorithms/misc/MoveZeroes.java b/src/main/java/com/thealgorithms/misc/MoveZeroes.java new file mode 100644 index 000000000000..31d6eb8dad98 --- /dev/null +++ b/src/main/java/com/thealgorithms/misc/MoveZeroes.java @@ -0,0 +1,28 @@ +package com.thealgorithms.misc; + +/** + * Moves all zeroes in an array to the end while maintaining the relative + * order of non-zero elements. The operation is performed in-place. + * + *

Example: [0, 1, 0, 3, 12] -> [1, 3, 12, 0, 0] + * + *

Time complexity: O(n), Space complexity: O(1) + * + * @see LeetCode #283 + */ +public final class MoveZeroes { + private MoveZeroes() { + } + + public static void moveZeroes(int[] nums) { + int insertPos = 0; + for (int num : nums) { + if (num != 0) { + nums[insertPos++] = num; + } + } + while (insertPos < nums.length) { + nums[insertPos++] = 0; + } + } +} diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index ecdcd36adf21..4b66cf2a220e 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -20,7 +20,7 @@ * doesn't exist in the array, an array * {-1, -1} will be returned. */ -public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { +public final class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { @Override public > int[] find(T[][] matrix, T key) { @@ -28,6 +28,10 @@ public > int[] find(T[][] matrix, T key) { } public static > int[] search(T[][] matrix, T target) { + if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0 || target == null) { + return new int[] {-1, -1}; + } + int rowPointer = 0; // The pointer at 0th row int colPointer = matrix[0].length - 1; // The pointer at end column diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 192c4d26c735..9455636a4c9c 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -19,24 +19,39 @@ private SaddlebackSearch() { } /** - * This method performs Saddleback Search + * Searches for a key in a row-wise and column-wise sorted 2D array starting from the bottom-left corner. + * + * @param arr The sorted matrix. + * @param key The element to search for. + * @throws IllegalArgumentException if the array is null or empty. + * @return The index (row and column) of the element if found. Else returns {-1, -1}. + */ + public static int[] find(int[][] arr, int key) { + if (arr == null || arr.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + return find(arr, arr.length - 1, 0, key); + } + + /** + * This method performs Saddleback Search starting from the specified row and column. * * @param arr The **Sorted** array in which we will search the element. * @param row the current row. * @param col the current column. * @param key the element that we want to search for. - * @throws IllegalArgumentException if the array is empty. + * @throws IllegalArgumentException if the array is null or empty. * @return The index(row and column) of the element if found. Else returns * -1 -1. */ - static int[] find(int[][] arr, int row, int col, int key) { - if (arr.length == 0) { + public static int[] find(int[][] arr, int row, int col, int key) { + if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Array is empty"); } // array to store the answer row and column int[] ans = {-1, -1}; - if (row < 0 || col >= arr[row].length) { + if (row < 0 || row >= arr.length || arr[row] == null || col < 0 || col >= arr[row].length) { return ans; } if (arr[row][col] == key) { diff --git a/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java new file mode 100644 index 000000000000..b220c82542d4 --- /dev/null +++ b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java @@ -0,0 +1,203 @@ +package com.thealgorithms.streaming; + +/** + * Watches the timestamps of a stream for samples that arrive out of order or twice. + * + *

Every windowed algorithm assumes that time moves forward. When it does not, nothing crashes: + * the window simply holds samples that never coexisted, a rate is computed over a negative interval, + * and a duplicate counts twice in an average. Retries, buffers flushed after a reconnect, several + * producers writing into one topic and a clock stepped backwards all produce exactly that, and the + * only cheap defence is to check the order explicitly. + * + *

Each timestamp is compared with the one immediately before it and classified as + * {@link Order#INCREASING}, {@link Order#DUPLICATE} or {@link Order#BACKWARDS}. The checker reports, + * it does not reorder or drop anything, so {@link #lastTimestamp()} is always the most recent sample + * and not the largest one seen. + * + *

Besides the counters it keeps the worst backwards step, which is what a caller needs in order to + * size a reordering buffer: a stream whose worst violation is 20 milliseconds can be repaired by + * holding samples for 20 milliseconds, while one that jumps back an hour cannot be repaired at all. + * + *

Usage

+ * + *
{@code
+ * TimestampOrderChecker checker = new TimestampOrderChecker();
+ * for (double timestamp : timestamps) {
+ *     if (checker.accept(timestamp).isViolation()) {
+ *         quarantine(timestamp);
+ *     }
+ * }
+ * }
+ * + *

Each sample costs O(1) time and the checker keeps O(1) state. This class is not thread-safe. + * + * @see Monotonic function + */ +public final class TimestampOrderChecker { + + private double lastTimestamp; + private double worstBackwardsStep; + private boolean started; + private long count; + private long duplicateCount; + private long backwardsCount; + private Order lastOrder = Order.INCREASING; + + /** + * Feeds the timestamp of one sample. + * + * @param timestamp when the sample arrived + * @return how this timestamp relates to the previous one; the first one is always + * {@link Order#INCREASING} + * @throws IllegalArgumentException if {@code timestamp} is NaN or infinite + */ + public Order accept(double timestamp) { + if (!Double.isFinite(timestamp)) { + throw new IllegalArgumentException("Timestamps must be finite, but was " + timestamp); + } + + Order order = Order.INCREASING; + if (started) { + if (timestamp == lastTimestamp) { + order = Order.DUPLICATE; + duplicateCount++; + } else if (timestamp < lastTimestamp) { + order = Order.BACKWARDS; + backwardsCount++; + worstBackwardsStep = Math.max(worstBackwardsStep, lastTimestamp - timestamp); + } + } + + lastTimestamp = timestamp; + started = true; + count++; + lastOrder = order; + return order; + } + + /** + * Runs the checker over a whole series of timestamps. + * + * @param timestamps the timestamps to inspect + * @return a new array of the same length holding the verdict for every timestamp + * @throws IllegalArgumentException if a timestamp is NaN or infinite + * @throws NullPointerException if {@code timestamps} is {@code null} + */ + public Order[] scan(double[] timestamps) { + Order[] verdicts = new Order[timestamps.length]; + for (int i = 0; i < timestamps.length; i++) { + verdicts[i] = accept(timestamps[i]); + } + return verdicts; + } + + /** + * Returns the verdict on the most recent timestamp. + * + * @return the last verdict, {@link Order#INCREASING} before the first timestamp + */ + public Order lastOrder() { + return lastOrder; + } + + /** + * Tells whether every timestamp so far moved forward. + * + * @return {@code true} if neither a duplicate nor a backwards step has been seen + */ + public boolean isOrdered() { + return duplicateCount == 0 && backwardsCount == 0; + } + + /** + * Returns the timestamp of the most recent sample, which is not necessarily the largest one seen. + * + * @return the last timestamp + * @throws IllegalStateException if no timestamp has been accepted yet + */ + public double lastTimestamp() { + if (!started) { + throw new IllegalStateException("The checker has not seen any timestamp yet"); + } + return lastTimestamp; + } + + /** + * Returns the largest distance a timestamp ever jumped backwards, which is how long a reordering + * buffer would have to hold a sample to repair this stream. + * + * @return the worst backwards step, {@code 0} if the stream never went backwards + */ + public double worstBackwardsStep() { + return worstBackwardsStep; + } + + /** + * Returns how many timestamps have been inspected since the last reset. + * + * @return the sample count + */ + public long count() { + return count; + } + + /** + * Returns how many timestamps repeated the one before them. + * + * @return the duplicate count + */ + public long duplicateCount() { + return duplicateCount; + } + + /** + * Returns how many timestamps were smaller than the one before them. + * + * @return the backwards count + */ + public long backwardsCount() { + return backwardsCount; + } + + /** + * Forgets every timestamp seen so far. + */ + public void reset() { + lastTimestamp = 0.0; + worstBackwardsStep = 0.0; + started = false; + count = 0; + duplicateCount = 0; + backwardsCount = 0; + lastOrder = Order.INCREASING; + } + + @Override + public String toString() { + return "TimestampOrderChecker{samples=" + count + ", duplicates=" + duplicateCount + ", backwards=" + backwardsCount + ", worstStep=" + worstBackwardsStep + "}"; + } + + /** + * How a timestamp relates to the one before it. + */ + public enum Order { + + /** The timestamp moved forward, which is the only healthy case. */ + INCREASING, + + /** The timestamp repeats the previous one. */ + DUPLICATE, + + /** The timestamp is older than the previous one. */ + BACKWARDS; + + /** + * Tells whether this verdict reports a broken timeline. + * + * @return {@code true} for {@link #DUPLICATE} and {@link #BACKWARDS} + */ + public boolean isViolation() { + return this != INCREASING; + } + } +} diff --git a/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java b/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java index 1fe792028dca..69ac30755ee5 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java @@ -20,6 +20,18 @@ public void testGrayToBinary() { assertEquals(1, GrayCodeConversion.grayToBinary(1)); // 001 -> 001 } + @Test + public void testBinaryToGrayWithHighBitSet() { + assertEquals(0x80000000, GrayCodeConversion.binaryToGray(0xFFFFFFFF)); + assertEquals(0xC0000000, GrayCodeConversion.binaryToGray(0x80000000)); + } + + @Test + public void testGrayToBinaryWithHighBitSet() { + assertEquals(0xFFFFFFFF, GrayCodeConversion.grayToBinary(0x80000000)); + assertEquals(0x80000000, GrayCodeConversion.grayToBinary(0xC0000000)); + } + @Test public void testBinaryGrayCycle() { int binary = 9; // 1001 in binary diff --git a/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java b/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java new file mode 100644 index 000000000000..61d7c17ec663 --- /dev/null +++ b/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java @@ -0,0 +1,92 @@ +package com.thealgorithms.ciphers; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class ChaCha20Test { + + @Test + void quarterRoundMatchesRfc8439Vector() { + int[] state = {0x11111111, 0x01020304, 0x9b8d6f43, 0x01234567}; + + ChaCha20.quarterRound(state, 0, 1, 2, 3); + + assertArrayEquals(new int[] {0xea2a92f4, 0xcb1cf8ce, 0x4581472e, 0x5881c4bb}, state); + } + + @Test + void encryptingZeroesMatchesRfc8439BlockVector() { + byte[] key = new byte[32]; + for (int i = 0; i < key.length; i++) { + key[i] = (byte) i; + } + + byte[] nonce = {0, 0, 0, 9, 0, 0, 0, 0x4a, 0, 0, 0, 0}; + byte[] expected = {0x10, (byte) 0xf1, (byte) 0xe7, (byte) 0xe4, (byte) 0xd1, 0x3b, 0x59, 0x15, 0x50, 0x0f, (byte) 0xdd, 0x1f, (byte) 0xa3, 0x20, 0x71, (byte) 0xc4, (byte) 0xc7, (byte) 0xd1, (byte) 0xf4, (byte) 0xc7, 0x33, (byte) 0xc0, 0x68, 0x03, 0x04, 0x22, (byte) 0xaa, (byte) 0x9a, + (byte) 0xc3, (byte) 0xd4, 0x6c, 0x4e, (byte) 0xd2, (byte) 0x82, 0x64, 0x46, 0x07, (byte) 0x9f, (byte) 0xaa, 0x09, 0x14, (byte) 0xc2, (byte) 0xd7, 0x05, (byte) 0xd9, (byte) 0x8b, 0x02, (byte) 0xa2, (byte) 0xb5, 0x12, (byte) 0x9c, (byte) 0xd1, (byte) 0xde, 0x16, 0x4e, (byte) 0xb9, + (byte) 0xcb, (byte) 0xd0, (byte) 0x83, (byte) 0xe8, (byte) 0xa2, 0x50, 0x3c, 0x4e}; + + byte[] actual = ChaCha20.encrypt(new byte[64], key, nonce, 1); + + assertArrayEquals(expected, actual); + } + + @Test + void decryptRestoresInputAcrossMultipleBlocks() { + byte[] input = new byte[130]; + for (int i = 0; i < input.length; i++) { + input[i] = (byte) (i * 3); + } + + byte[] key = new byte[32]; + byte[] nonce = new byte[12]; + + byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 7); + byte[] decrypted = ChaCha20.decrypt(encrypted, key, nonce, 7); + + assertArrayEquals(input, decrypted); + } + + @Test + void handlesPartialBlocksAroundBlockBoundary() { + for (int length : new int[] {1, 63, 65}) { + byte[] input = new byte[length]; + for (int i = 0; i < input.length; i++) { + input[i] = (byte) (i + 1); + } + + byte[] key = new byte[32]; + byte[] nonce = new byte[12]; + byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 0); + + assertArrayEquals(input, ChaCha20.decrypt(encrypted, key, nonce, 0)); + } + } + + @Test + void emptyInputReturnsEmptyOutput() { + assertArrayEquals(new byte[0], ChaCha20.encrypt(new byte[0], new byte[32], new byte[12], 1)); + } + + @Test + void maximumCounterCanProcessOneBlock() { + byte[] input = new byte[64]; + + assertArrayEquals(input, ChaCha20.decrypt(ChaCha20.encrypt(input, new byte[32], new byte[12], 0xFFFF_FFFFL), new byte[32], new byte[12], 0xFFFF_FFFFL)); + } + + @Test + void counterOverflowIsRejected() { + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[65], new byte[32], new byte[12], 0xFFFF_FFFFL)); + } + + @Test + void invalidKeyNonceAndCounterAreRejected() { + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[31], new byte[12], 0)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[11], 0)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], -1)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], 0x1_0000_0000L)); + } +} diff --git a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java index 8121b6177aa9..3f8b81c0d069 100644 --- a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.ciphers; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; @@ -33,4 +34,25 @@ void hillCipherDecryptTest() { // then assertEquals("ACT", plainText); } + + @Test + void rejectsNonInvertibleKeyWithEvenDeterminant() { + // det = 2, gcd(2, 26) = 2: passes the old zero-check but has no inverse mod 26 + int[][] keyMatrix = {{1, 0}, {0, 2}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("AA", keyMatrix)); + } + + @Test + void rejectsNonInvertibleKeyWithDeterminantThirteen() { + // det = 13, gcd(13, 26) = 13: also not invertible mod 26 + int[][] keyMatrix = {{13, 0}, {0, 1}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("BB", keyMatrix)); + } + + @Test + void acceptsKeyWithNegativeCoprimeDeterminant() { + // det = -1, coprime with 26: a valid key that a naive signed modulo would misclassify + int[][] keyMatrix = {{1, 2}, {1, 1}}; + assertEquals("XP", hillCipher.encrypt("HI", keyMatrix)); + } } diff --git a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java index fa497e4682e8..2386aa735b7e 100644 --- a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java +++ b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java @@ -34,4 +34,30 @@ public void testEncryptionAndDecryption() { assertEquals(plaintext, decryptedText); } + + @Test + public void testLowercaseKeyBehavesLikeUppercase() { + PlayfairCipher lowercase = new PlayfairCipher("monarchy"); + PlayfairCipher uppercase = new PlayfairCipher("MONARCHY"); + + assertEquals(uppercase.encrypt("HELLO"), lowercase.encrypt("HELLO")); + assertEquals("CFSUPM", lowercase.encrypt("HELLO")); + } + + @Test + public void testKeyContainingJStillCoversZ() { + PlayfairCipher playfairCipher = new PlayfairCipher("JUMP"); + + String decryptedText = playfairCipher.decrypt(playfairCipher.encrypt("ZOO")); + + assertEquals("ZOXO", decryptedText); + } + + @Test + public void testKeyWithNonLettersIsStripped() { + PlayfairCipher messy = new PlayfairCipher("Mon@rchy2026"); + PlayfairCipher clean = new PlayfairCipher("MONRCHY"); + + assertEquals(clean.encrypt("HELLO"), messy.encrypt("HELLO")); + } } diff --git a/src/test/java/com/thealgorithms/conversions/HexToOctTest.java b/src/test/java/com/thealgorithms/conversions/HexToOctTest.java index b3f94b19b6e6..5793b640316b 100644 --- a/src/test/java/com/thealgorithms/conversions/HexToOctTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexToOctTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; @@ -30,4 +31,11 @@ public void testHexToOctal() { assertEquals(0, HexToOct.hexToOctal("0")); assertEquals(7777, HexToOct.hexToOctal("FFF")); } + + @Test + public void testInvalidHexDigitThrows() { + assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToDecimal("1G")); + assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToDecimal("0x1A")); + assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToOctal("Z")); + } } diff --git a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java index 8e007151c301..eb440f647e44 100644 --- a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java +++ b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java @@ -32,4 +32,14 @@ public void testConvertOctalToBinaryWithZeroPadding() { assertEquals(100001010, OctalToBinary.convertOctalToBinary(412)); assertEquals(101101110, OctalToBinary.convertOctalToBinary(556)); } + + @Test + public void testConvertOctalToBinaryLargeInput() { + // Regression: digit position overflowed int for octal inputs with 5+ digits + assertEquals(1000000000000L, OctalToBinary.convertOctalToBinary(10000)); + assertEquals(1000000000001L, OctalToBinary.convertOctalToBinary(10001)); + assertEquals(111111111111111L, OctalToBinary.convertOctalToBinary(77777)); + assertEquals(111111111111111111L, OctalToBinary.convertOctalToBinary(777777)); + assertEquals(1001001001001001001L, OctalToBinary.convertOctalToBinary(1111111)); + } } diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java index 8f93bd630aa7..c493a141c61c 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java @@ -55,13 +55,19 @@ void testHeapSort() { queue.insert(1); queue.insert(3); - // Delete all elements to sort the queue - int[] sortedArray = new int[5]; - for (int i = 0; i < 5; i++) { - sortedArray[i] = queue.delete(); - } + int[] sortedArray = queue.heapSort(); Assertions.assertArrayEquals(new int[] {1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order."); + Assertions.assertTrue(queue.isEmpty(), "The queue should be empty after heap sort."); + } + + @Test + void testHeapSortEmptyQueue() { + MinPriorityQueue queue = new MinPriorityQueue(5); + int[] sortedArray = queue.heapSort(); + + Assertions.assertEquals(0, sortedArray.length, "Sorting an empty queue should return an empty array."); + Assertions.assertTrue(queue.isEmpty(), "The queue should remain empty."); } @Test diff --git a/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java new file mode 100644 index 000000000000..ded92d4d8de5 --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java @@ -0,0 +1,60 @@ +package com.thealgorithms.datastructures.trees; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class RightSideViewOfBinaryTreeTest { + + @Test + public void testNullRoot() { + assertEquals(Collections.emptyList(), RightSideViewOfBinaryTree.rightSideView(null)); + } + + @Test + public void testSingleNode() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1}); + assertEquals(List.of(1), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + / \ + 2 3 + \ \ + 5 4 + */ + @Test + public void testRightSideView() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, null, 5, null, 4}); + assertEquals(List.of(1, 3, 4), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + / + 2 + / + 3 + */ + @Test + public void testLeftSkewedTree() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3}); + assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + \ + 2 + \ + 3 + */ + @Test + public void testRightSkewedTree() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, null, 2, null, 3}); + assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root)); + } +} diff --git a/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java b/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java index 2248ffd93732..cf8b1ddabc98 100644 --- a/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/CatalanNumbersTest.java @@ -19,7 +19,8 @@ class CatalanNumbersTest { * [input number, expected Catalan number for that input] */ static Stream catalanNumbersProvider() { - return Stream.of(new Object[] {0, 1}, new Object[] {1, 1}, new Object[] {2, 2}, new Object[] {3, 5}, new Object[] {4, 14}, new Object[] {5, 42}, new Object[] {6, 132}, new Object[] {7, 429}, new Object[] {8, 1430}, new Object[] {9, 4862}, new Object[] {10, 16796}); + return Stream.of(new Object[] {0, 1L}, new Object[] {1, 1L}, new Object[] {2, 2L}, new Object[] {3, 5L}, new Object[] {4, 14L}, new Object[] {5, 42L}, new Object[] {6, 132L}, new Object[] {7, 429L}, new Object[] {8, 1430L}, new Object[] {9, 4862L}, new Object[] {10, 16796L}, + new Object[] {11, 58786L}, new Object[] {15, 9694845L}, new Object[] {35, 3116285494907301262L}); } /** @@ -28,7 +29,7 @@ static Stream catalanNumbersProvider() { */ @ParameterizedTest @MethodSource("catalanNumbersProvider") - void testCatalanNumbers(int input, int expected) { + void testCatalanNumbers(int input, long expected) { assertEquals(expected, CatalanNumbers.catalan(input), () -> String.format("Catalan number for input %d should be %d", input, expected)); } @@ -39,5 +40,6 @@ void testCatalanNumbers(int input, int expected) { void testIllegalInput() { assertThrows(IllegalArgumentException.class, () -> CatalanNumbers.catalan(-1)); assertThrows(IllegalArgumentException.class, () -> CatalanNumbers.catalan(-5)); + assertThrows(IllegalArgumentException.class, () -> CatalanNumbers.catalan(36)); } } diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index 66f3b7b03938..d761326558a4 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -14,17 +14,32 @@ void euclideanTest1() { @Test void euclideanTest2() { - Assertions.assertEquals(7.0710678118654755, DistanceFormula.euclideanDistance(1, 3, 8, 0)); + Assertions.assertEquals(7.615773105863909, DistanceFormula.euclideanDistance(1, 3, 8, 0)); } @Test void euclideanTest3() { - Assertions.assertEquals(110.91911467371168, DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100)); + Assertions.assertEquals(105.07188015829927, DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100)); } @Test void euclideanTest4() { - Assertions.assertEquals(19022.067605809836, DistanceFormula.euclideanDistance(1000, 13, 20000, 84)); + Assertions.assertEquals(19000.13265743163, DistanceFormula.euclideanDistance(1000, 13, 20000, 84)); + } + + @Test + void euclideanTestZeroDistance() { + Assertions.assertEquals(0.0, DistanceFormula.euclideanDistance(0, 0, 0, 0)); + } + + @Test + void euclideanTestPythagoreanTriple() { + Assertions.assertEquals(5.0, DistanceFormula.euclideanDistance(0, 0, 3, 4)); + } + + @Test + void euclideanTestNegativeCoordinates() { + Assertions.assertEquals(5.0, DistanceFormula.euclideanDistance(-1, -2, 2, 2)); } @Test diff --git a/src/test/java/com/thealgorithms/maths/SmithNumberTest.java b/src/test/java/com/thealgorithms/maths/SmithNumberTest.java index 4e2ba0b88e33..b073cda880fb 100644 --- a/src/test/java/com/thealgorithms/maths/SmithNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/SmithNumberTest.java @@ -9,13 +9,13 @@ class SmithNumberTest { @ParameterizedTest - @CsvSource({"4", "22", "121", "562", "985", "4937775"}) + @CsvSource({"4", "22", "27", "58", "85", "94", "121", "562", "985", "4937775"}) void positiveSmithNumbersTest(int n) { assertTrue(SmithNumber.isSmithNumber(n)); } @ParameterizedTest - @CsvSource({"2", "11", "100", "550", "999", "1234557"}) + @CsvSource({"-22", "-4", "-1", "0", "1", "2", "3", "5", "6", "8", "9", "10", "11", "100", "550", "999", "1234557"}) void negativeSmithNumbersTest(int n) { assertFalse(SmithNumber.isSmithNumber(n)); } diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java index c4a74af0ba8b..aa1d46c223d0 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -190,6 +190,42 @@ public void testWithLongValues() { assertEquals(46116860244273878L, stream.getMedian()); } + @Test + public void testWithIntegerValuesNearMaxValue() { + var stream = new MedianOfRunningArrayInteger(); + stream.insert(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, stream.getMedian()); + stream.insert(Integer.MAX_VALUE - 2); + assertEquals(Integer.MAX_VALUE - 1, stream.getMedian()); + stream.insert(2000000000); + assertEquals(Integer.MAX_VALUE - 2, stream.getMedian()); + } + + @Test + public void testWithIntegerValuesNearMinValue() { + var stream = new MedianOfRunningArrayInteger(); + stream.insert(Integer.MIN_VALUE); + stream.insert(Integer.MIN_VALUE + 2); + assertEquals(Integer.MIN_VALUE + 1, stream.getMedian()); + } + + @Test + public void testWithLongValuesNearMaxValue() { + var stream = new MedianOfRunningArrayLong(); + stream.insert(Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, stream.getMedian()); + stream.insert(Long.MAX_VALUE - 2); + assertEquals(Long.MAX_VALUE - 1, stream.getMedian()); + } + + @Test + public void testWithLongValuesNearMinValue() { + var stream = new MedianOfRunningArrayLong(); + stream.insert(Long.MIN_VALUE); + stream.insert(Long.MIN_VALUE + 2); + assertEquals(Long.MIN_VALUE + 1, stream.getMedian()); + } + @Test public void testWithDoubleValues() { var stream = new MedianOfRunningArrayDouble(); diff --git a/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java b/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java new file mode 100644 index 000000000000..9c26e6b7340e --- /dev/null +++ b/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java @@ -0,0 +1,36 @@ +package com.thealgorithms.misc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.Test; + +public class MoveZeroesTest { + + @Test + public void testMoveZeroes() { + int[] nums = {0, 1, 0, 3, 12}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {1, 3, 12, 0, 0}, nums); + } + + @Test + public void testNoZeroes() { + int[] nums = {1, 2, 3}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {1, 2, 3}, nums); + } + + @Test + public void testAllZeroes() { + int[] nums = {0, 0, 0}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {0, 0, 0}, nums); + } + + @Test + public void testSingleElement() { + int[] nums = {0}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {0}, nums); + } +} diff --git a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java index 8d1423cbeeb0..6740baeb3c89 100644 --- a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java @@ -237,4 +237,56 @@ public void rowColumnSorted2dArrayBinarySearchTestTallMatrixNotFound() { assertEquals(expected[0], ans[0]); assertEquals(expected[1], ans[1]); } + + @Test + public void testNullMatrixReturnsNotFound() { + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(null, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testEmptyMatrixReturnsNotFound() { + Integer[][] matrix = {}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testEmptyFirstRowReturnsNotFound() { + Integer[][] matrix = {{}}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testNullTargetReturnsNotFound() { + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, null); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testNullFirstRowReturnsNotFound() { + Integer[][] matrix = {null}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testFindMethodThroughInterface() { + RowColumnWiseSorted2dArrayBinarySearch searcher = new RowColumnWiseSorted2dArrayBinarySearch(); + int[] ans = searcher.find(WIDE_RECTANGULAR_MATRIX, 35); + int[] expected = {1, 2}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } } diff --git a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java index ec22cbf38152..e4e6b2bf107d 100644 --- a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java @@ -82,4 +82,53 @@ void testFindSingleElementNotExists() { int[] result = SaddlebackSearch.find(arr, 0, 0, 10); assertArrayEquals(new int[] {-1, -1}, result, "Element 10 should not be found in single element array"); } + + /** + * Test convenience method searching from the bottom-left corner automatically. + */ + @Test + void testFindWithConvenienceMethod() { + int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; + int[] result = SaddlebackSearch.find(arr, 4); + assertArrayEquals(new int[] {0, 3}, result, "Element 4 should be found at (0, 3) using convenience overload"); + } + + /** + * Test searching in a null array throws IllegalArgumentException. + */ + @Test + void testFindWithNullArray() { + assertThrows(IllegalArgumentException.class, () -> SaddlebackSearch.find(null, 4)); + assertThrows(IllegalArgumentException.class, () -> SaddlebackSearch.find(null, 0, 0, 4)); + } + + /** + * Test row index out of bounds returns {-1, -1}. + */ + @Test + void testFindWithRowOutOfBounds() { + int[][] arr = {{1, 2}, {3, 4}}; + int[] result = SaddlebackSearch.find(arr, 5, 0, 3); + assertArrayEquals(new int[] {-1, -1}, result, "Row index out of bounds should return {-1, -1}"); + } + + /** + * Test negative column index returns {-1, -1}. + */ + @Test + void testFindWithNegativeColumn() { + int[][] arr = {{1, 2}, {3, 4}}; + int[] result = SaddlebackSearch.find(arr, 1, -1, 3); + assertArrayEquals(new int[] {-1, -1}, result, "Negative column index should return {-1, -1}"); + } + + /** + * Test null row in matrix returns {-1, -1} safely. + */ + @Test + void testFindWithNullRowInMatrix() { + int[][] arr = {{1, 2}, null, {5, 6}}; + int[] result = SaddlebackSearch.find(arr, 1, 0, 5); + assertArrayEquals(new int[] {-1, -1}, result, "Null row in matrix should safely return {-1, -1}"); + } } diff --git a/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java b/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java new file mode 100644 index 000000000000..43867ccd15b6 --- /dev/null +++ b/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java @@ -0,0 +1,139 @@ +package com.thealgorithms.streaming; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.thealgorithms.streaming.TimestampOrderChecker.Order; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TimestampOrderCheckerTest { + + @ParameterizedTest + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) + void rejectsNonFiniteTimestamps(double timestamp) { + TimestampOrderChecker checker = new TimestampOrderChecker(); + assertThrows(IllegalArgumentException.class, () -> checker.accept(timestamp)); + } + + @Test + void startsEmpty() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + assertEquals(0, checker.count()); + assertEquals(Order.INCREASING, checker.lastOrder()); + assertTrue(checker.isOrdered()); + assertEquals(0.0, checker.worstBackwardsStep()); + assertThrows(IllegalStateException.class, checker::lastTimestamp); + } + + @Test + void theFirstTimestampIsAlwaysAccepted() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + assertEquals(Order.INCREASING, checker.accept(-500.0)); + assertEquals(-500.0, checker.lastTimestamp()); + } + + @Test + void anOrderedStreamHasNoViolations() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + for (int i = 0; i < 20; i++) { + assertEquals(Order.INCREASING, checker.accept(i)); + } + assertTrue(checker.isOrdered()); + assertEquals(20, checker.count()); + } + + @Test + void reportsADuplicate() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.accept(10.0); + + assertEquals(Order.DUPLICATE, checker.accept(10.0)); + assertEquals(1, checker.duplicateCount()); + assertEquals(0, checker.backwardsCount()); + assertFalse(checker.isOrdered()); + } + + @Test + void reportsAStepBackwards() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.accept(10.0); + + assertEquals(Order.BACKWARDS, checker.accept(7.5)); + assertEquals(1, checker.backwardsCount()); + assertEquals(2.5, checker.worstBackwardsStep()); + } + + @Test + @DisplayName("the worst backwards step is the largest one, not the last one") + void keepsTheWorstBackwardsStep() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + checker.scan(new double[] {100.0, 60.0, 61.0, 59.0, 200.0, 199.0}); + + assertEquals(3, checker.backwardsCount()); + assertEquals(40.0, checker.worstBackwardsStep()); + } + + @Test + @DisplayName("the checker reports without reordering, so the last timestamp is the most recent one") + void doesNotReorderTheStream() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + checker.accept(100.0); + checker.accept(50.0); + + assertEquals(50.0, checker.lastTimestamp()); + assertEquals(Order.INCREASING, checker.accept(60.0), "the next sample is compared with the previous one, not with the maximum"); + } + + @Test + void scanReportsOneVerdictPerTimestamp() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + Order[] verdicts = checker.scan(new double[] {1.0, 2.0, 2.0, 1.5, 3.0}); + + Assertions.assertArrayEquals(new Order[] {Order.INCREASING, Order.INCREASING, Order.DUPLICATE, Order.BACKWARDS, Order.INCREASING}, verdicts); + } + + @Test + void theVerdictKnowsWhetherItIsAViolation() { + assertFalse(Order.INCREASING.isViolation()); + assertTrue(Order.DUPLICATE.isViolation()); + assertTrue(Order.BACKWARDS.isViolation()); + } + + @Test + void resetRestoresTheInitialState() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.scan(new double[] {5.0, 4.0, 4.0}); + + checker.reset(); + + assertEquals(0, checker.count()); + assertEquals(0, checker.duplicateCount()); + assertEquals(0, checker.backwardsCount()); + assertEquals(0.0, checker.worstBackwardsStep()); + assertTrue(checker.isOrdered()); + assertThrows(IllegalStateException.class, checker::lastTimestamp); + } + + @Test + void toStringMentionsTheState() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.scan(new double[] {5.0, 4.0}); + + String text = checker.toString(); + + assertTrue(text.contains("TimestampOrderChecker")); + assertTrue(text.contains("backwards=1")); + } +}