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/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 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/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.
+ *
+ * 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/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/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/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"));
+ }
+}
Usage
+ *
+ * {@code
+ * TimestampOrderChecker checker = new TimestampOrderChecker();
+ * for (double timestamp : timestamps) {
+ * if (checker.accept(timestamp).isViolation()) {
+ * quarantine(timestamp);
+ * }
+ * }
+ * }
+ *
+ *