repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/OneBitDifferenceTest.java | src/test/java/com/thealgorithms/bitmanipulation/OneBitDifferenceTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class OneBitDifferenceTest {
@ParameterizedTest
@CsvSource({"7, 5, true", "3, 2, true", "10, 8, true", "15, 15, false", "4, 1, false"})
void testDifferByOneBit(int x, int y, boolean expected) {
assertEquals(expected, OneBitDifference.differByOneBit(x, y));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/BcdConversionTest.java | src/test/java/com/thealgorithms/bitmanipulation/BcdConversionTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class BcdConversionTest {
@Test
public void testBcdToDecimal() {
int decimal = BcdConversion.bcdToDecimal(0x1234);
assertEquals(1234, decimal); // BCD 0x1234 should convert to decimal 1234
}
@Test
public void testDecimalToBcd() {
int bcd = BcdConversion.decimalToBcd(1234);
assertEquals(0x1234, bcd); // Decimal 1234 should convert to BCD 0x1234
}
@Test
public void testBcdToDecimalZero() {
int decimal = BcdConversion.bcdToDecimal(0x0);
assertEquals(0, decimal); // BCD 0x0 should convert to decimal 0
}
@Test
public void testDecimalToBcdZero() {
int bcd = BcdConversion.decimalToBcd(0);
assertEquals(0x0, bcd); // Decimal 0 should convert to BCD 0x0
}
@Test
public void testBcdToDecimalSingleDigit() {
int decimal = BcdConversion.bcdToDecimal(0x7);
assertEquals(7, decimal); // BCD 0x7 should convert to decimal 7
}
@Test
public void testDecimalToBcdSingleDigit() {
int bcd = BcdConversion.decimalToBcd(7);
assertEquals(0x7, bcd); // Decimal 7 should convert to BCD 0x7
}
@Test
public void testBcdToDecimalMaxValue() {
int decimal = BcdConversion.bcdToDecimal(0x9999);
assertEquals(9999, decimal); // BCD 0x9999 should convert to decimal 9999
}
@Test
public void testDecimalToBcdMaxValue() {
int bcd = BcdConversion.decimalToBcd(9999);
assertEquals(0x9999, bcd); // Decimal 9999 should convert to BCD 0x9999
}
@Test
public void testBcdToDecimalInvalidHighDigit() {
// Testing invalid BCD input where one of the digits is > 9
assertThrows(IllegalArgumentException.class, () -> {
BcdConversion.bcdToDecimal(0x123A); // Invalid BCD, 'A' is not a valid digit
});
}
@Test
public void testDecimalToBcdInvalidValue() {
// Testing conversion for numbers greater than 9999, which cannot be represented in BCD
assertThrows(IllegalArgumentException.class, () -> {
BcdConversion.decimalToBcd(10000); // 10000 is too large for BCD representation
});
}
@Test
public void testBcdToDecimalLeadingZeroes() {
int decimal = BcdConversion.bcdToDecimal(0x0234);
assertEquals(234, decimal); // BCD 0x0234 should convert to decimal 234, ignoring leading zero
}
@Test
public void testDecimalToBcdLeadingZeroes() {
int bcd = BcdConversion.decimalToBcd(234);
assertEquals(0x0234, bcd); // Decimal 234 should convert to BCD 0x0234
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/Xs3ConversionTest.java | src/test/java/com/thealgorithms/bitmanipulation/Xs3ConversionTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the Xs3Conversion class.
*/
public class Xs3ConversionTest {
/**
* Test the xs3ToBinary method with an XS-3 number.
*/
@Test
public void testXs3ToBinary() {
int binary = Xs3Conversion.xs3ToBinary(0x4567);
assertEquals(1234, binary); // XS-3 0x4567 should convert to binary 1234
}
/**
* Test the binaryToXs3 method with a binary number.
*/
@Test
public void testBinaryToXs3() {
int xs3 = Xs3Conversion.binaryToXs3(1234);
assertEquals(0x4567, xs3); // Binary 1234 should convert to XS-3 0x4567
}
/**
* Test the xs3ToBinary method with zero.
*/
@Test
public void testXs3ToBinaryZero() {
int binary = Xs3Conversion.xs3ToBinary(0x0);
assertEquals(0, binary); // XS-3 0x0 should convert to binary 0
}
/**
* Test the binaryToXs3 method with zero.
*/
@Test
public void testBinaryToXs3Zero() {
int xs3 = Xs3Conversion.binaryToXs3(0);
assertEquals(0x0, xs3); // Binary 0 should convert to XS-3 0x0
}
/**
* Test the xs3ToBinary method with a single digit XS-3 number.
*/
@Test
public void testXs3ToBinarySingleDigit() {
int binary = Xs3Conversion.xs3ToBinary(0x5);
assertEquals(2, binary); // XS-3 0x5 should convert to binary 2
}
/**
* Test the binaryToXs3 method with a single digit binary number.
*/
@Test
public void testBinaryToXs3SingleDigit() {
int xs3 = Xs3Conversion.binaryToXs3(2);
assertEquals(0x5, xs3); // Binary 2 should convert to XS-3 0x5
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java | src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class SwapAdjacentBitsTest {
@ParameterizedTest
@CsvSource({"2, 1", // 2 (binary: 10) -> 1 (binary: 01)
"43, 23", // 43 (binary: 101011) -> 23 (binary: 010111)
"153, 102", // 153 (binary: 10011001) -> 102 (binary: 01100110)
"15, 15", // 15 (binary: 1111) -> 15 (binary: 1111) (no change)
"0, 0", // 0 (binary: 0000) -> 0 (binary: 0000) (no change)
"1, 2", // 1 (binary: 01) -> 2 (binary: 10)
"170, 85", // 170 (binary: 10101010) -> 85 (binary: 01010101)
"85, 170", // 85 (binary: 01010101) -> 170 (binary: 10101010)
"255, 255", // 255 (binary: 11111111) -> 255 (binary: 11111111) (no change)
"128, 64", // 128 (binary: 10000000) -> 64 (binary: 01000000)
"1024, 2048",
"-1, -1", // -1 (all bits 1) remains -1 (no change due to two's complement)
"-2, -3", // -2 (binary: ...1110) -> -3 (binary: ...1101)
"2147483647, -1073741825", "-2147483648, -1073741824"})
void
testSwapAdjacentBits(int input, int expected) {
assertEquals(expected, SwapAdjacentBits.swapAdjacentBits(input));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java | src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Test case for Highest Set Bit
* @author Abhinay Verma(https://github.com/Monk-AbhinayVerma)
*/
public class TwosComplementTest {
@Test
public void testTwosComplementAllZeroes() {
assertEquals("10000", TwosComplement.twosComplement("0000"));
assertEquals("1000", TwosComplement.twosComplement("000"));
assertEquals("100", TwosComplement.twosComplement("00"));
assertEquals("10", TwosComplement.twosComplement("0"));
}
@Test
public void testTwosComplementAllOnes() {
assertEquals("00001", TwosComplement.twosComplement("11111"));
assertEquals("0001", TwosComplement.twosComplement("1111"));
assertEquals("001", TwosComplement.twosComplement("111"));
assertEquals("01", TwosComplement.twosComplement("11"));
}
@Test
public void testTwosComplementMixedBits() {
assertEquals("1111", TwosComplement.twosComplement("0001")); // 1 -> 1111
assertEquals("1001", TwosComplement.twosComplement("0111")); // 0111 -> 1001
assertEquals("11001", TwosComplement.twosComplement("00111")); // 00111 -> 11001
assertEquals("011", TwosComplement.twosComplement("101")); // 101 -> 011
}
@Test
public void testTwosComplementSingleBit() {
assertEquals("10", TwosComplement.twosComplement("0")); // 0 -> 10
assertEquals("1", TwosComplement.twosComplement("1")); // 1 -> 1
}
@Test
public void testTwosComplementWithLeadingZeroes() {
assertEquals("1111", TwosComplement.twosComplement("0001")); // 0001 -> 1111
assertEquals("101", TwosComplement.twosComplement("011")); // 011 -> 101
assertEquals("110", TwosComplement.twosComplement("010")); // 010 -> 110
}
@Test
public void testInvalidBinaryInput() {
// Test for invalid input that contains non-binary characters.
assertThrows(IllegalArgumentException.class, () -> TwosComplement.twosComplement("102"));
assertThrows(IllegalArgumentException.class, () -> TwosComplement.twosComplement("abc"));
assertThrows(IllegalArgumentException.class, () -> TwosComplement.twosComplement("10a01"));
}
@Test
public void testEmptyInput() {
// Edge case: Empty input should result in an IllegalArgumentException.
assertThrows(IllegalArgumentException.class, () -> TwosComplement.twosComplement(""));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBitTest.java | src/test/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBitTest.java | package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ClearLeftmostSetBitTest {
@Test
public void testClearLeftmostSetBit() {
assertEquals(10, ClearLeftmostSetBit.clearLeftmostSetBit(26)); // 11010 -> 01010
assertEquals(0, ClearLeftmostSetBit.clearLeftmostSetBit(1)); // 1 -> 0
assertEquals(3, ClearLeftmostSetBit.clearLeftmostSetBit(7)); // 111 -> 011
assertEquals(2, ClearLeftmostSetBit.clearLeftmostSetBit(6)); // 0110 -> 0010
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/MoveToFrontTest.java | src/test/java/com/thealgorithms/compression/MoveToFrontTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.Test;
public class MoveToFrontTest {
@Test
public void testTransformAndInverseBananaExample() {
String original = "annb$aa";
String alphabet = "$abn";
List<Integer> expectedTransform = List.of(1, 3, 0, 3, 3, 3, 0);
// Test forward transform
List<Integer> actualTransform = MoveToFront.transform(original, alphabet);
assertEquals(expectedTransform, actualTransform);
// Test inverse transform
String reconstructed = MoveToFront.inverseTransform(actualTransform, alphabet);
assertEquals(original, reconstructed);
}
@Test
public void testTransformAndInverseCabaaExample() {
String original = "cabaa";
String alphabet = "abcdef";
List<Integer> expectedTransform = List.of(2, 1, 2, 1, 0);
// Test forward transform
List<Integer> actualTransform = MoveToFront.transform(original, alphabet);
assertEquals(expectedTransform, actualTransform);
// Test inverse transform
String reconstructed = MoveToFront.inverseTransform(actualTransform, alphabet);
assertEquals(original, reconstructed);
}
@Test
public void testEmptyInput() {
String original = "";
String alphabet = "abc";
List<Integer> expectedTransform = List.of();
List<Integer> actualTransform = MoveToFront.transform(original, alphabet);
assertEquals(expectedTransform, actualTransform);
String reconstructed = MoveToFront.inverseTransform(actualTransform, alphabet);
assertEquals(original, reconstructed);
}
@Test
public void testEmptyAlphabet() {
assertThrows(IllegalArgumentException.class, () -> MoveToFront.transform("abc", ""));
assertEquals("", MoveToFront.inverseTransform(List.of(1, 2), ""));
}
@Test
public void testSymbolNotInAlphabet() {
// 'd' is not in "abc"
assertThrows(IllegalArgumentException.class, () -> MoveToFront.transform("abd", "abc"));
}
@Test
public void testIndexOutOfBounds() {
// Index 5 is out of bounds for alphabet "abc"
// 1. test index >= alphabet.size()
assertThrows(IllegalArgumentException.class, () -> MoveToFront.inverseTransform(List.of(1, 2, 5), "abc"));
// 2. test index < 0
assertThrows(IllegalArgumentException.class, () -> MoveToFront.inverseTransform(List.of(1, -1, 2), "abc"));
}
@Test
public void testTransformNull() {
List<Integer> expected = List.of();
assertEquals(expected, MoveToFront.transform(null, "abc"));
assertThrows(IllegalArgumentException.class, () -> MoveToFront.transform("abc", null));
}
@Test
public void testInverseTransformNulls() {
// 1. test indices == null
assertEquals("", MoveToFront.inverseTransform(null, "abc"));
// 2. test initialAlphabet == null
assertEquals("", MoveToFront.inverseTransform(List.of(1, 2), null));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/ArithmeticCodingTest.java | src/test/java/com/thealgorithms/compression/ArithmeticCodingTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class ArithmeticCodingTest {
@Test
void testThrowsExceptionForNullOrEmptyInput() {
// Test that null input throws IllegalArgumentException
assertThrows(IllegalArgumentException.class, () -> ArithmeticCoding.compress(null));
// Test that empty string throws IllegalArgumentException
assertThrows(IllegalArgumentException.class, () -> ArithmeticCoding.compress(""));
}
@Test
void testCompressionAndDecompressionSimple() {
String original = "BABA";
Map<Character, ArithmeticCoding.Symbol> probTable = ArithmeticCoding.calculateProbabilities(original);
BigDecimal compressed = ArithmeticCoding.compress(original);
// Verify that compression produces a valid number in [0, 1)
assertNotNull(compressed);
assertTrue(compressed.compareTo(BigDecimal.ZERO) >= 0);
assertTrue(compressed.compareTo(BigDecimal.ONE) < 0);
// Verify decompression restores the original string
String decompressed = ArithmeticCoding.decompress(compressed, original.length(), probTable);
assertEquals(original, decompressed);
}
@Test
void testSymmetryWithComplexString() {
String original = "THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG";
Map<Character, ArithmeticCoding.Symbol> probTable = ArithmeticCoding.calculateProbabilities(original);
BigDecimal compressed = ArithmeticCoding.compress(original);
// Verify compression produces a number in valid range
assertTrue(compressed.compareTo(BigDecimal.ZERO) >= 0);
assertTrue(compressed.compareTo(BigDecimal.ONE) < 0);
// Verify symmetry: decompress(compress(x)) == x
String decompressed = ArithmeticCoding.decompress(compressed, original.length(), probTable);
assertEquals(original, decompressed);
}
@Test
void testSymmetryWithRepetitions() {
String original = "MISSISSIPPI";
Map<Character, ArithmeticCoding.Symbol> probTable = ArithmeticCoding.calculateProbabilities(original);
BigDecimal compressed = ArithmeticCoding.compress(original);
// Verify compression produces a number in valid range
assertTrue(compressed.compareTo(BigDecimal.ZERO) >= 0);
assertTrue(compressed.compareTo(BigDecimal.ONE) < 0);
// Verify the compression-decompression cycle
String decompressed = ArithmeticCoding.decompress(compressed, original.length(), probTable);
assertEquals(original, decompressed);
}
@Test
void testSingleCharacterString() {
String original = "AAAAA";
Map<Character, ArithmeticCoding.Symbol> probTable = ArithmeticCoding.calculateProbabilities(original);
BigDecimal compressed = ArithmeticCoding.compress(original);
// Even with a single unique character, compression should work
assertTrue(compressed.compareTo(BigDecimal.ZERO) >= 0);
assertTrue(compressed.compareTo(BigDecimal.ONE) < 0);
String decompressed = ArithmeticCoding.decompress(compressed, original.length(), probTable);
assertEquals(original, decompressed);
}
@Test
void testCompressionOutputDemo() {
// Demonstrate actual compression output similar to LZW test
String original = "BABA";
BigDecimal compressed = ArithmeticCoding.compress(original);
// Example: "BABA" compresses to approximately 0.625
// This shows that the entire message is encoded as a single number
System.out.println("Original: " + original);
System.out.println("Compressed to: " + compressed);
System.out.println("Compression: " + original.length() + " characters -> 1 BigDecimal number");
// Verify the compressed value is in valid range [0, 1)
assertTrue(compressed.compareTo(BigDecimal.ZERO) >= 0);
assertTrue(compressed.compareTo(BigDecimal.ONE) < 0);
}
@Test
void testProbabilityTableCalculation() {
// Test that probability table is calculated correctly
String text = "AABBC";
Map<Character, ArithmeticCoding.Symbol> probTable = ArithmeticCoding.calculateProbabilities(text);
// Verify all characters are in the table
assertTrue(probTable.containsKey('A'));
assertTrue(probTable.containsKey('B'));
assertTrue(probTable.containsKey('C'));
// Verify probability ranges are valid
for (ArithmeticCoding.Symbol symbol : probTable.values()) {
assertTrue(symbol.low().compareTo(BigDecimal.ZERO) >= 0);
assertTrue(symbol.high().compareTo(BigDecimal.ONE) <= 0);
assertTrue(symbol.low().compareTo(symbol.high()) < 0);
}
}
@Test
void testDecompressionWithMismatchedProbabilityTable() {
// Test decompression with a probability table that doesn't match the original
String original = "ABCD";
BigDecimal compressed = ArithmeticCoding.compress(original);
// Create a different probability table (for "XYZ" instead of "ABCD")
Map<Character, ArithmeticCoding.Symbol> wrongProbTable = ArithmeticCoding.calculateProbabilities("XYZ");
// Decompression with wrong probability table should produce incorrect output
String decompressed = ArithmeticCoding.decompress(compressed, original.length(), wrongProbTable);
// The decompressed string will be different from original (likely all 'X', 'Y', or 'Z')
// This tests the edge case where the compressed value doesn't fall into expected ranges
assertNotNull(decompressed);
assertEquals(original.length(), decompressed.length());
}
@Test
void testDecompressionWithValueOutsideSymbolRanges() {
// Create a custom probability table
Map<Character, ArithmeticCoding.Symbol> probTable = new HashMap<>();
probTable.put('A', new ArithmeticCoding.Symbol(new BigDecimal("0.0"), new BigDecimal("0.5")));
probTable.put('B', new ArithmeticCoding.Symbol(new BigDecimal("0.5"), new BigDecimal("1.0")));
// Use a compressed value that should decode properly
BigDecimal compressed = new BigDecimal("0.25"); // Falls in 'A' range
String decompressed = ArithmeticCoding.decompress(compressed, 3, probTable);
// Verify decompression completes (even if result might not be meaningful)
assertNotNull(decompressed);
assertEquals(3, decompressed.length());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/RunLengthEncodingTest.java | src/test/java/com/thealgorithms/compression/RunLengthEncodingTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class RunLengthEncodingTest {
@Test
void testNullInputs() {
// Test that a null input to compress returns an empty string
assertEquals("", RunLengthEncoding.compress(null));
// Test that a null input to decompress returns an empty string
assertEquals("", RunLengthEncoding.decompress(null));
}
@Test
void testCompressionSimple() {
// Test a typical string with multiple runs
String input = "AAAABBBCCDAA";
String expected = "4A3B2C1D2A";
assertEquals(expected, RunLengthEncoding.compress(input));
}
@Test
void testCompressionWithNoRuns() {
// Test a string with no consecutive characters
String input = "ABCDE";
String expected = "1A1B1C1D1E";
assertEquals(expected, RunLengthEncoding.compress(input));
}
@Test
void testCompressionEdgeCases() {
// Test with an empty string
assertEquals("", RunLengthEncoding.compress(""));
// Test with a single character
assertEquals("1A", RunLengthEncoding.compress("A"));
// Test with a long run of a single character
assertEquals("10Z", RunLengthEncoding.compress("ZZZZZZZZZZ"));
}
@Test
void testDecompressionSimple() {
// Test decompression of a typical RLE string
String input = "4A3B2C1D2A";
String expected = "AAAABBBCCDAA";
assertEquals(expected, RunLengthEncoding.decompress(input));
}
@Test
void testDecompressionWithNoRuns() {
// Test decompression of a string with single characters
String input = "1A1B1C1D1E";
String expected = "ABCDE";
assertEquals(expected, RunLengthEncoding.decompress(input));
}
@Test
void testDecompressionWithMultiDigitCount() {
// Test decompression where a run count is greater than 9
String input = "12A1B3C";
String expected = "AAAAAAAAAAAABCCC";
assertEquals(expected, RunLengthEncoding.decompress(input));
}
@Test
void testDecompressionEdgeCases() {
// Test with an empty string
assertEquals("", RunLengthEncoding.decompress(""));
// Test with a single character run
assertEquals("A", RunLengthEncoding.decompress("1A"));
}
@Test
void testSymmetry() {
// Test that compressing and then decompressing returns the original string
String original1 = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB";
String compressed = RunLengthEncoding.compress(original1);
String decompressed = RunLengthEncoding.decompress(compressed);
assertEquals(original1, decompressed);
String original2 = "A";
assertEquals(original2, RunLengthEncoding.decompress(RunLengthEncoding.compress(original2)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/LZWTest.java | src/test/java/com/thealgorithms/compression/LZWTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
class LZWTest {
@Test
void testNullAndEmptyInputs() {
// Test that a null input to compress returns an empty list
assertTrue(LZW.compress(null).isEmpty());
// Test that a null input to decompress returns an empty string
assertEquals("", LZW.decompress(null));
// Test that an empty input to compress returns an empty list
assertTrue(LZW.compress("").isEmpty());
// Test that an empty input to decompress returns an empty string
assertEquals("", LZW.decompress(Collections.emptyList()));
}
@Test
void testCompressionAndDecompressionWithSimpleString() {
// Test a classic example string
String original = "TOBEORNOTTOBEORTOBEORNOT";
List<Integer> compressed = LZW.compress(original);
// Create the expected output list
List<Integer> expectedOutput = List.of(84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263);
// This assertion will fail if the output is not what we expect
assertEquals(expectedOutput, compressed);
// This assertion ensures the decompressed string is correct
String decompressed = LZW.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
void testCompressionWithRepeatedChars() {
// Test a string with long runs of the same character
String original = "AAAAABBBBBAAAAA";
List<Integer> compressed = LZW.compress(original);
String decompressed = LZW.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
void testCompressionWithUniqueChars() {
// Test a string with no repetitions
String original = "ABCDEFG";
List<Integer> compressed = LZW.compress(original);
String decompressed = LZW.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
void testSymmetry() {
// Test that compressing and then decompressing a complex string returns the
// original
String original = "THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG";
List<Integer> compressed = LZW.compress(original);
String decompressed = LZW.decompress(compressed);
assertEquals(original, decompressed);
// Another symmetry test with special characters and patterns
String original2 = "ababcbababa";
List<Integer> compressed2 = LZW.compress(original2);
String decompressed2 = LZW.decompress(compressed2);
assertEquals(original2, decompressed2);
}
@Test
void testInvalidCompressedData() {
// Test that decompressing with an invalid code throws IllegalArgumentException
// Create a list with a code that doesn't exist in the dictionary
List<Integer> invalidCompressed = new ArrayList<>();
invalidCompressed.add(65); // 'A' - valid
invalidCompressed.add(999); // Invalid code (not in dictionary)
// This should throw IllegalArgumentException with message "Bad compressed k: 999"
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> LZW.decompress(invalidCompressed));
assertTrue(exception.getMessage().contains("Bad compressed k: 999"));
}
@Test
void testDecompressionWithGapInDictionary() {
// Test with codes that skip dictionary entries
List<Integer> invalidCompressed = new ArrayList<>();
invalidCompressed.add(84); // 'T' - valid
invalidCompressed.add(500); // Way beyond current dictionary size
// This should throw IllegalArgumentException
assertThrows(IllegalArgumentException.class, () -> LZW.decompress(invalidCompressed));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/ShannonFanoTest.java | src/test/java/com/thealgorithms/compression/ShannonFanoTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Map;
import org.junit.jupiter.api.Test;
class ShannonFanoTest {
@Test
void testNullInput() {
// Test with a null string, should return an empty map
assertTrue(ShannonFano.generateCodes(null).isEmpty());
}
@Test
void testSimpleString() {
// A simple string to test basic code generation
String text = "AAABBC";
Map<Character, String> codes = ShannonFano.generateCodes(text);
assertEquals(3, codes.size());
assertEquals("0", codes.get('A'));
assertEquals("10", codes.get('B'));
assertEquals("11", codes.get('C'));
}
@Test
void testExampleFromStringIssue() {
// Example from the original issue proposal: A:15, B:7, C:6, D:6, E:5
// The code finds a more optimal split: {A,B} | {C,D,E} -> |22-17|=5
// instead of {A} | {B,C,D,E} -> |15-24|=9.
String text = "AAAAAAAAAAAAAAABBBBBBBCCCCCCDDDDDDEEEEE";
Map<Character, String> codes = ShannonFano.generateCodes(text);
assertEquals(5, codes.size());
assertEquals("00", codes.get('A'));
assertEquals("01", codes.get('B'));
assertEquals("10", codes.get('C'));
assertEquals("110", codes.get('D'));
assertEquals("111", codes.get('E'));
}
@Test
void testEdgeCases() {
// Test with an empty string
assertTrue(ShannonFano.generateCodes("").isEmpty());
// Test with a single character
Map<Character, String> singleCharCodes = ShannonFano.generateCodes("AAAAA");
assertEquals(1, singleCharCodes.size());
assertEquals("0", singleCharCodes.get('A')); // A single symbol gets code "0"
// Test with all unique characters
String uniqueCharsText = "ABCDEF";
Map<Character, String> uniqueCharCodes = ShannonFano.generateCodes(uniqueCharsText);
assertEquals(6, uniqueCharCodes.size());
// Check that codes are unique and have varying lengths as expected
assertEquals(6, uniqueCharCodes.values().stream().distinct().count());
}
@Test
void testStringWithTwoChars() {
String text = "ABABAB";
Map<Character, String> codes = ShannonFano.generateCodes(text);
assertEquals(2, codes.size());
assertTrue(codes.get('A').equals("0") && codes.get('B').equals("1") || codes.get('A').equals("1") && codes.get('B').equals("0"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/LZ77Test.java | src/test/java/com/thealgorithms/compression/LZ77Test.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class LZ77Test {
@Test
@DisplayName("Test compression and decompression of a simple repeating string")
void testSimpleRepeatingString() {
String original = "ababcbababaa";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 4);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test compression and decompression of a string with no repeats initially")
void testNoInitialRepeats() {
String original = "abcdefgh";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test compression and decompression of a longer example")
void testLongerExample() {
String original = "TOBEORNOTTOBEORTOBEORNOT";
List<LZ77.Token> compressed = LZ77.compress(original, 20, 10);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test empty string compression and decompression")
void testEmptyString() {
String original = "";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
assertTrue(compressed.isEmpty());
}
@Test
@DisplayName("Test null string compression")
void testNullStringCompress() {
List<LZ77.Token> compressed = LZ77.compress(null);
assertTrue(compressed.isEmpty());
}
@Test
@DisplayName("Test null list decompression")
void testNullListDecompress() {
String decompressed = LZ77.decompress(null);
assertEquals("", decompressed);
}
@Test
@DisplayName("Test invalid buffer sizes throw exception")
void testInvalidBufferSizes() {
assertThrows(IllegalArgumentException.class, () -> LZ77.compress("test", 0, 5));
assertThrows(IllegalArgumentException.class, () -> LZ77.compress("test", 5, 0));
assertThrows(IllegalArgumentException.class, () -> LZ77.compress("test", -1, 5));
assertThrows(IllegalArgumentException.class, () -> LZ77.compress("test", 5, -1));
}
@Test
@DisplayName("Test string with all same characters")
void testAllSameCharacters() {
String original = "AAAAAA";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 5);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve good compression for repeated characters
assertTrue(compressed.size() < original.length());
}
@Test
@DisplayName("Test string with all unique characters")
void testAllUniqueCharacters() {
String original = "abcdefghijklmnop";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 5);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
// No compression expected for unique characters
assertEquals(original.length(), compressed.size());
}
@Test
@DisplayName("Test single character string")
void testSingleCharacter() {
String original = "a";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
assertEquals(1, compressed.size());
}
@Test
@DisplayName("Test match that goes exactly to the end")
void testMatchToEnd() {
String original = "abcabc";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 10);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with very small window size")
void testSmallWindowSize() {
String original = "ababababab";
List<LZ77.Token> compressed = LZ77.compress(original, 2, 4);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with very small lookahead buffer")
void testSmallLookaheadBuffer() {
String original = "ababcbababaa";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 2);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test repeating pattern at the end")
void testRepeatingPatternAtEnd() {
String original = "xyzabcabcabcabc";
List<LZ77.Token> compressed = LZ77.compress(original, 15, 8);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test overlapping matches (run-length encoding case)")
void testOverlappingMatches() {
String original = "aaaaaa";
List<LZ77.Token> compressed = LZ77.compress(original, 10, 10);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test complex pattern with multiple repeats")
void testComplexPattern() {
String original = "abcabcabcxyzxyzxyz";
List<LZ77.Token> compressed = LZ77.compress(original, 20, 10);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with special characters")
void testSpecialCharacters() {
String original = "hello world! @#$%^&*()";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with numbers")
void testWithNumbers() {
String original = "1234567890123456";
List<LZ77.Token> compressed = LZ77.compress(original, 15, 8);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test long repeating sequence")
void testLongRepeatingSequence() {
String original = "abcdefgh".repeat(10);
List<LZ77.Token> compressed = LZ77.compress(original, 50, 20);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve significant compression
assertTrue(compressed.size() < original.length() / 2);
}
@Test
@DisplayName("Test compression effectiveness")
void testCompressionEffectiveness() {
String original = "ababababababab";
List<LZ77.Token> compressed = LZ77.compress(original, 20, 10);
// Verify that compression actually reduces the data size
// Each token represents potentially multiple characters
assertTrue(compressed.size() <= original.length());
// Verify decompression
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with mixed case letters")
void testMixedCase() {
String original = "AaBbCcAaBbCc";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test default parameters")
void testDefaultParameters() {
String original = "This is a test string with some repeated patterns. This is repeated.";
List<LZ77.Token> compressed = LZ77.compress(original);
String decompressed = LZ77.decompress(compressed);
assertEquals(original, decompressed);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java | src/test/java/com/thealgorithms/compression/BurrowsWheelerTransformTest.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class BurrowsWheelerTransformTest {
@Test
public void testTransformAndInverseBanana() {
String original = "banana$";
BurrowsWheelerTransform.BWTResult expectedTransform = new BurrowsWheelerTransform.BWTResult("annb$aa", 4);
// Test forward transform
BurrowsWheelerTransform.BWTResult actualTransform = BurrowsWheelerTransform.transform(original);
assertEquals(expectedTransform, actualTransform);
// Test inverse transform
String reconstructed = BurrowsWheelerTransform.inverseTransform(actualTransform.transformed, actualTransform.originalIndex);
assertEquals(original, reconstructed);
}
@Test
public void testTransformAndInverseAbracadabra() {
String original = "abracadabra$";
BurrowsWheelerTransform.BWTResult expectedTransform = new BurrowsWheelerTransform.BWTResult("ard$rcaaaabb", 3);
// Test forward transform
BurrowsWheelerTransform.BWTResult actualTransform = BurrowsWheelerTransform.transform(original);
assertEquals(expectedTransform, actualTransform);
// Test inverse transform
String reconstructed = BurrowsWheelerTransform.inverseTransform(actualTransform.transformed, actualTransform.originalIndex);
assertEquals(original, reconstructed);
}
@Test
public void testTransformAndInverseSixMixPixFix() {
String original = "SIX.MIX.PIX.FIX$";
BurrowsWheelerTransform.BWTResult expectedTransform = new BurrowsWheelerTransform.BWTResult("XXXX.FPSM..$IIII", 11);
// Test forward transform
BurrowsWheelerTransform.BWTResult actualTransform = BurrowsWheelerTransform.transform(original);
assertEquals(expectedTransform, actualTransform);
// Test inverse transform
String reconstructed = BurrowsWheelerTransform.inverseTransform(actualTransform.transformed, actualTransform.originalIndex);
assertEquals(original, reconstructed);
}
@Test
public void testEmptyString() {
String original = "";
BurrowsWheelerTransform.BWTResult expectedTransform = new BurrowsWheelerTransform.BWTResult("", -1);
BurrowsWheelerTransform.BWTResult actualTransform = BurrowsWheelerTransform.transform(original);
assertEquals(expectedTransform, actualTransform);
String reconstructed = BurrowsWheelerTransform.inverseTransform(actualTransform.transformed, actualTransform.originalIndex);
assertEquals(original, reconstructed);
}
@Test
public void testSingleCharacter() {
String original = "a";
BurrowsWheelerTransform.BWTResult expectedTransform = new BurrowsWheelerTransform.BWTResult("a", 0);
BurrowsWheelerTransform.BWTResult actualTransform = BurrowsWheelerTransform.transform(original);
assertEquals(expectedTransform, actualTransform);
String reconstructed = BurrowsWheelerTransform.inverseTransform(actualTransform.transformed, actualTransform.originalIndex);
assertEquals(original, reconstructed);
}
@Test
public void testTransformNull() {
assertEquals(new BurrowsWheelerTransform.BWTResult("", -1), BurrowsWheelerTransform.transform(null));
}
@Test
public void testInverseTransformNullString() {
// bwtString == null
assertEquals("", BurrowsWheelerTransform.inverseTransform(null, 1));
// bwtString.isEmpty()
assertEquals("", BurrowsWheelerTransform.inverseTransform("", 0));
}
@Test
public void testInverseTransformIndexOutOfBounds() {
String bwt = "annb$aa";
int n = bwt.length(); // n = 7
// originalIndex >= n
assertThrows(IllegalArgumentException.class, () -> BurrowsWheelerTransform.inverseTransform(bwt, n));
assertThrows(IllegalArgumentException.class, () -> BurrowsWheelerTransform.inverseTransform(bwt, 8));
// originalIndex < 0
assertThrows(IllegalArgumentException.class, () -> BurrowsWheelerTransform.inverseTransform(bwt, -2));
}
@Test
public void testBWTResultHelpers() {
BurrowsWheelerTransform.BWTResult res1 = new BurrowsWheelerTransform.BWTResult("annb$aa", 4);
BurrowsWheelerTransform.BWTResult res2 = new BurrowsWheelerTransform.BWTResult("annb$aa", 4);
BurrowsWheelerTransform.BWTResult res3 = new BurrowsWheelerTransform.BWTResult("other", 4);
BurrowsWheelerTransform.BWTResult res4 = new BurrowsWheelerTransform.BWTResult("annb$aa", 1);
assertEquals(res1, res1);
assertEquals(res1, res2);
assertNotEquals(res1, null); // obj == null
assertNotEquals(res1, new Object()); // different class
assertNotEquals(res1, res3); // different transformed
assertNotEquals(res1, res4); // different originalIndex
assertEquals(res1.hashCode(), res2.hashCode());
assertNotEquals(res1.hashCode(), res3.hashCode());
assertTrue(res1.toString().contains("annb$aa"));
assertTrue(res1.toString().contains("originalIndex=4"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/compression/LZ78Test.java | src/test/java/com/thealgorithms/compression/LZ78Test.java | package com.thealgorithms.compression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class LZ78Test {
@Test
@DisplayName("Test compression and decompression of a simple repeating string")
void testSimpleRepeatingString() {
String original = "ababcbababaa";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test compression and decompression example ABAABABAABAB")
void testStandardExample() {
String original = "ABAABABAABAB";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Verify the compression produces expected tokens
// Expected: (0,A)(0,B)(1,A)(2,B)(3,A)(4,B)
// Where dictionary builds as: 1:A, 2:B, 3:AA, 4:BA, 5:ABA, 6:BAB
assertEquals(6, compressed.size());
assertEquals(0, compressed.get(0).index());
assertEquals('A', compressed.get(0).nextChar());
assertEquals(0, compressed.get(1).index());
assertEquals('B', compressed.get(1).nextChar());
assertEquals(1, compressed.get(2).index());
assertEquals('A', compressed.get(2).nextChar());
}
@Test
@DisplayName("Test compression and decompression of a longer example")
void testLongerExample() {
String original = "TOBEORNOTTOBEORTOBEORNOT";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test empty string compression and decompression")
void testEmptyString() {
String original = "";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
assertTrue(compressed.isEmpty());
}
@Test
@DisplayName("Test null string compression")
void testNullStringCompress() {
List<LZ78.Token> compressed = LZ78.compress(null);
assertTrue(compressed.isEmpty());
}
@Test
@DisplayName("Test null list decompression")
void testNullListDecompress() {
String decompressed = LZ78.decompress(null);
assertEquals("", decompressed);
}
@Test
@DisplayName("Test string with all same characters")
void testAllSameCharacters() {
String original = "AAAAAA";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve good compression: (0,A)(1,A)(2,A)...
assertTrue(compressed.size() <= 4); // Builds: A, AA, AAA, etc.
}
@Test
@DisplayName("Test string with all unique characters")
void testAllUniqueCharacters() {
String original = "abcdefg";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// No compression for unique characters
assertEquals(original.length(), compressed.size());
// Each token should have index 0 (empty prefix)
for (LZ78.Token token : compressed) {
assertEquals(0, token.index());
}
}
@Test
@DisplayName("Test single character string")
void testSingleCharacter() {
String original = "a";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
assertEquals(1, compressed.size());
assertEquals(0, compressed.getFirst().index());
assertEquals('a', compressed.getFirst().nextChar());
}
@Test
@DisplayName("Test two character string")
void testTwoCharacters() {
String original = "ab";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
assertEquals(2, compressed.size());
}
@Test
@DisplayName("Test repeating pairs")
void testRepeatingPairs() {
String original = "ababab";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Should compress well: (0,a)(0,b)(1,b) or similar
assertTrue(compressed.size() < original.length());
}
@Test
@DisplayName("Test growing patterns")
void testGrowingPatterns() {
String original = "abcabcdabcde";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test dictionary building correctness")
void testDictionaryBuilding() {
String original = "aabaabaab";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Verify first few tokens
// Expected pattern: (0,a)(1,b)(2,a)(3,b) building dictionary 1:a, 2:ab, 3:aa, 4:aab
assertTrue(compressed.size() > 0);
assertEquals(0, compressed.getFirst().index()); // First char always has index 0
}
@Test
@DisplayName("Test with special characters")
void testSpecialCharacters() {
String original = "hello world! hello!";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test with numbers")
void testWithNumbers() {
String original = "1234512345";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve compression
assertTrue(compressed.size() < original.length());
}
@Test
@DisplayName("Test long repeating sequence")
void testLongRepeatingSequence() {
String original = "abcdefgh".repeat(5);
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// LZ78 should achieve some compression for repeating sequences
assertTrue(compressed.size() < original.length(), "Compressed size should be less than original length");
}
@Test
@DisplayName("Test alternating characters")
void testAlternatingCharacters() {
String original = "ababababab";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test compression effectiveness")
void testCompressionEffectiveness() {
String original = "the quick brown fox jumps over the lazy dog the quick brown fox";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve some compression due to repeated phrases
assertTrue(compressed.size() < original.length());
}
@Test
@DisplayName("Test with mixed case letters")
void testMixedCase() {
String original = "AaBbCcAaBbCc";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test palindrome string")
void testPalindrome() {
String original = "abccba";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test highly compressible pattern")
void testHighlyCompressible() {
String original = "aaaaaaaaaa";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
// Should achieve excellent compression ratio
assertTrue(compressed.size() <= 4);
}
@Test
@DisplayName("Test empty list decompression")
void testEmptyListDecompress() {
List<LZ78.Token> compressed = List.of();
String decompressed = LZ78.decompress(compressed);
assertEquals("", decompressed);
}
@Test
@DisplayName("Test binary-like pattern")
void testBinaryPattern() {
String original = "0101010101";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test nested patterns")
void testNestedPatterns() {
String original = "abcabcdefabcdefghi";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test whitespace handling")
void testWhitespace() {
String original = "a b c a b c";
List<LZ78.Token> compressed = LZ78.compress(original);
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
@Test
@DisplayName("Test token structure correctness")
void testTokenStructure() {
String original = "abc";
List<LZ78.Token> compressed = LZ78.compress(original);
// All tokens should have valid indices (>= 0)
for (LZ78.Token token : compressed) {
assertTrue(token.index() >= 0);
assertNotNull(token.nextChar());
}
String decompressed = LZ78.decompress(compressed);
assertEquals(original, decompressed);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionTest.java | src/test/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionTest.java | package com.thealgorithms.datastructures.disjointsetunion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
public class DisjointSetUnionTest {
@Test
public void testMakeSet() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node = dsu.makeSet(1);
assertNotNull(node);
assertEquals(node, node.parent);
}
@Test
public void testUnionFindSet() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
Node<Integer> node4 = dsu.makeSet(4);
dsu.unionSets(node1, node2);
dsu.unionSets(node3, node2);
dsu.unionSets(node3, node4);
dsu.unionSets(node1, node3);
Node<Integer> root1 = dsu.findSet(node1);
Node<Integer> root2 = dsu.findSet(node2);
Node<Integer> root3 = dsu.findSet(node3);
Node<Integer> root4 = dsu.findSet(node4);
assertEquals(node1, node1.parent);
assertEquals(node1, node2.parent);
assertEquals(node1, node3.parent);
assertEquals(node1, node4.parent);
assertEquals(node1, root1);
assertEquals(node1, root2);
assertEquals(node1, root3);
assertEquals(node1, root4);
assertEquals(1, node1.rank);
assertEquals(0, node2.rank);
assertEquals(0, node3.rank);
assertEquals(0, node4.rank);
}
@Test
public void testFindSetOnSingleNode() {
DisjointSetUnion<String> dsu = new DisjointSetUnion<>();
Node<String> node = dsu.makeSet("A");
assertEquals(node, dsu.findSet(node));
}
@Test
public void testUnionAlreadyConnectedNodes() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
// Union nodes that are already connected
dsu.unionSets(node1, node3);
// All should have the same root
Node<Integer> root = dsu.findSet(node1);
assertEquals(root, dsu.findSet(node2));
assertEquals(root, dsu.findSet(node3));
}
@Test
public void testRankIncrease() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
Node<Integer> node4 = dsu.makeSet(4);
dsu.unionSets(node1, node2); // rank of node1 should increase
dsu.unionSets(node3, node4); // rank of node3 should increase
dsu.unionSets(node1, node3); // union two trees of same rank -> rank increases
assertEquals(2, dsu.findSet(node1).rank);
}
@Test
public void testMultipleMakeSets() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
assertNotEquals(node1, node2);
assertNotEquals(node2, node3);
assertNotEquals(node1, node3);
assertEquals(node1, node1.parent);
assertEquals(node2, node2.parent);
assertEquals(node3, node3.parent);
}
@Test
public void testPathCompression() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
// After findSet, path compression should update parent to root directly
Node<Integer> root = dsu.findSet(node3);
assertEquals(root, node1);
assertEquals(node1, node3.parent);
}
@Test
public void testUnionByRankSmallerToLarger() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
// Create tree with node1 as root and rank 1
dsu.unionSets(node1, node2);
assertEquals(1, node1.rank);
assertEquals(0, node2.rank);
// Union single node (rank 0) with tree (rank 1)
// Smaller rank tree should attach to larger rank tree
dsu.unionSets(node3, node1);
assertEquals(node1, dsu.findSet(node3));
assertEquals(1, node1.rank); // Rank should not increase
}
@Test
public void testUnionByRankEqualRanks() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
Node<Integer> node4 = dsu.makeSet(4);
// Create two trees of equal rank (1)
dsu.unionSets(node1, node2);
dsu.unionSets(node3, node4);
assertEquals(1, node1.rank);
assertEquals(1, node3.rank);
// Union two trees of equal rank
dsu.unionSets(node1, node3);
Node<Integer> root = dsu.findSet(node1);
assertEquals(2, root.rank); // Rank should increase by 1
}
@Test
public void testLargeChainPathCompression() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
Node<Integer> node4 = dsu.makeSet(4);
Node<Integer> node5 = dsu.makeSet(5);
// Create a long chain: 1 -> 2 -> 3 -> 4 -> 5
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
dsu.unionSets(node3, node4);
dsu.unionSets(node4, node5);
// Find from the deepest node
Node<Integer> root = dsu.findSet(node5);
// Path compression should make all nodes point directly to root
assertEquals(root, node5.parent);
assertEquals(root, node4.parent);
assertEquals(root, node3.parent);
assertEquals(root, node2.parent);
assertEquals(root, node1.parent);
}
@Test
public void testMultipleDisjointSets() {
DisjointSetUnion<Integer> dsu = new DisjointSetUnion<>();
Node<Integer> node1 = dsu.makeSet(1);
Node<Integer> node2 = dsu.makeSet(2);
Node<Integer> node3 = dsu.makeSet(3);
Node<Integer> node4 = dsu.makeSet(4);
Node<Integer> node5 = dsu.makeSet(5);
Node<Integer> node6 = dsu.makeSet(6);
// Create two separate components
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
dsu.unionSets(node4, node5);
dsu.unionSets(node5, node6);
// Verify they are separate
assertEquals(dsu.findSet(node1), dsu.findSet(node2));
assertEquals(dsu.findSet(node2), dsu.findSet(node3));
assertEquals(dsu.findSet(node4), dsu.findSet(node5));
assertEquals(dsu.findSet(node5), dsu.findSet(node6));
assertNotEquals(dsu.findSet(node1), dsu.findSet(node4));
assertNotEquals(dsu.findSet(node3), dsu.findSet(node6));
}
@Test
public void testEmptyValues() {
DisjointSetUnion<String> dsu = new DisjointSetUnion<>();
Node<String> emptyNode = dsu.makeSet("");
Node<String> nullNode = dsu.makeSet(null);
assertEquals(emptyNode, dsu.findSet(emptyNode));
assertEquals(nullNode, dsu.findSet(nullNode));
dsu.unionSets(emptyNode, nullNode);
assertEquals(dsu.findSet(emptyNode), dsu.findSet(nullNode));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySizeTest.java | src/test/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySizeTest.java | package com.thealgorithms.datastructures.disjointsetunion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
public class DisjointSetUnionBySizeTest {
@Test
public void testMakeSet() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node = dsu.makeSet(1);
assertNotNull(node);
assertEquals(node, node.parent);
assertEquals(1, node.size);
}
@Test
public void testUnionFindSet() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node1 = dsu.makeSet(1);
DisjointSetUnionBySize.Node<Integer> node2 = dsu.makeSet(2);
DisjointSetUnionBySize.Node<Integer> node3 = dsu.makeSet(3);
DisjointSetUnionBySize.Node<Integer> node4 = dsu.makeSet(4);
dsu.unionSets(node1, node2);
dsu.unionSets(node3, node2);
dsu.unionSets(node3, node4);
dsu.unionSets(node1, node3);
DisjointSetUnionBySize.Node<Integer> root1 = dsu.findSet(node1);
DisjointSetUnionBySize.Node<Integer> root2 = dsu.findSet(node2);
DisjointSetUnionBySize.Node<Integer> root3 = dsu.findSet(node3);
DisjointSetUnionBySize.Node<Integer> root4 = dsu.findSet(node4);
assertEquals(root1, root2);
assertEquals(root1, root3);
assertEquals(root1, root4);
assertEquals(4, root1.size);
}
@Test
public void testFindSetOnSingleNode() {
DisjointSetUnionBySize<String> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<String> node = dsu.makeSet("A");
assertEquals(node, dsu.findSet(node));
}
@Test
public void testUnionAlreadyConnectedNodes() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node1 = dsu.makeSet(1);
DisjointSetUnionBySize.Node<Integer> node2 = dsu.makeSet(2);
DisjointSetUnionBySize.Node<Integer> node3 = dsu.makeSet(3);
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
// Union nodes that are already connected
dsu.unionSets(node1, node3);
// All should have the same root
DisjointSetUnionBySize.Node<Integer> root = dsu.findSet(node1);
assertEquals(root, dsu.findSet(node2));
assertEquals(root, dsu.findSet(node3));
assertEquals(3, root.size);
}
@Test
public void testMultipleMakeSets() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node1 = dsu.makeSet(1);
DisjointSetUnionBySize.Node<Integer> node2 = dsu.makeSet(2);
DisjointSetUnionBySize.Node<Integer> node3 = dsu.makeSet(3);
assertNotEquals(node1, node2);
assertNotEquals(node2, node3);
assertNotEquals(node1, node3);
assertEquals(node1, node1.parent);
assertEquals(node2, node2.parent);
assertEquals(node3, node3.parent);
assertEquals(1, node1.size);
assertEquals(1, node2.size);
assertEquals(1, node3.size);
}
@Test
public void testPathCompression() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node1 = dsu.makeSet(1);
DisjointSetUnionBySize.Node<Integer> node2 = dsu.makeSet(2);
DisjointSetUnionBySize.Node<Integer> node3 = dsu.makeSet(3);
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
// After findSet, path compression should update parent to root directly
DisjointSetUnionBySize.Node<Integer> root = dsu.findSet(node3);
assertEquals(root, node1);
assertEquals(node1, node3.parent);
assertEquals(3, root.size);
}
@Test
public void testMultipleDisjointSets() {
DisjointSetUnionBySize<Integer> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<Integer> node1 = dsu.makeSet(1);
DisjointSetUnionBySize.Node<Integer> node2 = dsu.makeSet(2);
DisjointSetUnionBySize.Node<Integer> node3 = dsu.makeSet(3);
DisjointSetUnionBySize.Node<Integer> node4 = dsu.makeSet(4);
DisjointSetUnionBySize.Node<Integer> node5 = dsu.makeSet(5);
DisjointSetUnionBySize.Node<Integer> node6 = dsu.makeSet(6);
// Create two separate components
dsu.unionSets(node1, node2);
dsu.unionSets(node2, node3);
dsu.unionSets(node4, node5);
dsu.unionSets(node5, node6);
// Verify they are separate
assertEquals(dsu.findSet(node1), dsu.findSet(node2));
assertEquals(dsu.findSet(node2), dsu.findSet(node3));
assertEquals(dsu.findSet(node4), dsu.findSet(node5));
assertEquals(dsu.findSet(node5), dsu.findSet(node6));
assertNotEquals(dsu.findSet(node1), dsu.findSet(node4));
assertNotEquals(dsu.findSet(node3), dsu.findSet(node6));
}
@Test
public void testEmptyValues() {
DisjointSetUnionBySize<String> dsu = new DisjointSetUnionBySize<>();
DisjointSetUnionBySize.Node<String> emptyNode = dsu.makeSet("");
DisjointSetUnionBySize.Node<String> nullNode = dsu.makeSet(null);
assertEquals(emptyNode, dsu.findSet(emptyNode));
assertEquals(nullNode, dsu.findSet(nullNode));
dsu.unionSets(emptyNode, nullNode);
assertEquals(dsu.findSet(emptyNode), dsu.findSet(nullNode));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java | src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CreateAndDetectLoopTest {
private CreateAndDetectLoop.Node head;
@BeforeEach
void setUp() {
// Set up a linked list: 1 -> 2 -> 3 -> 4 -> 5 -> 6
head = new CreateAndDetectLoop.Node(1);
CreateAndDetectLoop.Node second = new CreateAndDetectLoop.Node(2);
CreateAndDetectLoop.Node third = new CreateAndDetectLoop.Node(3);
CreateAndDetectLoop.Node fourth = new CreateAndDetectLoop.Node(4);
CreateAndDetectLoop.Node fifth = new CreateAndDetectLoop.Node(5);
CreateAndDetectLoop.Node sixth = new CreateAndDetectLoop.Node(6);
head.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
fifth.next = sixth;
}
@Test
void testDetectLoopNoLoop() {
// Test when no loop exists
assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop.");
}
@Test
void testCreateAndDetectLoopLoopExists() {
// Create a loop between position 2 (node with value 2) and position 5 (node with value 5)
CreateAndDetectLoop.createLoop(head, 2, 5);
// Now test if the loop is detected
assertTrue(CreateAndDetectLoop.detectLoop(head), "A loop should be detected.");
}
@Test
void testCreateLoopInvalidPosition() {
// Create loop with invalid positions (0)
CreateAndDetectLoop.createLoop(head, 0, 0);
// Ensure no loop was created
assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop with invalid positions.");
}
@Test
void testCreateLoopSelfLoop() {
// Create a self-loop at position 3 (node with value 3)
CreateAndDetectLoop.createLoop(head, 3, 3);
// Test if the self-loop is detected
assertTrue(CreateAndDetectLoop.detectLoop(head), "A self-loop should be detected.");
}
@Test
void testCreateLoopNoChangeForNonExistentPositions() {
// Create a loop with non-existent positions
CreateAndDetectLoop.createLoop(head, 10, 20);
// Ensure no loop was created
assertFalse(CreateAndDetectLoop.detectLoop(head), "No loop should be created if positions are out of bounds.");
}
@Test
void testMultipleNodesWithNoLoop() {
// Multiple nodes without creating any loop
assertFalse(CreateAndDetectLoop.detectLoop(head), "No loop should be detected for a standard linear list.");
}
@Test
void testHeadToTailLoop() {
// Create a loop from the tail back to the head
CreateAndDetectLoop.createLoop(head, 1, 6);
// Detect the head-to-tail loop
assertTrue(CreateAndDetectLoop.detectLoop(head), "A head-to-tail loop should be detected.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java | src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
/**
* Test cases for Reverse K Group LinkedList
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class ReverseKGroupTest {
@Test
public void testReverseKGroupWithEmptyList() {
ReverseKGroup reverser = new ReverseKGroup();
assertNull(reverser.reverseKGroup(null, 3));
}
@Test
public void testReverseKGroupWithSingleNodeList() {
ReverseKGroup reverser = new ReverseKGroup();
SinglyLinkedListNode singleNode = new SinglyLinkedListNode(5);
SinglyLinkedListNode result = reverser.reverseKGroup(singleNode, 2);
assertEquals(5, result.value);
assertNull(result.next);
}
@Test
public void testReverseKGroupWithKEqualTo2() {
ReverseKGroup reverser = new ReverseKGroup();
// Create a list with multiple elements (1 -> 2 -> 3 -> 4 -> 5)
SinglyLinkedListNode head;
head = new SinglyLinkedListNode(1);
head.next = new SinglyLinkedListNode(2);
head.next.next = new SinglyLinkedListNode(3);
head.next.next.next = new SinglyLinkedListNode(4);
head.next.next.next.next = new SinglyLinkedListNode(5);
// Test reverse with k=2
SinglyLinkedListNode result1 = reverser.reverseKGroup(head, 2);
assertEquals(2, result1.value);
assertEquals(1, result1.next.value);
assertEquals(4, result1.next.next.value);
assertEquals(3, result1.next.next.next.value);
assertEquals(5, result1.next.next.next.next.value);
assertNull(result1.next.next.next.next.next);
}
@Test
public void testReverseKGroupWithKEqualTo3() {
ReverseKGroup reverser = new ReverseKGroup();
// Create a list with multiple elements (1 -> 2 -> 3 -> 4 -> 5)
SinglyLinkedListNode head;
head = new SinglyLinkedListNode(1);
head.next = new SinglyLinkedListNode(2);
head.next.next = new SinglyLinkedListNode(3);
head.next.next.next = new SinglyLinkedListNode(4);
head.next.next.next.next = new SinglyLinkedListNode(5);
// Test reverse with k=3
SinglyLinkedListNode result = reverser.reverseKGroup(head, 3);
assertEquals(3, result.value);
assertEquals(2, result.next.value);
assertEquals(1, result.next.next.value);
assertEquals(4, result.next.next.next.value);
assertEquals(5, result.next.next.next.next.value);
assertNull(result.next.next.next.next.next);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.thealgorithms.datastructures.lists.MergeKSortedLinkedList.Node;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class MergeKSortedLinkedListTest {
@Test
void testMergeKLists() {
Node list1 = new Node(1, new Node(4, new Node(5)));
Node list2 = new Node(1, new Node(3, new Node(4)));
Node list3 = new Node(2, new Node(6));
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 1, 2, 3, 4, 4, 5, 6};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Merged list values do not match the expected sorted order.");
}
@Test
void testMergeEmptyLists() {
Node[] lists = {null, null, null};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
assertNull(mergedHead, "Merged list should be null when all input lists are empty.");
}
@Test
void testMergeSingleList() {
Node list1 = new Node(1, new Node(3, new Node(5)));
Node[] lists = {list1};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 3, 5};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Merged list should match the single input list when only one list is provided.");
}
@Test
void testMergeListsOfDifferentLengths() {
Node list1 = new Node(1, new Node(3, new Node(5)));
Node list2 = new Node(2, new Node(4));
Node list3 = new Node(6);
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 2, 3, 4, 5, 6};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Merged list values do not match expected sorted order for lists of different lengths.");
}
@Test
void testMergeSingleElementLists() {
Node list1 = new Node(1);
Node list2 = new Node(3);
Node list3 = new Node(2);
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 2, 3};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Merged list values do not match expected sorted order for single-element lists.");
}
/**
* Helper method to extract values from the linked list into an array for assertion.
*/
private int[] getListValues(Node head) {
int[] values = new int[100]; // assuming max length for simplicity
int i = 0;
Node curr = head;
while (curr != null) {
values[i++] = curr.data;
curr = curr.next;
}
return Arrays.copyOf(values, i); // return only filled part
}
@Test
void testMergeWithNullListsInArray() {
Node list1 = new Node(1, new Node(3));
Node list2 = null;
Node list3 = new Node(2, new Node(4));
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 2, 3, 4};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Should handle null lists mixed with valid lists");
}
@Test
void testMergeWithDuplicateValues() {
Node list1 = new Node(1, new Node(1, new Node(3)));
Node list2 = new Node(1, new Node(2, new Node(3)));
Node list3 = new Node(3, new Node(3));
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 1, 1, 2, 3, 3, 3, 3};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Should handle duplicate values correctly");
}
@Test
void testMergeWithZeroLength() {
Node[] lists = {};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, 0);
assertNull(mergedHead, "Should return null for zero-length array");
}
@Test
void testMergeWithNegativeNumbers() {
Node list1 = new Node(-5, new Node(-1, new Node(3)));
Node list2 = new Node(-3, new Node(0, new Node(2)));
Node[] lists = {list1, list2};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {-5, -3, -1, 0, 2, 3};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Should handle negative numbers correctly");
}
@Test
void testMergeIdenticalLists() {
Node list1 = new Node(1, new Node(2, new Node(3)));
Node list2 = new Node(1, new Node(2, new Node(3)));
Node list3 = new Node(1, new Node(2, new Node(3)));
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 1, 1, 2, 2, 2, 3, 3, 3};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Should merge identical lists correctly");
}
@Test
void testMergeAlreadySortedSequence() {
Node list1 = new Node(1, new Node(2));
Node list2 = new Node(3, new Node(4));
Node list3 = new Node(5, new Node(6));
Node[] lists = {list1, list2, list3};
MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
Node mergedHead = merger.mergeKList(lists, lists.length);
int[] expectedValues = {1, 2, 3, 4, 5, 6};
int[] actualValues = getListValues(mergedHead);
assertArrayEquals(expectedValues, actualValues, "Should handle already sorted sequence");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java | src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class SkipListTest {
private SkipList<String> skipList;
@BeforeEach
void setUp() {
skipList = new SkipList<>();
}
@Test
@DisplayName("Add element and verify size and retrieval")
void testAdd() {
assertEquals(0, skipList.size());
skipList.add("value");
assertEquals(1, skipList.size());
assertEquals("value", skipList.get(0));
}
@Test
@DisplayName("Get retrieves correct element by index")
void testGet() {
skipList.add("value");
assertEquals("value", skipList.get(0));
}
@Test
@DisplayName("Contains returns true if element exists")
void testContains() {
skipList = createSkipList();
assertTrue(skipList.contains("b"));
assertTrue(skipList.contains("a"));
assertFalse(skipList.contains("z")); // negative test
}
@Test
@DisplayName("Remove element from head and check size and order")
void testRemoveFromHead() {
skipList = createSkipList();
String first = skipList.get(0);
int initialSize = skipList.size();
skipList.remove(first);
assertEquals(initialSize - 1, skipList.size());
assertFalse(skipList.contains(first));
}
@Test
@DisplayName("Remove element from tail and check size and order")
void testRemoveFromTail() {
skipList = createSkipList();
String last = skipList.get(skipList.size() - 1);
int initialSize = skipList.size();
skipList.remove(last);
assertEquals(initialSize - 1, skipList.size());
assertFalse(skipList.contains(last));
}
@Test
@DisplayName("Elements should be sorted at base level")
void testSortedOrderOnBaseLevel() {
String[] values = {"d", "b", "a", "c"};
Arrays.stream(values).forEach(skipList::add);
String[] actualOrder = IntStream.range(0, values.length).mapToObj(skipList::get).toArray(String[] ::new);
org.junit.jupiter.api.Assertions.assertArrayEquals(new String[] {"a", "b", "c", "d"}, actualOrder);
}
@Test
@DisplayName("Duplicate elements can be added and count correctly")
void testAddDuplicates() {
skipList.add("x");
skipList.add("x");
assertEquals(2, skipList.size());
assertEquals("x", skipList.get(0));
assertEquals("x", skipList.get(1));
}
@Test
@DisplayName("Add multiple and remove all")
void testClearViaRemovals() {
String[] values = {"a", "b", "c"};
Arrays.stream(values).forEach(skipList::add);
for (String v : values) {
skipList.remove(v);
}
assertEquals(0, skipList.size());
}
private SkipList<String> createSkipList() {
SkipList<String> s = new SkipList<>();
String[] values = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"};
Arrays.stream(values).forEach(s::add);
return s;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the FlattenMultilevelLinkedList class.
* This class tests the flattening logic with various list structures,
* including null lists, simple lists, and complex multilevel lists.
*/
final class FlattenMultilevelLinkedListTest {
// A helper function to convert a flattened list (connected by child pointers)
// into a standard Java List for easy comparison.
private List<Integer> toList(FlattenMultilevelLinkedList.Node head) {
List<Integer> list = new ArrayList<>();
FlattenMultilevelLinkedList.Node current = head;
while (current != null) {
list.add(current.data);
current = current.child;
}
return list;
}
@Test
@DisplayName("Test with a null list")
void testFlattenNullList() {
assertNull(FlattenMultilevelLinkedList.flatten(null));
}
@Test
@DisplayName("Test with a simple, single-level list")
void testFlattenSingleLevelList() {
// Create a simple list: 1 -> 2 -> 3
FlattenMultilevelLinkedList.Node head = new FlattenMultilevelLinkedList.Node(1);
head.next = new FlattenMultilevelLinkedList.Node(2);
head.next.next = new FlattenMultilevelLinkedList.Node(3);
// Flatten the list
FlattenMultilevelLinkedList.Node flattenedHead = FlattenMultilevelLinkedList.flatten(head);
// Expected output: 1 -> 2 -> 3 (vertically)
List<Integer> expected = List.of(1, 2, 3);
assertEquals(expected, toList(flattenedHead));
}
@Test
@DisplayName("Test with a complex multilevel list")
void testFlattenComplexMultilevelList() {
// Create the multilevel structure from the problem description
// 5 -> 10 -> 19 -> 28
// | | | |
// 7 20 22 35
// | | |
// 8 50 40
// | |
// 30 45
FlattenMultilevelLinkedList.Node head = new FlattenMultilevelLinkedList.Node(5);
head.child = new FlattenMultilevelLinkedList.Node(7);
head.child.child = new FlattenMultilevelLinkedList.Node(8);
head.child.child.child = new FlattenMultilevelLinkedList.Node(30);
head.next = new FlattenMultilevelLinkedList.Node(10);
head.next.child = new FlattenMultilevelLinkedList.Node(20);
head.next.next = new FlattenMultilevelLinkedList.Node(19);
head.next.next.child = new FlattenMultilevelLinkedList.Node(22);
head.next.next.child.child = new FlattenMultilevelLinkedList.Node(50);
head.next.next.next = new FlattenMultilevelLinkedList.Node(28);
head.next.next.next.child = new FlattenMultilevelLinkedList.Node(35);
head.next.next.next.child.child = new FlattenMultilevelLinkedList.Node(40);
head.next.next.next.child.child.child = new FlattenMultilevelLinkedList.Node(45);
// Flatten the list
FlattenMultilevelLinkedList.Node flattenedHead = FlattenMultilevelLinkedList.flatten(head);
// Expected sorted output
List<Integer> expected = List.of(5, 7, 8, 10, 19, 20, 22, 28, 30, 35, 40, 45, 50);
assertEquals(expected, toList(flattenedHead));
}
@Test
@DisplayName("Test with some empty child lists")
void testFlattenWithEmptyChildLists() {
// Create a list: 5 -> 10 -> 12
// | |
// 7 11
// |
// 9
FlattenMultilevelLinkedList.Node head = new FlattenMultilevelLinkedList.Node(5);
head.child = new FlattenMultilevelLinkedList.Node(7);
head.child.child = new FlattenMultilevelLinkedList.Node(9);
head.next = new FlattenMultilevelLinkedList.Node(10); // No child list
head.next.child = null;
head.next.next = new FlattenMultilevelLinkedList.Node(12);
head.next.next.child = new FlattenMultilevelLinkedList.Node(16);
// Flatten the list
FlattenMultilevelLinkedList.Node flattenedHead = FlattenMultilevelLinkedList.flatten(head);
// Expected sorted output
List<Integer> expected = List.of(5, 7, 9, 10, 12, 16);
assertEquals(expected, toList(flattenedHead));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SinglyLinkedListTest {
/**
* Initialize a list with natural order values with pre-defined length
* @param length
* @return linked list with pre-defined number of nodes
*/
private SinglyLinkedList createSampleList(int length) {
List<SinglyLinkedListNode> nodeList = new ArrayList<>();
for (int i = 1; i <= length; i++) {
SinglyLinkedListNode node = new SinglyLinkedListNode(i);
nodeList.add(node);
}
for (int i = 0; i < length - 1; i++) {
nodeList.get(i).next = nodeList.get(i + 1);
}
return new SinglyLinkedList(nodeList.get(0), length);
}
@Test
void detectLoop() {
// List has cycle
SinglyLinkedListNode firstNode = new SinglyLinkedListNode(1);
SinglyLinkedListNode secondNode = new SinglyLinkedListNode(2);
SinglyLinkedListNode thirdNode = new SinglyLinkedListNode(3);
SinglyLinkedListNode fourthNode = new SinglyLinkedListNode(4);
firstNode.next = secondNode;
secondNode.next = thirdNode;
thirdNode.next = fourthNode;
fourthNode.next = firstNode;
SinglyLinkedList listHasLoop = new SinglyLinkedList(firstNode, 4);
assertTrue(listHasLoop.detectLoop());
SinglyLinkedList listHasNoLoop = createSampleList(5);
assertFalse(listHasNoLoop.detectLoop());
}
@Test
void middle() {
int oddNumberOfNode = 7;
SinglyLinkedList list = createSampleList(oddNumberOfNode);
assertEquals(oddNumberOfNode / 2 + 1, list.middle().value);
int evenNumberOfNode = 8;
list = createSampleList(evenNumberOfNode);
assertEquals(evenNumberOfNode / 2, list.middle().value);
// return null if empty
list = new SinglyLinkedList();
assertNull(list.middle());
// return head if there is only one node
list = createSampleList(1);
assertEquals(list.getHead(), list.middle());
}
@Test
void swap() {
SinglyLinkedList list = createSampleList(5);
assertEquals(1, list.getHead().value);
assertEquals(5, list.getNth(4));
list.swapNodes(1, 5);
assertEquals(5, list.getHead().value);
assertEquals(1, list.getNth(4));
}
@Test
void clear() {
SinglyLinkedList list = createSampleList(5);
assertEquals(5, list.size());
list.clear();
assertEquals(0, list.size());
assertTrue(list.isEmpty());
}
@Test
void search() {
SinglyLinkedList list = createSampleList(10);
assertTrue(list.search(5));
assertFalse(list.search(20));
}
@Test
void deleteNth() {
SinglyLinkedList list = createSampleList(10);
assertTrue(list.search(7));
list.deleteNth(6); // Index 6 has value 7
assertFalse(list.search(7));
}
// Test to check whether the method reverseList() works fine
@Test
void reverseList() {
// Creating a new LinkedList of size:4
// The linkedlist will be 1->2->3->4->null
SinglyLinkedList list = createSampleList(4);
// Reversing the LinkedList using reverseList() method and storing the head of the reversed
// linkedlist in a head node The reversed linkedlist will be 4->3->2->1->null
SinglyLinkedListNode head = list.reverseListIter(list.getHead());
// Recording the Nodes after reversing the LinkedList
SinglyLinkedListNode firstNode = head; // 4
SinglyLinkedListNode secondNode = firstNode.next; // 3
SinglyLinkedListNode thirdNode = secondNode.next; // 2
SinglyLinkedListNode fourthNode = thirdNode.next; // 1
// Checking whether the LinkedList is reversed or not by comparing the original list and
// reversed list nodes
assertEquals(1, fourthNode.value);
assertEquals(2, thirdNode.value);
assertEquals(3, secondNode.value);
assertEquals(4, firstNode.value);
}
// Test to check whether implemented reverseList() method handles NullPointer Exception for
// TestCase where head==null
@Test
void reverseListNullPointer() {
// Creating a linkedlist with first node assigned to null
SinglyLinkedList list = new SinglyLinkedList();
SinglyLinkedListNode first = list.getHead();
// Reversing the linkedlist
SinglyLinkedListNode head = list.reverseListIter(first);
// checking whether the method works fine if the input is null
assertEquals(head, first);
}
// Testing reverseList() method for a linkedlist of size: 20
@Test
void reverseListTest() {
// Creating a new linkedlist
SinglyLinkedList list = createSampleList(20);
// Reversing the LinkedList using reverseList() method and storing the head of the reversed
// linkedlist in a head node
SinglyLinkedListNode head = list.reverseListIter(list.getHead());
// Storing the head in a temp variable, so that we cannot loose the track of head
SinglyLinkedListNode temp = head;
int i = 20; // This is for the comparison of values of nodes of the reversed linkedlist
// Checking whether the reverseList() method performed its task
while (temp != null && i > 0) {
assertEquals(i, temp.value);
temp = temp.next;
i--;
}
}
// This is Recursive Reverse List Test
// Test to check whether the method reverseListRec() works fine
void recursiveReverseList() {
// Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
SinglyLinkedList list = createSampleList(5);
// Reversing the linked list using reverseList() method
SinglyLinkedListNode head = list.reverseListRec(list.getHead());
// Check if the reversed list is: 5 -> 4 -> 3 -> 2 -> 1
assertEquals(5, head.value);
assertEquals(4, head.next.value);
assertEquals(3, head.next.next.value);
assertEquals(2, head.next.next.next.value);
assertEquals(1, head.next.next.next.next.value);
}
@Test
void recursiveReverseListNullPointer() {
// Create an empty linked list
SinglyLinkedList list = new SinglyLinkedList();
SinglyLinkedListNode first = list.getHead();
// Reversing the empty linked list
SinglyLinkedListNode head = list.reverseListRec(first);
// Check if the head remains the same (null)
assertNull(head);
}
@Test
void recursiveReverseListTest() {
// Create a linked list with values from 1 to 20
SinglyLinkedList list = createSampleList(20);
// Reversing the linked list using reverseList() method
SinglyLinkedListNode head = list.reverseListRec(list.getHead());
// Check if the reversed list has the correct values
int i = 20;
SinglyLinkedListNode temp = head;
while (temp != null && i > 0) {
assertEquals(i, temp.value);
temp = temp.next;
i--;
}
}
@Test
void readWithEnhancedForLoopTest() {
final var expected = new ArrayList<Integer>(Arrays.asList(10, 20, 30));
SinglyLinkedList list = new SinglyLinkedList();
for (final var x : expected) {
list.insert(x);
}
var readElements = new ArrayList<Integer>();
for (final var x : list) {
readElements.add(x);
}
assertEquals(readElements, expected);
}
@Test
void toStringTest() {
SinglyLinkedList list = new SinglyLinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
assertEquals("1->2->3", list.toString());
}
@Test
void toStringForEmptyListTest() {
SinglyLinkedList list = new SinglyLinkedList();
assertEquals("", list.toString());
}
@Test
void countTest() {
SinglyLinkedList list = new SinglyLinkedList();
list.insert(10);
list.insert(20);
assertEquals(2, list.count());
}
@Test
void countForEmptyListTest() {
SinglyLinkedList list = new SinglyLinkedList();
assertEquals(0, list.count());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CircularDoublyLinkedListTest {
private CircularDoublyLinkedList<Integer> list;
@BeforeEach
public void setUp() {
list = new CircularDoublyLinkedList<>();
}
@Test
public void testInitialSize() {
assertEquals(0, list.getSize(), "Initial size should be 0.");
}
@Test
public void testAppendAndSize() {
list.append(10);
list.append(20);
list.append(30);
assertEquals(3, list.getSize(), "Size after appends should be 3.");
assertEquals("[ 10, 20, 30 ]", list.toString(), "List content should match appended values.");
}
@Test
public void testRemove() {
list.append(10);
list.append(20);
list.append(30);
int removed = list.remove(1);
assertEquals(20, removed, "Removed element at index 1 should be 20.");
assertEquals("[ 10, 30 ]", list.toString(), "List content should reflect removal.");
assertEquals(2, list.getSize(), "Size after removal should be 2.");
removed = list.remove(0);
assertEquals(10, removed, "Removed element at index 0 should be 10.");
assertEquals("[ 30 ]", list.toString(), "List content should reflect second removal.");
assertEquals(1, list.getSize(), "Size after second removal should be 1.");
}
@Test
public void testRemoveInvalidIndex() {
list.append(10);
list.append(20);
assertThrows(IndexOutOfBoundsException.class, () -> list.remove(2), "Removing at invalid index 2 should throw exception.");
assertThrows(IndexOutOfBoundsException.class, () -> list.remove(-1), "Removing at negative index should throw exception.");
}
@Test
public void testToStringEmpty() {
assertEquals("[]", list.toString(), "Empty list should display as [].");
}
@Test
public void testSingleElement() {
list.append(10);
assertEquals(1, list.getSize(), "Size after adding single element should be 1.");
assertEquals("[ 10 ]", list.toString(), "Single element list string should be formatted correctly.");
int removed = list.remove(0);
assertEquals(10, removed, "Removed element should be the one appended.");
assertEquals("[]", list.toString(), "List should be empty after removing last element.");
assertEquals(0, list.getSize(), "Size after removing last element should be 0.");
}
@Test
public void testNullAppend() {
assertThrows(NullPointerException.class, () -> list.append(null), "Appending null should throw NullPointerException.");
}
@Test
public void testRemoveLastPosition() {
list.append(10);
list.append(20);
list.append(30);
int removed = list.remove(list.getSize() - 1);
assertEquals(30, removed, "Last element removed should be 30.");
assertEquals(2, list.getSize(), "Size should decrease after removing last element.");
}
@Test
public void testRemoveFromEmptyThrows() {
assertThrows(IndexOutOfBoundsException.class, () -> list.remove(0), "Remove from empty list should throw.");
}
@Test
public void testRepeatedAppendAndRemove() {
for (int i = 0; i < 100; i++) {
list.append(i);
}
assertEquals(100, list.getSize());
for (int i = 99; i >= 0; i--) {
int removed = list.remove(i);
assertEquals(i, removed, "Removed element should match appended value.");
}
assertEquals(0, list.getSize(), "List should be empty after all removes.");
}
@Test
public void testToStringAfterMultipleRemoves() {
list.append(1);
list.append(2);
list.append(3);
list.remove(2);
list.remove(0);
assertEquals("[ 2 ]", list.toString(), "ToString should correctly represent remaining elements.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursionTest.java | src/test/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursionTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SearchSinglyLinkedListRecursionTest {
private SearchSinglyLinkedListRecursion list;
@BeforeEach
public void setUp() {
list = new SearchSinglyLinkedListRecursion();
}
@Test
public void testSearchInEmptyList() {
// Test searching for a value in an empty list (should return false)
assertFalse(list.search(1));
}
@Test
public void testSearchSingleElementListFound() {
// Insert a single element and search for it
list.insert(5);
assertTrue(list.search(5));
}
@Test
public void testSearchSingleElementListNotFound() {
// Insert a single element and search for a non-existent value
list.insert(5);
assertFalse(list.search(10));
}
@Test
public void testSearchMultipleElementsListFound() {
// Insert multiple elements and search for a middle value
for (int i = 1; i <= 10; i++) {
list.insert(i);
}
assertTrue(list.search(5));
}
@Test
public void testSearchMultipleElementsListFirstElement() {
// Insert multiple elements and search for the first element
for (int i = 1; i <= 10; i++) {
list.insert(i);
}
assertTrue(list.search(1));
}
@Test
public void testSearchMultipleElementsListLastElement() {
// Insert multiple elements and search for the last element
for (int i = 1; i <= 10; i++) {
list.insert(i);
}
assertTrue(list.search(10));
}
@Test
public void testSearchMultipleElementsListNotFound() {
// Insert multiple elements and search for a non-existent element
for (int i = 1; i <= 10; i++) {
list.insert(i);
}
assertFalse(list.search(15));
}
@Test
public void testSearchNegativeValues() {
// Insert positive and negative values and search for a negative value
list.insert(-5);
list.insert(-10);
list.insert(5);
assertTrue(list.search(-10));
assertFalse(list.search(-3));
}
@Test
public void testSearchZeroValue() {
list.insert(0);
assertTrue(list.search(0));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursionTest.java | src/test/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursionTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class CountSinglyLinkedListRecursionTest {
private CountSinglyLinkedListRecursion list;
@BeforeEach
public void setUp() {
list = new CountSinglyLinkedListRecursion();
}
@Test
@DisplayName("Count of an empty list should be 0")
public void testCountEmptyList() {
assertEquals(0, list.count());
}
@Test
@DisplayName("Count after inserting a single element should be 1")
public void testCountSingleElementList() {
list.insert(1);
assertEquals(1, list.count());
}
@Test
@DisplayName("Count after inserting multiple distinct elements")
public void testCountMultipleElements() {
for (int i = 1; i <= 5; i++) {
list.insert(i);
}
assertEquals(5, list.count());
}
@Test
@DisplayName("Count should reflect total number of nodes with duplicate values")
public void testCountWithDuplicateElements() {
list.insert(2);
list.insert(2);
list.insert(3);
list.insert(3);
list.insert(1);
assertEquals(5, list.count());
}
@Test
@DisplayName("Count should return 0 after clearing the list")
public void testCountAfterClearingList() {
for (int i = 1; i <= 4; i++) {
list.insert(i);
}
list.clear(); // assumed to exist
assertEquals(0, list.count());
}
@Test
@DisplayName("Count on a very large list should be accurate")
public void testCountOnVeryLargeList() {
int n = 1000;
for (int i = 0; i < n; i++) {
list.insert(i);
}
assertEquals(n, list.count());
}
@Test
@DisplayName("Count should work correctly with negative values")
public void testCountOnListWithNegativeNumbers() {
list.insert(-1);
list.insert(-2);
list.insert(-3);
assertEquals(3, list.count());
}
@Test
@DisplayName("Calling count multiple times should return the same value if list is unchanged")
public void testCountIsConsistentWithoutModification() {
list.insert(1);
list.insert(2);
int count1 = list.count();
int count2 = list.count();
assertEquals(count1, count2);
}
@Test
@DisplayName("Count should reflect total even if all values are the same")
public void testCountAllSameValues() {
for (int i = 0; i < 5; i++) {
list.insert(42);
}
assertEquals(5, list.count());
}
@Test
@DisplayName("Count should remain correct after multiple interleaved insert and count operations")
public void testCountAfterEachInsert() {
assertEquals(0, list.count());
list.insert(1);
assertEquals(1, list.count());
list.insert(2);
assertEquals(2, list.count());
list.insert(3);
assertEquals(3, list.count());
}
@Test
@DisplayName("List should not throw on edge count (0 nodes)")
public void testEdgeCaseNoElements() {
assertDoesNotThrow(() -> list.count());
}
@Test
@DisplayName("Should count accurately after inserting then removing all elements")
public void testCountAfterInsertAndClear() {
for (int i = 0; i < 10; i++) {
list.insert(i);
}
assertEquals(10, list.count());
list.clear();
assertEquals(0, list.count());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java | src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MergeSortedArrayListTest {
@Test
void testMergeTwoSortedLists() {
List<Integer> listA = Arrays.asList(1, 3, 5, 7, 9);
List<Integer> listB = Arrays.asList(2, 4, 6, 8, 10);
List<Integer> result = new ArrayList<>();
MergeSortedArrayList.merge(listA, listB, result);
List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
assertEquals(expected, result, "Merged list should be sorted and contain all elements from both input lists.");
}
@Test
void testMergeWithEmptyList() {
List<Integer> listA = Arrays.asList(1, 2, 3);
List<Integer> listB = new ArrayList<>(); // Empty list
List<Integer> result = new ArrayList<>();
MergeSortedArrayList.merge(listA, listB, result);
List<Integer> expected = Arrays.asList(1, 2, 3);
assertEquals(expected, result, "Merged list should match listA when listB is empty.");
}
@Test
void testMergeWithBothEmptyLists() {
List<Integer> listA = new ArrayList<>(); // Empty list
List<Integer> listB = new ArrayList<>(); // Empty list
List<Integer> result = new ArrayList<>();
MergeSortedArrayList.merge(listA, listB, result);
assertTrue(result.isEmpty(), "Merged list should be empty when both input lists are empty.");
}
@Test
void testMergeWithDuplicateElements() {
List<Integer> listA = Arrays.asList(1, 2, 2, 3);
List<Integer> listB = Arrays.asList(2, 3, 4);
List<Integer> result = new ArrayList<>();
MergeSortedArrayList.merge(listA, listB, result);
List<Integer> expected = Arrays.asList(1, 2, 2, 2, 3, 3, 4);
assertEquals(expected, result, "Merged list should correctly handle and include duplicate elements.");
}
@Test
void testMergeWithNegativeAndPositiveNumbers() {
List<Integer> listA = Arrays.asList(-3, -1, 2);
List<Integer> listB = Arrays.asList(-2, 0, 3);
List<Integer> result = new ArrayList<>();
MergeSortedArrayList.merge(listA, listB, result);
List<Integer> expected = Arrays.asList(-3, -2, -1, 0, 2, 3);
assertEquals(expected, result, "Merged list should correctly handle negative and positive numbers.");
}
@Test
void testMergeThrowsExceptionOnNullInput() {
List<Integer> listA = null;
List<Integer> listB = Arrays.asList(1, 2, 3);
List<Integer> result = new ArrayList<>();
List<Integer> finalListB = listB;
List<Integer> finalListA = listA;
List<Integer> finalResult = result;
assertThrows(NullPointerException.class, () -> MergeSortedArrayList.merge(finalListA, finalListB, finalResult), "Should throw NullPointerException if any input list is null.");
listA = Arrays.asList(1, 2, 3);
listB = null;
List<Integer> finalListA1 = listA;
List<Integer> finalListB1 = listB;
List<Integer> finalResult1 = result;
assertThrows(NullPointerException.class, () -> MergeSortedArrayList.merge(finalListA1, finalListB1, finalResult1), "Should throw NullPointerException if any input list is null.");
listA = Arrays.asList(1, 2, 3);
listB = Arrays.asList(4, 5, 6);
result = null;
List<Integer> finalListA2 = listA;
List<Integer> finalListB2 = listB;
List<Integer> finalResult2 = result;
assertThrows(NullPointerException.class, () -> MergeSortedArrayList.merge(finalListA2, finalListB2, finalResult2), "Should throw NullPointerException if the result collection is null.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/SortedLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/SortedLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SortedLinkedListTest {
private SortedLinkedList list;
@BeforeEach
public void setUp() {
list = new SortedLinkedList();
}
@Test
public void testInsertIntoEmptyList() {
list.insert(5);
assertEquals("[5]", list.toString());
}
@Test
public void testInsertInSortedOrder() {
list.insert(5);
list.insert(3);
list.insert(7);
assertEquals("[3, 5, 7]", list.toString());
}
@Test
public void testInsertDuplicateValues() {
list.insert(5);
list.insert(5);
list.insert(5);
assertEquals("[5, 5, 5]", list.toString());
}
@Test
public void testDeleteHeadElement() {
list.insert(1);
list.insert(2);
list.insert(3);
assertTrue(list.delete(1));
assertEquals("[2, 3]", list.toString());
}
@Test
public void testDeleteTailElement() {
list.insert(1);
list.insert(2);
list.insert(3);
assertTrue(list.delete(3));
assertEquals("[1, 2]", list.toString());
}
@Test
public void testDeleteMiddleElement() {
list.insert(1);
list.insert(2);
list.insert(3);
assertTrue(list.delete(2));
assertEquals("[1, 3]", list.toString());
}
@Test
public void testDeleteNonexistentElement() {
list.insert(1);
list.insert(2);
assertFalse(list.delete(3));
}
@Test
public void testDeleteFromSingleElementList() {
list.insert(5);
assertTrue(list.delete(5));
assertEquals("[]", list.toString());
}
@Test
public void testDeleteFromEmptyList() {
assertFalse(list.delete(5));
}
@Test
public void testSearchInEmptyList() {
assertFalse(list.search(5));
}
@Test
public void testSearchForExistingElement() {
list.insert(3);
list.insert(1);
list.insert(5);
assertTrue(list.search(3));
}
@Test
public void testSearchForNonexistentElement() {
list.insert(3);
list.insert(1);
list.insert(5);
assertFalse(list.search(10));
}
@Test
public void testIsEmptyOnEmptyList() {
assertTrue(list.isEmpty());
}
@Test
public void testIsEmptyOnNonEmptyList() {
list.insert(10);
assertFalse(list.isEmpty());
}
@Test
public void testIsEmptyAfterInsertion() {
list.insert(10);
assertFalse(list.isEmpty());
}
@Test
public void testIsEmptyAfterDeletion() {
list.insert(10);
list.delete(10);
assertTrue(list.isEmpty());
}
@Test
public void testInsertNegativeNumbers() {
list.insert(-10);
list.insert(-5);
list.insert(-20);
assertEquals("[-20, -10, -5]", list.toString());
}
@Test
public void testInsertMixedPositiveAndNegativeNumbers() {
list.insert(0);
list.insert(-1);
list.insert(1);
assertEquals("[-1, 0, 1]", list.toString());
}
@Test
public void testMultipleDeletesUntilEmpty() {
list.insert(2);
list.insert(4);
list.insert(6);
assertTrue(list.delete(4));
assertTrue(list.delete(2));
assertTrue(list.delete(6));
assertTrue(list.isEmpty());
assertEquals("[]", list.toString());
}
@Test
public void testDeleteDuplicateValuesOnlyDeletesOneInstance() {
list.insert(5);
list.insert(5);
list.insert(5);
assertTrue(list.delete(5));
assertEquals("[5, 5]", list.toString());
assertTrue(list.delete(5));
assertEquals("[5]", list.toString());
assertTrue(list.delete(5));
assertEquals("[]", list.toString());
}
@Test
public void testSearchOnListWithDuplicates() {
list.insert(7);
list.insert(7);
list.insert(7);
assertTrue(list.search(7));
assertFalse(list.search(10));
}
@Test
public void testToStringOnEmptyList() {
assertEquals("[]", list.toString());
}
@Test
public void testDeleteAllDuplicates() {
list.insert(4);
list.insert(4);
list.insert(4);
assertTrue(list.delete(4));
assertTrue(list.delete(4));
assertTrue(list.delete(4));
assertFalse(list.delete(4)); // nothing left to delete
assertEquals("[]", list.toString());
}
@Test
public void testInsertAfterDeletion() {
list.insert(1);
list.insert(3);
list.insert(5);
assertTrue(list.delete(3));
list.insert(2);
assertEquals("[1, 2, 5]", list.toString());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java | src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
/**
* Test cases for RotateSinglyLinkedLists.
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class RotateSinglyLinkedListsTest {
private final RotateSinglyLinkedLists rotator = new RotateSinglyLinkedLists();
// Helper method to create a linked list from an array of values
private SinglyLinkedListNode createLinkedList(int[] values) {
if (values.length == 0) {
return null;
}
SinglyLinkedListNode head = new SinglyLinkedListNode(values[0]);
SinglyLinkedListNode current = head;
for (int i = 1; i < values.length; i++) {
current.next = new SinglyLinkedListNode(values[i]);
current = current.next;
}
return head;
}
// Helper method to convert a linked list to a string for easy comparison
private String linkedListToString(SinglyLinkedListNode head) {
StringBuilder sb = new StringBuilder();
SinglyLinkedListNode current = head;
while (current != null) {
sb.append(current.value);
if (current.next != null) {
sb.append(" -> ");
}
current = current.next;
}
return sb.toString();
}
@Test
public void testRotateRightEmptyList() {
// Rotate an empty list
assertNull(rotator.rotateRight(null, 2));
}
@Test
public void testRotateRightSingleNodeList() {
// Rotate a list with a single element
SinglyLinkedListNode singleNode = new SinglyLinkedListNode(5);
SinglyLinkedListNode rotatedSingleNode = rotator.rotateRight(singleNode, 3);
assertEquals("5", linkedListToString(rotatedSingleNode));
}
@Test
public void testRotateRightMultipleElementsList() {
// Rotate a list with multiple elements (rotate by 2)
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 2);
assertEquals("4 -> 5 -> 1 -> 2 -> 3", linkedListToString(rotated));
}
@Test
public void testRotateRightFullRotation() {
// Rotate by more than the length of the list
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 7);
assertEquals("4 -> 5 -> 1 -> 2 -> 3", linkedListToString(rotated));
}
@Test
public void testRotateRightZeroRotation() {
// Rotate a list by k = 0 (no rotation)
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 0);
assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated));
}
@Test
public void testRotateRightByListLength() {
// Rotate a list by k equal to list length (no change)
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 5);
assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated));
}
@Test
public void testRotateRightByMultipleOfListLength() {
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 10); // k = 2 * list length
assertEquals("1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated));
}
@Test
public void testRotateRightLongerList() {
// Rotate a longer list by a smaller k
SinglyLinkedListNode head = createLinkedList(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9});
SinglyLinkedListNode rotated = rotator.rotateRight(head, 4);
assertEquals("6 -> 7 -> 8 -> 9 -> 1 -> 2 -> 3 -> 4 -> 5", linkedListToString(rotated));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/CursorLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/CursorLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CursorLinkedListTest {
private CursorLinkedList<String> list;
@BeforeEach
void setUp() {
list = new CursorLinkedList<>();
}
@Test
void testAppendAndGet() {
list.append("First");
list.append("Second");
list.append("Third");
assertEquals("First", list.get(0));
assertEquals("Second", list.get(1));
assertEquals("Third", list.get(2));
assertNull(list.get(3));
assertNull(list.get(-1));
}
@Test
void testIndexOf() {
list.append("First");
list.append("Second");
list.append("Third");
assertEquals(0, list.indexOf("First"));
assertEquals(1, list.indexOf("Second"));
assertEquals(2, list.indexOf("Third"));
assertEquals(-1, list.indexOf("NonExistent"));
}
@Test
void testRemove() {
list.append("First");
list.append("Second");
list.append("Third");
list.remove("Second");
assertEquals("First", list.get(0));
assertEquals("Third", list.get(1));
assertNull(list.get(2));
assertEquals(-1, list.indexOf("Second"));
}
@Test
void testRemoveByIndex() {
list.append("First");
list.append("Second");
list.append("Third");
list.removeByIndex(1);
assertEquals("First", list.get(0));
assertEquals("Third", list.get(1));
assertNull(list.get(2));
}
@Test
void testRemoveFirstElement() {
list.append("First");
list.append("Second");
list.remove("First");
assertEquals("Second", list.get(0));
assertNull(list.get(1));
assertEquals(-1, list.indexOf("First"));
}
@Test
void testRemoveLastElement() {
list.append("First");
list.append("Second");
list.remove("Second");
assertEquals("First", list.get(0));
assertNull(list.get(1));
assertEquals(-1, list.indexOf("Second"));
}
@Test
void testNullHandling() {
assertThrows(NullPointerException.class, () -> list.append(null));
assertThrows(NullPointerException.class, () -> list.remove(null));
assertThrows(NullPointerException.class, () -> list.indexOf(null));
}
@Test
void testEmptyList() {
assertNull(list.get(0));
assertEquals(-1, list.indexOf("Any"));
}
@Test
void testMemoryLimitExceeded() {
// Test adding more elements than CURSOR_SPACE_SIZE
assertThrows(OutOfMemoryError.class, () -> {
for (int i = 0; i < 101; i++) { // CURSOR_SPACE_SIZE is 100
list.append("Element" + i);
}
});
}
@Test
void testSingleElementOperations() {
// Test operations with just one element
list.append("Only");
assertEquals("Only", list.get(0));
assertEquals(0, list.indexOf("Only"));
list.remove("Only");
assertNull(list.get(0));
assertEquals(-1, list.indexOf("Only"));
}
@Test
void testDuplicateElements() {
// Test handling of duplicate elements
list.append("Duplicate");
list.append("Other");
list.append("Duplicate");
assertEquals(0, list.indexOf("Duplicate")); // Should return first occurrence
assertEquals("Duplicate", list.get(0));
assertEquals("Duplicate", list.get(2));
list.remove("Duplicate"); // Should remove first occurrence
assertEquals("Other", list.get(0));
assertEquals("Duplicate", list.get(1));
}
@Test
void testRemoveByIndexEdgeCases() {
list.append("First");
list.append("Second");
list.append("Third");
// Test removing invalid indices
list.removeByIndex(-1); // Should not crash
list.removeByIndex(10); // Should not crash
// Verify list unchanged
assertEquals("First", list.get(0));
assertEquals("Second", list.get(1));
assertEquals("Third", list.get(2));
// Test removing first element by index
list.removeByIndex(0);
assertEquals("Second", list.get(0));
assertEquals("Third", list.get(1));
}
@Test
void testRemoveByIndexLastElement() {
list.append("First");
list.append("Second");
list.append("Third");
// Remove last element by index
list.removeByIndex(2);
assertEquals("First", list.get(0));
assertEquals("Second", list.get(1));
assertNull(list.get(2));
}
@Test
void testConsecutiveOperations() {
// Test multiple consecutive operations
list.append("A");
list.append("B");
list.append("C");
list.append("D");
list.remove("B");
list.remove("D");
assertEquals("A", list.get(0));
assertEquals("C", list.get(1));
assertNull(list.get(2));
list.append("E");
assertEquals("E", list.get(2));
}
@Test
void testMemoryReclamation() {
// Test that removed elements free up memory space
for (int i = 0; i < 50; i++) {
list.append("Element" + i);
}
// Remove some elements
for (int i = 0; i < 25; i++) {
list.remove("Element" + i);
}
// Should be able to add more elements (testing memory reclamation)
for (int i = 100; i < 150; i++) {
list.append("New" + i);
}
// Verify some elements exist
assertEquals("Element25", list.get(0));
assertEquals("New100", list.get(25));
}
@Test
void testSpecialCharacters() {
// Test with strings containing special characters
list.append("Hello World!");
list.append("Test@123");
list.append("Special#$%");
list.append(""); // Empty string
assertEquals("Hello World!", list.get(0));
assertEquals("Test@123", list.get(1));
assertEquals("Special#$%", list.get(2));
assertEquals("", list.get(3));
assertEquals(3, list.indexOf(""));
}
@Test
void testLargeIndices() {
list.append("Test");
// Test very large indices
assertNull(list.get(Integer.MAX_VALUE));
assertNull(list.get(1000));
}
@Test
void testSequentialRemovalByIndex() {
list.append("A");
list.append("B");
list.append("C");
list.append("D");
// Remove elements sequentially by index
list.removeByIndex(1); // Remove "B"
assertEquals("A", list.get(0));
assertEquals("C", list.get(1));
assertEquals("D", list.get(2));
list.removeByIndex(1); // Remove "C"
assertEquals("A", list.get(0));
assertEquals("D", list.get(1));
assertNull(list.get(2));
}
@Test
void testAppendAfterRemoval() {
list.append("First");
list.append("Second");
list.remove("First");
list.append("Third");
assertEquals("Second", list.get(0));
assertEquals("Third", list.get(1));
assertEquals(1, list.indexOf("Third"));
}
@Test
void testPerformanceWithManyOperations() {
// Test with many mixed operations
for (int i = 0; i < 50; i++) {
list.append("Item" + i);
}
// Remove every other element
for (int i = 0; i < 50; i += 2) {
list.remove("Item" + i);
}
// Verify remaining elements
assertEquals("Item1", list.get(0));
assertEquals("Item3", list.get(1));
assertEquals("Item5", list.get(2));
// Add more elements
for (int i = 100; i < 110; i++) {
list.append("New" + i);
}
assertEquals("New100", list.get(25));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgoTest.java | src/test/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgoTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class TortoiseHareAlgoTest {
@Test
void testAppendAndToString() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(10);
list.append(20);
list.append(30);
assertEquals("[10, 20, 30]", list.toString());
}
@Test
void testGetMiddleOdd() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
assertEquals(3, list.getMiddle());
}
@Test
void testGetMiddleEven() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
assertEquals(3, list.getMiddle()); // returns second middle
}
@Test
void testEmptyList() {
TortoiseHareAlgo<Integer> list = new TortoiseHareAlgo<>();
assertNull(list.getMiddle());
assertEquals("[]", list.toString());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CircleLinkedListTest {
private CircleLinkedList<Integer> list;
@BeforeEach
public void setUp() {
list = new CircleLinkedList<>();
}
@Test
public void testInitialSize() {
assertEquals(0, list.getSize(), "Initial size should be 0.");
}
@Test
public void testAppendAndSize() {
list.append(1);
list.append(2);
list.append(3);
assertEquals(3, list.getSize(), "Size after three appends should be 3.");
assertEquals("[ 1, 2, 3 ]", list.toString(), "List content should match appended values.");
}
@Test
public void testRemove() {
list.append(1);
list.append(2);
list.append(3);
list.append(4);
assertEquals(2, list.remove(1), "Removed element at index 1 should be 2.");
assertEquals(3, list.remove(1), "Removed element at index 1 after update should be 3.");
assertEquals("[ 1, 4 ]", list.toString(), "List content should reflect removals.");
assertEquals(2, list.getSize(), "Size after two removals should be 2.");
}
@Test
public void testRemoveInvalidIndex() {
list.append(1);
list.append(2);
assertThrows(IndexOutOfBoundsException.class, () -> list.remove(2), "Should throw on out-of-bounds index.");
assertThrows(IndexOutOfBoundsException.class, () -> list.remove(-1), "Should throw on negative index.");
}
@Test
public void testToStringEmpty() {
assertEquals("[]", list.toString(), "Empty list should be represented by '[]'.");
}
@Test
public void testToStringAfterRemoval() {
list.append(1);
list.append(2);
list.append(3);
list.remove(1);
assertEquals("[ 1, 3 ]", list.toString(), "List content should match remaining elements after removal.");
}
@Test
public void testSingleElement() {
list.append(1);
assertEquals(1, list.getSize(), "Size after single append should be 1.");
assertEquals("[ 1 ]", list.toString(), "Single element list should display properly.");
assertEquals(1, list.remove(0), "Single element removed should match appended value.");
assertEquals("[]", list.toString(), "List should be empty after removing the single element.");
}
@Test
public void testNullElement() {
assertThrows(NullPointerException.class, () -> list.append(null), "Appending null should throw exception.");
}
@Test
public void testCircularReference() {
list.append(1);
list.append(2);
list.append(3);
CircleLinkedList.Node<Integer> current = list.head;
// Traverse one full cycle and verify the circular reference
for (int i = 0; i <= list.getSize(); i++) {
current = current.next;
}
assertEquals(list.head, current, "End of list should point back to the head (circular structure).");
}
@Test
public void testClear() {
list.append(1);
list.append(2);
list.append(3);
// Remove all elements to simulate clearing the list
for (int i = list.getSize() - 1; i >= 0; i--) {
list.remove(i);
}
assertEquals(0, list.getSize(), "Size after clearing should be 0.");
assertEquals("[]", list.toString(), "Empty list should be represented by '[]' after clear.");
assertSame(list.head.next, list.head, "Head's next should point to itself after clearing.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
/**
* Test cases for QuickSortLinkedList.
* Author: Prabhat-Kumar-42
* GitHub: https://github.com/Prabhat-Kumar-42
*/
public class QuickSortLinkedListTest {
@Test
public void testSortEmptyList() {
SinglyLinkedList emptyList = new SinglyLinkedList();
QuickSortLinkedList sorter = new QuickSortLinkedList(emptyList);
sorter.sortList();
assertNull(emptyList.getHead(), "Sorted empty list should have no elements.");
}
@Test
public void testSortSingleNodeList() {
SinglyLinkedList singleNodeList = new SinglyLinkedList();
singleNodeList.insert(5);
QuickSortLinkedList sorter = new QuickSortLinkedList(singleNodeList);
sorter.sortList();
assertEquals(5, singleNodeList.getHead().value, "Single node list should remain unchanged after sorting.");
assertNull(singleNodeList.getHead().next, "Single node should not have a next node.");
}
@Test
public void testSortAlreadySorted() {
SinglyLinkedList sortedList = new SinglyLinkedList();
sortedList.insert(1);
sortedList.insert(2);
sortedList.insert(3);
sortedList.insert(4);
sortedList.insert(5);
QuickSortLinkedList sorter = new QuickSortLinkedList(sortedList);
sorter.sortList();
assertEquals("1->2->3->4->5", sortedList.toString(), "Already sorted list should remain unchanged.");
}
@Test
public void testSortReverseOrderedList() {
SinglyLinkedList reverseList = new SinglyLinkedList();
reverseList.insert(5);
reverseList.insert(4);
reverseList.insert(3);
reverseList.insert(2);
reverseList.insert(1);
QuickSortLinkedList sorter = new QuickSortLinkedList(reverseList);
sorter.sortList();
assertEquals("1->2->3->4->5", reverseList.toString(), "Reverse ordered list should be sorted in ascending order.");
}
@Test
public void testSortWithDuplicates() {
SinglyLinkedList listWithDuplicates = new SinglyLinkedList();
listWithDuplicates.insert(3);
listWithDuplicates.insert(1);
listWithDuplicates.insert(3);
listWithDuplicates.insert(2);
listWithDuplicates.insert(2);
QuickSortLinkedList sorter = new QuickSortLinkedList(listWithDuplicates);
sorter.sortList();
assertEquals("1->2->2->3->3", listWithDuplicates.toString(), "List with duplicates should be sorted correctly.");
}
@Test
public void testSortMultipleElementsList() {
SinglyLinkedList list = new SinglyLinkedList();
list.insert(5);
list.insert(3);
list.insert(8);
list.insert(1);
list.insert(10);
list.insert(2);
list.insert(7);
list.insert(4);
list.insert(9);
list.insert(6);
QuickSortLinkedList sorter = new QuickSortLinkedList(list);
sorter.sortList();
assertEquals("1->2->3->4->5->6->7->8->9->10", list.toString(), "List should be sorted in ascending order.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedListTest.java | package com.thealgorithms.datastructures.lists;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class MergeSortedSinglyLinkedListTest {
@Test
void testMergeTwoSortedLists() {
SinglyLinkedList listA = new SinglyLinkedList();
SinglyLinkedList listB = new SinglyLinkedList();
for (int i = 2; i <= 10; i += 2) {
listA.insert(i);
listB.insert(i - 1);
}
SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
assertEquals("1->2->3->4->5->6->7->8->9->10", mergedList.toString(), "Merged list should contain all elements in sorted order.");
}
@Test
void testMergeWithEmptyListA() {
SinglyLinkedList listA = new SinglyLinkedList(); // Empty listA
SinglyLinkedList listB = new SinglyLinkedList();
listB.insert(1);
listB.insert(3);
listB.insert(5);
SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
assertEquals("1->3->5", mergedList.toString(), "Merged list should match listB when listA is empty.");
}
@Test
void testMergeWithEmptyListB() {
SinglyLinkedList listA = new SinglyLinkedList();
SinglyLinkedList listB = new SinglyLinkedList(); // Empty listB
listA.insert(2);
listA.insert(4);
listA.insert(6);
SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
assertEquals("2->4->6", mergedList.toString(), "Merged list should match listA when listB is empty.");
}
@Test
void testMergeWithBothEmptyLists() {
SinglyLinkedList listA = new SinglyLinkedList(); // Empty listA
SinglyLinkedList listB = new SinglyLinkedList(); // Empty listB
SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
assertEquals("", mergedList.toString(), "Merged list should be empty when both input lists are empty.");
}
@Test
void testMergeWithDuplicateValues() {
SinglyLinkedList listA = new SinglyLinkedList();
SinglyLinkedList listB = new SinglyLinkedList();
listA.insert(1);
listA.insert(3);
listA.insert(5);
listB.insert(1);
listB.insert(4);
listB.insert(5);
SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
assertEquals("1->1->3->4->5->5", mergedList.toString(), "Merged list should include duplicate values in sorted order.");
}
@Test
void testMergeThrowsExceptionOnNullInput() {
SinglyLinkedList listA = null;
SinglyLinkedList listB = new SinglyLinkedList();
listB.insert(1);
listB.insert(2);
SinglyLinkedList finalListA = listA;
SinglyLinkedList finalListB = listB;
assertThrows(NullPointerException.class, () -> MergeSortedSinglyLinkedList.merge(finalListA, finalListB), "Should throw NullPointerException if listA is null.");
listA = new SinglyLinkedList();
listB = null;
SinglyLinkedList finalListA1 = listA;
SinglyLinkedList finalListB1 = listB;
assertThrows(NullPointerException.class, () -> MergeSortedSinglyLinkedList.merge(finalListA1, finalListB1), "Should throw NullPointerException if listB is null.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java | src/test/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueueTest.java | package com.thealgorithms.datastructures.heaps;
import java.util.Comparator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link IndexedPriorityQueue}.
*
* Notes:
* - We mainly use a Node class with a mutable "prio" field to test changeKey/decreaseKey/increaseKey.
* - The queue is a min-heap, so smaller "prio" means higher priority.
* - By default the implementation uses IdentityHashMap so duplicate-equals objects are allowed.
*/
public class IndexedPriorityQueueTest {
// ------------------------
// Helpers
// ------------------------
/** Simple payload with mutable priority. */
static class Node {
final String id;
int prio; // lower is better (min-heap)
Node(String id, int prio) {
this.id = id;
this.prio = prio;
}
@Override
public String toString() {
return id + "(" + prio + ")";
}
}
/** Same as Node but overrides equals/hashCode to simulate "duplicate-equals" scenario. */
static class NodeWithEquals {
final String id;
int prio;
NodeWithEquals(String id, int prio) {
this.id = id;
this.prio = prio;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof NodeWithEquals)) {
return false;
}
NodeWithEquals other = (NodeWithEquals) o;
// Intentionally naive equality: equal if priority is equal
return this.prio == other.prio;
}
@Override
public int hashCode() {
return Integer.hashCode(prio);
}
@Override
public String toString() {
return id + "(" + prio + ")";
}
}
private static IndexedPriorityQueue<Node> newNodePQ() {
return new IndexedPriorityQueue<>(Comparator.comparingInt(n -> n.prio));
}
// ------------------------
// Basic operations
// ------------------------
@Test
void testOfferPollWithIntegersComparableMode() {
// cmp == null -> elements must be Comparable
IndexedPriorityQueue<Integer> pq = new IndexedPriorityQueue<>();
Assertions.assertTrue(pq.isEmpty());
pq.offer(5);
pq.offer(1);
pq.offer(3);
Assertions.assertEquals(3, pq.size());
Assertions.assertEquals(1, pq.peek());
Assertions.assertEquals(1, pq.poll());
Assertions.assertEquals(3, pq.poll());
Assertions.assertEquals(5, pq.poll());
Assertions.assertNull(pq.poll()); // empty -> null
Assertions.assertTrue(pq.isEmpty());
}
@Test
void testPeekAndIsEmpty() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Assertions.assertTrue(pq.isEmpty());
Assertions.assertNull(pq.peek());
pq.offer(new Node("A", 10));
pq.offer(new Node("B", 5));
pq.offer(new Node("C", 7));
Assertions.assertFalse(pq.isEmpty());
Assertions.assertEquals("B(5)", pq.peek().toString());
}
@Test
void testRemoveSpecificElement() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Node b = new Node("B", 5);
Node c = new Node("C", 7);
pq.offer(a);
pq.offer(b);
pq.offer(c);
// remove by reference (O(log n))
Assertions.assertTrue(pq.remove(b));
Assertions.assertEquals(2, pq.size());
// now min should be C(7)
Assertions.assertEquals("C(7)", pq.peek().toString());
// removing an element not present -> false
Assertions.assertFalse(pq.remove(b));
}
@Test
void testContainsAndClear() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 2);
Node b = new Node("B", 3);
pq.offer(a);
pq.offer(b);
Assertions.assertTrue(pq.contains(a));
Assertions.assertTrue(pq.contains(b));
pq.clear();
Assertions.assertTrue(pq.isEmpty());
Assertions.assertFalse(pq.contains(a));
Assertions.assertNull(pq.peek());
}
// ------------------------
// Key updates
// ------------------------
@Test
void testDecreaseKeyMovesUp() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Node b = new Node("B", 5);
Node c = new Node("C", 7);
pq.offer(a);
pq.offer(b);
pq.offer(c);
// current min is B(5)
Assertions.assertEquals("B(5)", pq.peek().toString());
// Make A more important: 10 -> 1 (smaller is better)
pq.decreaseKey(a, n -> n.prio = 1);
// Now A should be at the top
Assertions.assertEquals("A(1)", pq.peek().toString());
}
@Test
void testIncreaseKeyMovesDown() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 1);
Node b = new Node("B", 2);
Node c = new Node("C", 3);
pq.offer(a);
pq.offer(b);
pq.offer(c);
// min is A(1)
Assertions.assertEquals("A(1)", pq.peek().toString());
// Make A worse: 1 -> 100
pq.increaseKey(a, n -> n.prio = 100);
// Now min should be B(2)
Assertions.assertEquals("B(2)", pq.peek().toString());
}
@Test
void testChangeKeyChoosesDirectionAutomatically() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Node b = new Node("B", 20);
Node c = new Node("C", 30);
pq.offer(a);
pq.offer(b);
pq.offer(c);
// Decrease B to 0 -> should move up
pq.changeKey(b, n -> n.prio = 0);
Assertions.assertEquals("B(0)", pq.peek().toString());
// Increase B to 100 -> should move down
pq.changeKey(b, n -> n.prio = 100);
Assertions.assertEquals("A(10)", pq.peek().toString());
}
@Test
void testDirectMutationWithoutChangeKeyDoesNotReheapByDesign() {
// Demonstrates the contract: do NOT mutate comparator fields directly.
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 5);
Node b = new Node("B", 10);
pq.offer(a);
pq.offer(b);
// Illegally mutate priority directly
a.prio = 100; // worse than b now, but heap wasn't notified
// The heap structure is unchanged; peek still returns A(100) (was A(5) before)
// This test documents the behavior/contract rather than relying on it.
Assertions.assertEquals("A(100)", pq.peek().toString());
// Now fix properly via changeKey (no change in value, but triggers reheap)
pq.changeKey(a, n -> n.prio = n.prio);
Assertions.assertEquals("B(10)", pq.peek().toString());
}
// ------------------------
// Identity semantics & duplicates
// ------------------------
@Test
void testDuplicateEqualsElementsAreSupportedIdentityMap() {
IndexedPriorityQueue<NodeWithEquals> pq = new IndexedPriorityQueue<>(Comparator.comparingInt(n -> n.prio));
NodeWithEquals x1 = new NodeWithEquals("X1", 7);
NodeWithEquals x2 = new NodeWithEquals("X2", 7); // equals to X1 by prio, but different instance
// With IdentityHashMap internally, both can coexist
pq.offer(x1);
pq.offer(x2);
Assertions.assertEquals(2, pq.size());
// Poll twice; both 7s should be returned (order between x1/x2 is unspecified)
Assertions.assertEquals(7, pq.poll().prio);
Assertions.assertEquals(7, pq.poll().prio);
Assertions.assertTrue(pq.isEmpty());
}
// ------------------------
// Capacity growth
// ------------------------
@Test
void testGrowByManyInserts() {
IndexedPriorityQueue<Integer> pq = new IndexedPriorityQueue<>();
int n = 100; // beyond default capacity (11)
for (int i = n; i >= 1; i--) {
pq.offer(i);
}
Assertions.assertEquals(n, pq.size());
// Ensure min-to-max order when polling
for (int expected = 1; expected <= n; expected++) {
Integer v = pq.poll();
Assertions.assertEquals(expected, v);
}
Assertions.assertTrue(pq.isEmpty());
Assertions.assertNull(pq.poll());
}
// ------------------------
// remove/contains edge cases
// ------------------------
@Test
void testRemoveHeadAndMiddleAndTail() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 1);
Node b = new Node("B", 2);
Node c = new Node("C", 3);
Node d = new Node("D", 4);
pq.offer(a);
pq.offer(b);
pq.offer(c);
pq.offer(d);
// remove head
Assertions.assertTrue(pq.remove(a));
Assertions.assertFalse(pq.contains(a));
Assertions.assertEquals("B(2)", pq.peek().toString());
// remove middle
Assertions.assertTrue(pq.remove(c));
Assertions.assertFalse(pq.contains(c));
Assertions.assertEquals("B(2)", pq.peek().toString());
// remove tail (last)
Assertions.assertTrue(pq.remove(d));
Assertions.assertFalse(pq.contains(d));
Assertions.assertEquals("B(2)", pq.peek().toString());
// remove last remaining
Assertions.assertTrue(pq.remove(b));
Assertions.assertTrue(pq.isEmpty());
Assertions.assertNull(pq.peek());
}
// ------------------------
// Error / edge cases for coverage
// ------------------------
@Test
void testInvalidInitialCapacityThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new IndexedPriorityQueue<Integer>(0, Comparator.naturalOrder()));
}
@Test
void testChangeKeyOnMissingElementThrows() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Assertions.assertThrows(IllegalArgumentException.class, () -> pq.changeKey(a, n -> n.prio = 5));
}
@Test
void testDecreaseKeyOnMissingElementThrows() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Assertions.assertThrows(IllegalArgumentException.class, () -> pq.decreaseKey(a, n -> n.prio = 5));
}
@Test
void testIncreaseKeyOnMissingElementThrows() {
IndexedPriorityQueue<Node> pq = newNodePQ();
Node a = new Node("A", 10);
Assertions.assertThrows(IllegalArgumentException.class, () -> pq.increaseKey(a, n -> n.prio = 15));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java | src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java | package com.thealgorithms.datastructures.heaps;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for MaxHeap implementation
*/
class MaxHeapTest {
private MaxHeap heap;
@BeforeEach
void setUp() {
// Create a fresh heap for each test
List<HeapElement> elements = Arrays.asList(new HeapElement(5.0, "Five"), new HeapElement(2.0, "Two"), new HeapElement(8.0, "Eight"), new HeapElement(1.0, "One"), new HeapElement(9.0, "Nine"));
heap = new MaxHeap(elements);
}
@Test
void testConstructorWithNullList() {
assertThrows(IllegalArgumentException.class, () -> new MaxHeap(null));
}
@Test
void testConstructorWithEmptyList() {
MaxHeap emptyHeap = new MaxHeap(new ArrayList<>());
assertTrue(emptyHeap.isEmpty());
}
@Test
void testConstructorWithNullElements() {
List<HeapElement> elements = Arrays.asList(new HeapElement(1.0, "One"), null, new HeapElement(2.0, "Two"));
MaxHeap heap = new MaxHeap(elements);
assertEquals(2, heap.size());
}
@Test
void testInsertElement() {
heap.insertElement(new HeapElement(10.0, "Ten"));
assertEquals(10.0, heap.getElement(1).getKey());
assertEquals(6, heap.size());
}
@Test
void testInsertNullElement() {
assertThrows(IllegalArgumentException.class, () -> heap.insertElement(null));
}
@Test
void testGetElementAtIndex() {
HeapElement element = heap.getElement(1);
assertEquals(9.0, element.getKey());
assertEquals("Nine", element.getValue());
}
@Test
void testGetElementAtInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(0));
assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(10));
}
@Test
void testDeleteElement() throws EmptyHeapException {
heap.deleteElement(1);
assertEquals(8.0, heap.getElement(1).getKey());
assertEquals(4, heap.size());
}
@Test
void testDeleteElementAtInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(0));
assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(10));
}
@Test
void testDeleteFromEmptyHeap() {
MaxHeap emptyHeap = new MaxHeap(new ArrayList<>());
assertThrows(EmptyHeapException.class, () -> emptyHeap.deleteElement(1));
}
@Test
void testExtractMax() throws EmptyHeapException {
HeapElement max = heap.getElement();
assertEquals(9.0, max.getKey());
assertEquals("Nine", max.getValue());
assertEquals(4, heap.size());
max = heap.getElement();
assertEquals(8.0, max.getKey());
assertEquals(3, heap.size());
}
@Test
void testExtractMaxFromEmptyHeap() {
MaxHeap emptyHeap = new MaxHeap(new ArrayList<>());
assertThrows(EmptyHeapException.class, () -> emptyHeap.getElement());
}
@Test
void testHeapOrder() {
// Test that parent is always greater than or equal to children
for (int i = 1; i <= heap.size() / 2; i++) {
double parentKey = heap.getElement(i).getKey();
// Check left child
if (2 * i <= heap.size()) {
assertTrue(parentKey >= heap.getElement(2 * i).getKey());
}
// Check right child
if (2 * i + 1 <= heap.size()) {
assertTrue(parentKey >= heap.getElement(2 * i + 1).getKey());
}
}
}
@Test
void testSizeAndEmpty() {
assertEquals(5, heap.size());
assertFalse(heap.isEmpty());
// Remove all elements
while (!heap.isEmpty()) {
try {
heap.getElement();
} catch (EmptyHeapException e) {
Assertions.fail("Should not throw EmptyHeapException while heap is not empty");
}
}
assertEquals(0, heap.size());
assertTrue(heap.isEmpty());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java | src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java | package com.thealgorithms.datastructures.heaps;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class MergeKSortedArraysTest {
@ParameterizedTest
@MethodSource("provideTestCases")
public void testMergeKArrays(int[][] arrays, int[] expected) {
assertArrayEquals(expected, MergeKSortedArrays.mergeKArrays(arrays));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(
// Basic test case with multiple arrays
Arguments.of(new int[][] {{1, 4, 5}, {1, 3, 4}, {2, 6}}, new int[] {1, 1, 2, 3, 4, 4, 5, 6}),
// Edge case: All arrays are empty
Arguments.of(new int[][] {{}, {}, {}}, new int[] {}),
// Edge case: One array is empty
Arguments.of(new int[][] {{1, 3, 5}, {}, {2, 4, 6}}, new int[] {1, 2, 3, 4, 5, 6}),
// Single array
Arguments.of(new int[][] {{1, 2, 3}}, new int[] {1, 2, 3}),
// Arrays with negative numbers
Arguments.of(new int[][] {{-5, 1, 3}, {-10, 0, 2}}, new int[] {-10, -5, 0, 1, 2, 3}),
// Arrays with duplicate elements
Arguments.of(new int[][] {{1, 1, 2}, {1, 3, 3}, {2, 2, 4}}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 4}),
// Edge case: Arrays of varying lengths
Arguments.of(new int[][] {{1, 2}, {3}, {4, 5, 6, 7}}, new int[] {1, 2, 3, 4, 5, 6, 7}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java | src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java | package com.thealgorithms.datastructures.heaps;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LeftistHeapTest {
@Test
void testIsEmpty() {
LeftistHeap heap = new LeftistHeap();
Assertions.assertTrue(heap.isEmpty(), "Heap should be empty initially.");
heap.insert(10);
Assertions.assertFalse(heap.isEmpty(), "Heap should not be empty after insertion.");
heap.clear();
Assertions.assertTrue(heap.isEmpty(), "Heap should be empty after clearing.");
}
@Test
void testInsertAndExtractMin() {
LeftistHeap heap = new LeftistHeap();
heap.insert(6);
heap.insert(2);
heap.insert(3);
heap.insert(1);
Assertions.assertEquals(1, heap.extractMin(), "Minimum should be 1.");
Assertions.assertEquals(2, heap.extractMin(), "Next minimum should be 2.");
Assertions.assertEquals(3, heap.extractMin(), "Next minimum should be 3.");
Assertions.assertEquals(6, heap.extractMin(), "Next minimum should be 6.");
Assertions.assertEquals(-1, heap.extractMin(), "Extracting from an empty heap should return -1.");
}
@Test
void testMerge() {
LeftistHeap heap1 = new LeftistHeap();
heap1.insert(1);
heap1.insert(3);
heap1.insert(5);
LeftistHeap heap2 = new LeftistHeap();
heap2.insert(2);
heap2.insert(4);
heap2.insert(6);
heap1.merge(heap2);
Assertions.assertEquals(1, heap1.extractMin(), "After merging, minimum should be 1.");
Assertions.assertEquals(2, heap1.extractMin(), "Next minimum should be 2.");
Assertions.assertEquals(3, heap1.extractMin(), "Next minimum should be 3.");
Assertions.assertEquals(4, heap1.extractMin(), "Next minimum should be 4.");
Assertions.assertEquals(5, heap1.extractMin(), "Next minimum should be 5.");
Assertions.assertEquals(6, heap1.extractMin(), "Next minimum should be 6.");
Assertions.assertEquals(-1, heap1.extractMin(), "Extracting from an empty heap should return -1.");
}
@Test
void testInOrderTraversal() {
LeftistHeap heap = new LeftistHeap();
heap.insert(10);
heap.insert(5);
heap.insert(20);
heap.insert(15);
heap.insert(30);
Assertions.assertEquals("[20, 15, 30, 5, 10]", heap.inOrder().toString(), "In-order traversal should match the expected output.");
}
@Test
void testMultipleExtractions() {
LeftistHeap heap = new LeftistHeap();
heap.insert(10);
heap.insert(5);
heap.insert(3);
heap.insert(8);
// Extract multiple elements
Assertions.assertEquals(3, heap.extractMin());
Assertions.assertEquals(5, heap.extractMin());
Assertions.assertEquals(8, heap.extractMin());
Assertions.assertEquals(10, heap.extractMin());
Assertions.assertEquals(-1, heap.extractMin(), "Extracting from an empty heap should return -1.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java | src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java | package com.thealgorithms.datastructures.heaps;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class GenericHeapTest {
private GenericHeap<Integer> heap;
@BeforeEach
void setUp() {
heap = new GenericHeap<>();
}
@Test
void testAddAndGet() {
heap.add(10);
heap.add(20);
heap.add(5);
assertEquals(20, heap.get());
}
@Test
void testRemove() {
heap.add(10);
heap.add(20);
heap.add(5);
assertEquals(20, heap.remove());
assertEquals(10, heap.get());
}
@Test
void testIsEmpty() {
assertTrue(heap.isEmpty());
heap.add(1);
assertFalse(heap.isEmpty());
}
@Test
void testSize() {
assertEquals(0, heap.size());
heap.add(1);
heap.add(2);
assertEquals(2, heap.size());
}
@Test
void testUpdatePriority() {
heap.add(10);
heap.add(20);
heap.add(5);
heap.updatePriority(10);
assertEquals(20, heap.get());
heap.add(30);
heap.updatePriority(20); // 20 will be moved up
assertEquals(30, heap.get());
}
@Test
void testRemoveFromEmptyHeap() {
Exception exception = assertThrows(IllegalStateException.class, () -> heap.remove());
assertEquals("Heap is empty", exception.getMessage());
}
@Test
void testGetFromEmptyHeap() {
Exception exception = assertThrows(IllegalStateException.class, () -> heap.get());
assertEquals("Heap is empty", exception.getMessage());
}
@Test
void testUpdatePriorityForNonExistentItem() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> heap.updatePriority(100));
assertEquals("Item not found in the heap", exception.getMessage());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java | src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java | package com.thealgorithms.datastructures.heaps;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class MinHeapTest {
private MinHeap heap;
@BeforeEach
void setUp() {
// Create a fresh heap for each test
List<HeapElement> elements = Arrays.asList(new HeapElement(5.0, "Five"), new HeapElement(2.0, "Two"), new HeapElement(8.0, "Eight"), new HeapElement(1.0, "One"), new HeapElement(9.0, "Nine"));
heap = new MinHeap(elements);
}
@Test
void testConstructorWithNullList() {
assertThrows(IllegalArgumentException.class, () -> new MinHeap(null));
}
@Test
void testConstructorWithEmptyList() {
MinHeap emptyHeap = new MinHeap(new ArrayList<>());
assertTrue(emptyHeap.isEmpty());
}
@Test
void testConstructorWithNullElements() {
List<HeapElement> elements = Arrays.asList(new HeapElement(1.0, "One"), null, new HeapElement(2.0, "Two"));
MinHeap heap = new MinHeap(elements);
assertEquals(2, heap.size());
}
@Test
void testInsertElement() {
heap.insertElement(new HeapElement(0.5, "Half"));
assertEquals(0.5, heap.getElement(1).getKey());
assertEquals(6, heap.size());
}
@Test
void testInsertNullElement() {
assertThrows(IllegalArgumentException.class, () -> heap.insertElement(null));
}
@Test
void testGetElementAtIndex() {
HeapElement element = heap.getElement(1);
assertEquals(1.0, element.getKey());
assertEquals("One", element.getValue());
}
@Test
void testGetElementAtInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(0));
assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(10));
}
@Test
void testDeleteElement() throws EmptyHeapException {
heap.deleteElement(1);
assertEquals(2.0, heap.getElement(1).getKey());
assertEquals(4, heap.size());
}
@Test
void testDeleteElementAtInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(0));
assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(10));
}
@Test
void testDeleteFromEmptyHeap() {
MinHeap emptyHeap = new MinHeap(new ArrayList<>());
assertThrows(EmptyHeapException.class, () -> emptyHeap.deleteElement(1));
}
@Test
void testExtractMin() throws EmptyHeapException {
HeapElement min = heap.getElement();
assertEquals(1.0, min.getKey());
assertEquals("One", min.getValue());
assertEquals(4, heap.size());
min = heap.getElement();
assertEquals(2.0, min.getKey());
assertEquals(3, heap.size());
}
@Test
void testExtractMinFromEmptyHeap() {
MinHeap emptyHeap = new MinHeap(new ArrayList<>());
assertThrows(EmptyHeapException.class, () -> emptyHeap.getElement());
}
@Test
void testHeapOrder() {
// Test that parent is always smaller than or equal to children
for (int i = 1; i <= heap.size() / 2; i++) {
double parentKey = heap.getElement(i).getKey();
// Check left child
if (2 * i <= heap.size()) {
assertTrue(parentKey <= heap.getElement(2 * i).getKey());
}
// Check right child
if (2 * i + 1 <= heap.size()) {
assertTrue(parentKey <= heap.getElement(2 * i + 1).getKey());
}
}
}
@Test
void testSizeAndEmpty() {
assertEquals(5, heap.size());
assertFalse(heap.isEmpty());
// Remove all elements
while (!heap.isEmpty()) {
try {
heap.getElement();
} catch (EmptyHeapException e) {
Assertions.fail("Should not throw EmptyHeapException while heap is not empty");
}
}
assertEquals(0, heap.size());
assertTrue(heap.isEmpty());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/HeapElementTest.java | src/test/java/com/thealgorithms/datastructures/heaps/HeapElementTest.java | package com.thealgorithms.datastructures.heaps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class HeapElementTest {
@Test
void testConstructorAndGetters() {
HeapElement element = new HeapElement(5.0, "Info");
assertEquals(5.0, element.getKey());
assertEquals("Info", element.getInfo());
}
@Test
void testConstructorWithNullInfo() {
HeapElement element = new HeapElement(10);
assertEquals(10, element.getKey());
assertNull(element.getInfo());
}
@Test
void testToString() {
HeapElement element = new HeapElement(7.5, "TestInfo");
assertEquals("Key: 7.5 - TestInfo", element.toString());
HeapElement elementWithoutInfo = new HeapElement(3);
assertEquals("Key: 3.0 - No additional info", elementWithoutInfo.toString());
}
@Test
void testEquals() {
HeapElement element1 = new HeapElement(2.5, "Data");
HeapElement element2 = new HeapElement(2.5, "Data");
HeapElement element3 = new HeapElement(3.0, "DifferentData");
assertEquals(element1, element2); // Same key and info
assertNotEquals(element1, element3); // Different key
assertNotEquals(null, element1); // Check for null
assertNotEquals("String", element1); // Check for different type
}
@Test
void testHashCode() {
HeapElement element1 = new HeapElement(4, "HashMe");
HeapElement element2 = new HeapElement(4, "HashMe");
HeapElement element3 = new HeapElement(4, "DifferentHash");
assertEquals(element1.hashCode(), element2.hashCode()); // Same key and info
assertNotEquals(element1.hashCode(), element3.hashCode()); // Different info
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java | src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java | package com.thealgorithms.datastructures.heaps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MedianFinderTest {
@Test
public void testMedianMaintenance() {
MedianFinder mf = new MedianFinder();
mf.addNum(1);
mf.addNum(2);
assertEquals(1.5, mf.findMedian());
mf.addNum(3);
assertEquals(2.0, mf.findMedian());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java | src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java | package com.thealgorithms.datastructures.heaps;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class MinPriorityQueueTest {
@Test
void testInsertAndPeek() {
MinPriorityQueue queue = new MinPriorityQueue(5);
queue.insert(10);
queue.insert(5);
queue.insert(15);
Assertions.assertEquals(5, queue.peek(), "The minimum element should be 5.");
}
@Test
void testDelete() {
MinPriorityQueue queue = new MinPriorityQueue(5);
queue.insert(10);
queue.insert(5);
queue.insert(15);
Assertions.assertEquals(5, queue.delete(), "The deleted minimum element should be 5.");
Assertions.assertEquals(10, queue.peek(), "After deletion, the new minimum should be 10.");
}
@Test
void testIsEmpty() {
MinPriorityQueue queue = new MinPriorityQueue(5);
Assertions.assertTrue(queue.isEmpty(), "The queue should be empty initially.");
queue.insert(10);
Assertions.assertFalse(queue.isEmpty(), "The queue should not be empty after insertion.");
}
@Test
void testIsFull() {
MinPriorityQueue queue = new MinPriorityQueue(2);
queue.insert(10);
queue.insert(5);
Assertions.assertTrue(queue.isFull(), "The queue should be full after inserting two elements.");
queue.delete();
Assertions.assertFalse(queue.isFull(), "The queue should not be full after deletion.");
}
@Test
void testHeapSort() {
MinPriorityQueue queue = new MinPriorityQueue(5);
queue.insert(10);
queue.insert(5);
queue.insert(15);
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();
}
Assertions.assertArrayEquals(new int[] {1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order.");
}
@Test
void testPeekEmptyQueue() {
MinPriorityQueue queue = new MinPriorityQueue(5);
Assertions.assertThrows(IllegalStateException.class, queue::peek, "Should throw an exception when peeking into an empty queue.");
}
@Test
void testDeleteEmptyQueue() {
MinPriorityQueue queue = new MinPriorityQueue(5);
Assertions.assertThrows(IllegalStateException.class, queue::delete, "Should throw an exception when deleting from an empty queue.");
}
@Test
void testInsertWhenFull() {
MinPriorityQueue queue = new MinPriorityQueue(2);
queue.insert(10);
queue.insert(5);
Assertions.assertThrows(IllegalStateException.class, () -> queue.insert(15), "Should throw an exception when inserting into a full queue.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java | src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java | package com.thealgorithms.datastructures.heaps;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class FibonacciHeapTest {
@Test
void testHeapInsertionAndMinimum() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
fibonacciHeap.insert(5);
fibonacciHeap.insert(3);
fibonacciHeap.insert(1);
fibonacciHeap.insert(18);
fibonacciHeap.insert(33);
Assertions.assertEquals(1, fibonacciHeap.findMin().getKey());
fibonacciHeap.deleteMin();
Assertions.assertEquals(3, fibonacciHeap.findMin().getKey());
}
@Test
void testDeleteMinOnSingleElementHeap() {
FibonacciHeap fibonacciHeap = new FibonacciHeap(10);
Assertions.assertEquals(10, fibonacciHeap.findMin().getKey());
fibonacciHeap.deleteMin();
Assertions.assertTrue(fibonacciHeap.empty());
}
@Test
void testHeapMeld() {
FibonacciHeap heap1 = new FibonacciHeap();
FibonacciHeap heap2 = new FibonacciHeap();
heap1.insert(1);
heap1.insert(2);
heap2.insert(3);
heap2.insert(4);
heap1.meld(heap2);
Assertions.assertEquals(1, heap1.findMin().getKey());
}
@Test
void testHeapSize() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
Assertions.assertEquals(0, fibonacciHeap.size());
fibonacciHeap.insert(5);
Assertions.assertEquals(1, fibonacciHeap.size());
fibonacciHeap.insert(3);
Assertions.assertEquals(2, fibonacciHeap.size());
fibonacciHeap.deleteMin();
Assertions.assertEquals(1, fibonacciHeap.size());
}
@Test
void testCountersRep() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
fibonacciHeap.insert(5);
fibonacciHeap.insert(3);
fibonacciHeap.insert(8);
fibonacciHeap.insert(1);
int[] counters = fibonacciHeap.countersRep();
Assertions.assertEquals(4, counters[0]);
Assertions.assertEquals(0, counters[1]);
}
@Test
void testDeleteMinMultipleElements() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
fibonacciHeap.insert(5);
fibonacciHeap.insert(2);
fibonacciHeap.insert(8);
fibonacciHeap.insert(1);
Assertions.assertEquals(1, fibonacciHeap.findMin().getKey());
fibonacciHeap.deleteMin();
Assertions.assertEquals(2, fibonacciHeap.findMin().getKey());
}
@Test
void testInsertNegativeKeys() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
fibonacciHeap.insert(-10);
fibonacciHeap.insert(-5);
fibonacciHeap.insert(-20);
Assertions.assertEquals(-20, fibonacciHeap.findMin().getKey());
}
@Test
void testDeleteOnEmptyHeap() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
Assertions.assertThrows(NullPointerException.class, () -> { fibonacciHeap.delete(fibonacciHeap.findMin()); });
}
@Test
void testPotentialCalculation() {
FibonacciHeap fibonacciHeap = new FibonacciHeap();
fibonacciHeap.insert(10);
fibonacciHeap.insert(20);
Assertions.assertEquals(2, fibonacciHeap.potential()); // 2 trees, no marked nodes
var node = fibonacciHeap.findMin();
fibonacciHeap.delete(node);
Assertions.assertEquals(1, fibonacciHeap.potential());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/heaps/KthElementFinderTest.java | src/test/java/com/thealgorithms/datastructures/heaps/KthElementFinderTest.java | package com.thealgorithms.datastructures.heaps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KthElementFinderTest {
@Test
public void testFindKthLargest() {
int[] nums = {3, 2, 1, 5, 6, 4};
assertEquals(5, KthElementFinder.findKthLargest(nums, 2));
}
@Test
public void testFindKthSmallest() {
int[] nums = {7, 10, 4, 3, 20, 15};
assertEquals(7, KthElementFinder.findKthSmallest(nums, 3));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java | src/test/java/com/thealgorithms/datastructures/stacks/ReverseStackTest.java | package com.thealgorithms.datastructures.stacks;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Stack;
import org.junit.jupiter.api.Test;
class ReverseStackTest {
@Test
void testReverseNullStack() {
assertThrows(IllegalArgumentException.class, () -> ReverseStack.reverseStack(null), "Reversing a null stack should throw an IllegalArgumentException.");
}
@Test
void testReverseEmptyStack() {
Stack<Integer> stack = new Stack<>();
ReverseStack.reverseStack(stack);
assertTrue(stack.isEmpty(), "Reversing an empty stack should result in an empty stack.");
}
@Test
void testReverseSingleElementStack() {
Stack<Integer> stack = new Stack<>();
stack.push(1);
ReverseStack.reverseStack(stack);
assertEquals(1, stack.peek(), "Reversing a single-element stack should have the same element on top.");
}
@Test
void testReverseTwoElementStack() {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
ReverseStack.reverseStack(stack);
assertEquals(1, stack.pop(), "After reversal, the stack's top element should be the first inserted element.");
assertEquals(2, stack.pop(), "After reversal, the stack's next element should be the second inserted element.");
}
@Test
void testReverseMultipleElementsStack() {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
ReverseStack.reverseStack(stack);
assertEquals(1, stack.pop(), "Stack order after reversal should match the initial push order.");
assertEquals(2, stack.pop());
assertEquals(3, stack.pop());
assertEquals(4, stack.pop());
}
@Test
void testReverseStackAndVerifySize() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
int originalSize = stack.size();
ReverseStack.reverseStack(stack);
assertEquals(originalSize, stack.size(), "Stack size should remain unchanged after reversal.");
assertEquals(10, stack.pop(), "Reversal should place the first inserted element on top.");
assertEquals(20, stack.pop());
assertEquals(30, stack.pop());
assertEquals(40, stack.pop());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayTest.java | src/test/java/com/thealgorithms/datastructures/stacks/StackArrayTest.java | package com.thealgorithms.datastructures.stacks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StackArrayTest {
private Stack<Integer> stack;
@BeforeEach
void setUp() {
stack = new StackArray<>(5); // Initialize a stack with capacity of 5
}
@Test
void testPushAndPop() {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
Assertions.assertEquals(5, stack.pop());
Assertions.assertEquals(4, stack.pop());
Assertions.assertEquals(3, stack.pop());
Assertions.assertEquals(2, stack.pop());
Assertions.assertEquals(1, stack.pop());
}
@Test
void testPeek() {
stack.push(10);
stack.push(20);
stack.push(30);
Assertions.assertEquals(30, stack.peek());
Assertions.assertEquals(3, stack.size());
stack.pop();
Assertions.assertEquals(20, stack.peek());
}
@Test
void testIsEmpty() {
Assertions.assertTrue(stack.isEmpty());
stack.push(42);
Assertions.assertFalse(stack.isEmpty());
stack.pop();
Assertions.assertTrue(stack.isEmpty());
}
@Test
void testResizeOnPush() {
StackArray<Integer> smallStack = new StackArray<>(2);
smallStack.push(1);
smallStack.push(2);
Assertions.assertTrue(smallStack.isFull());
smallStack.push(3);
Assertions.assertFalse(smallStack.isFull());
Assertions.assertEquals(3, smallStack.size());
Assertions.assertEquals(3, smallStack.pop());
Assertions.assertEquals(2, smallStack.pop());
Assertions.assertEquals(1, smallStack.pop());
}
@Test
void testResizeOnPop() {
StackArray<Integer> stack = new StackArray<>(4);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
stack.pop();
stack.pop();
Assertions.assertEquals(1, stack.size());
stack.pop();
Assertions.assertTrue(stack.isEmpty());
}
@Test
void testMakeEmpty() {
stack.push(1);
stack.push(2);
stack.push(3);
stack.makeEmpty();
Assertions.assertTrue(stack.isEmpty());
Assertions.assertThrows(IllegalStateException.class, stack::pop);
}
@Test
void testPopEmptyStackThrowsException() {
Assertions.assertThrows(IllegalStateException.class, stack::pop);
}
@Test
void testPeekEmptyStackThrowsException() {
Assertions.assertThrows(IllegalStateException.class, stack::peek);
}
@Test
void testConstructorWithInvalidSizeThrowsException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new StackArray<>(0));
Assertions.assertThrows(IllegalArgumentException.class, () -> new StackArray<>(-5));
}
@Test
void testDefaultConstructor() {
StackArray<Integer> defaultStack = new StackArray<>();
Assertions.assertEquals(0, defaultStack.size());
defaultStack.push(1);
Assertions.assertEquals(1, defaultStack.size());
}
@Test
void testToString() {
stack.push(1);
stack.push(2);
stack.push(3);
Assertions.assertEquals("StackArray [1, 2, 3]", stack.toString());
}
@Test
void testSingleElementOperations() {
// Test operations with a single element
stack.push(2);
Assertions.assertEquals(1, stack.size());
Assertions.assertFalse(stack.isEmpty());
Assertions.assertEquals(2, stack.peek());
Assertions.assertEquals(2, stack.pop());
Assertions.assertTrue(stack.isEmpty());
}
@Test
void testAlternatingPushPop() {
// Test alternating push and pop operations
stack.push(1);
Assertions.assertEquals(1, stack.pop());
stack.push(2);
stack.push(3);
Assertions.assertEquals(3, stack.pop());
stack.push(4);
Assertions.assertEquals(4, stack.pop());
Assertions.assertEquals(2, stack.pop());
Assertions.assertTrue(stack.isEmpty());
}
@Test
void testPushNullElements() {
// Test pushing null values
stack.push(null);
Assertions.assertEquals(1, stack.size());
Assertions.assertNull(stack.peek());
Assertions.assertNull(stack.pop());
// Mix null and non-null values
stack.push(1);
stack.push(null);
stack.push(2);
Assertions.assertEquals(2, stack.pop());
Assertions.assertNull(stack.pop());
Assertions.assertEquals(1, stack.pop());
}
@Test
void testWithDifferentDataTypes() {
// Test with String type
StackArray<String> stringStack = new StackArray<>(3);
stringStack.push("first");
stringStack.push("second");
stringStack.push("third");
Assertions.assertEquals("third", stringStack.pop());
Assertions.assertEquals("second", stringStack.peek());
Assertions.assertEquals(2, stringStack.size());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java | src/test/java/com/thealgorithms/datastructures/stacks/StackOfLinkedListTest.java | package com.thealgorithms.datastructures.stacks;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class StackOfLinkedListTest {
private LinkedListStack stack;
@BeforeEach
public void setUp() {
stack = new LinkedListStack();
}
@Test
public void testPushAndPeek() {
stack.push(1);
stack.push(2);
stack.push(3);
assertEquals(3, stack.peek(), "Peek should return the last pushed value");
assertEquals(3, stack.getSize(), "Size should reflect the number of elements");
}
@Test
public void testPop() {
stack.push(1);
stack.push(2);
stack.push(3);
assertEquals(3, stack.pop(), "Pop should return the last pushed value");
assertEquals(2, stack.pop(), "Pop should return the next last pushed value");
assertEquals(1, stack.pop(), "Pop should return the first pushed value");
assertTrue(stack.isEmpty(), "Stack should be empty after popping all elements");
}
@Test
public void testPopEmptyStack() {
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, () -> stack.pop(), "Popping from an empty stack should throw NoSuchElementException");
}
@Test
public void testPeekEmptyStack() {
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, () -> stack.peek(), "Peeking into an empty stack should throw NoSuchElementException");
}
@Test
public void testIsEmpty() {
assertTrue(stack.isEmpty(), "Newly created stack should be empty");
stack.push(1);
assertFalse(stack.isEmpty(), "Stack should not be empty after pushing an element");
stack.pop();
assertTrue(stack.isEmpty(), "Stack should be empty after popping the only element");
}
@Test
public void testToString() {
stack.push(1);
stack.push(2);
stack.push(3);
assertEquals("3->2->1", stack.toString(), "String representation of stack should match the expected format");
}
@Test
public void testMultiplePushesAndPops() {
stack.push(5);
stack.push(10);
stack.push(15);
assertEquals(15, stack.pop(), "Pop should return the last pushed value");
assertEquals(10, stack.peek(), "Peek should return the new top value after popping");
assertEquals(10, stack.pop(), "Pop should return the next last pushed value");
assertEquals(5, stack.pop(), "Pop should return the first pushed value");
assertTrue(stack.isEmpty(), "Stack should be empty after popping all elements");
}
@Test
public void testGetSize() {
assertEquals(0, stack.getSize(), "Size of an empty stack should be zero");
stack.push(1);
stack.push(2);
assertEquals(2, stack.getSize(), "Size should reflect the number of elements");
stack.pop();
assertEquals(1, stack.getSize(), "Size should decrease with each pop");
}
@Test
public void testSizeAfterClearingStack() {
stack.push(1);
stack.push(2);
stack.push(3);
// Manually clear the stack
while (!stack.isEmpty()) {
stack.pop();
}
assertTrue(stack.isEmpty(), "Stack should be empty after clearing");
assertEquals(0, stack.getSize(), "Size should be zero after clearing the stack");
}
@Test
public void testSequentialPushAndPop() {
for (int i = 1; i <= 100; i++) {
stack.push(i);
}
assertEquals(100, stack.getSize(), "Size should be 100 after pushing 100 elements");
for (int i = 100; i >= 1; i--) {
assertEquals(i, stack.pop(), "Popping should return values in LIFO order");
}
assertTrue(stack.isEmpty(), "Stack should be empty after popping all elements");
}
@Test
public void testPushZeroAndNegativeValues() {
stack.push(0);
stack.push(-1);
stack.push(-1);
assertEquals(-1, stack.pop(), "Should handle negative values correctly");
assertEquals(-1, stack.pop(), "Should handle negative values correctly");
assertEquals(0, stack.pop(), "Should handle zero value correctly");
}
@Test
public void testPushDuplicateValues() {
stack.push(1);
stack.push(1);
stack.push(1);
assertEquals(3, stack.getSize(), "Should allow duplicate values");
assertEquals(1, stack.pop());
assertEquals(1, stack.pop());
assertEquals(1, stack.pop());
}
@Test
public void testPushAfterEmptyingStack() {
stack.push(1);
stack.push(2);
stack.pop();
stack.pop();
assertTrue(stack.isEmpty(), "Stack should be empty");
stack.push(10);
assertEquals(10, stack.peek(), "Should work correctly after emptying and refilling");
assertEquals(1, stack.getSize(), "Size should be correct after refilling");
}
@Test
public void testPeekDoesNotModifyStack() {
stack.push(1);
int firstPeek = stack.peek();
int secondPeek = stack.peek();
int thirdPeek = stack.peek();
assertEquals(firstPeek, secondPeek, "Multiple peeks should return same value");
assertEquals(secondPeek, thirdPeek, "Multiple peeks should return same value");
assertEquals(1, stack.getSize(), "Peek should not modify stack size");
assertEquals(1, stack.pop(), "Element should still be poppable after peeking");
}
@Test
public void testAlternatingPushAndPop() {
stack.push(1);
assertEquals(1, stack.pop());
stack.push(2);
stack.push(3);
assertEquals(3, stack.pop());
stack.push(4);
assertEquals(4, stack.pop());
assertEquals(2, stack.pop());
assertTrue(stack.isEmpty(), "Stack should be empty after alternating operations");
}
@Test
public void testToStringWithSingleElement() {
stack.push(42);
assertEquals("42", stack.toString(), "String representation with single element should not have arrows");
}
@Test
public void testStackIntegrity() {
// Test that internal state remains consistent
for (int i = 0; i < 10; i++) {
stack.push(i);
assertEquals(i + 1, stack.getSize(), "Size should be consistent during pushes");
assertEquals(i, stack.peek(), "Peek should return last pushed value");
}
for (int i = 9; i >= 0; i--) {
assertEquals(i, stack.peek(), "Peek should return correct value before pop");
assertEquals(i, stack.pop(), "Pop should return values in LIFO order");
assertEquals(i, stack.getSize(), "Size should be consistent during pops");
}
}
@Test
public void testMixedDataTypes() {
// If your stack supports Object types, test with different data types
stack.push(1);
stack.push(2);
assertEquals(Integer.valueOf(2), stack.pop());
assertEquals(Integer.valueOf(1), stack.pop());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java | src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java | package com.thealgorithms.datastructures.stacks;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class NodeStackTest {
private NodeStack<Integer> intStack;
private NodeStack<String> stringStack;
@BeforeEach
void setUp() {
intStack = new NodeStack<>();
stringStack = new NodeStack<>();
}
@Test
@DisplayName("Test push operation")
void testPush() {
NodeStack<Integer> stack = new NodeStack<>();
stack.push(10);
stack.push(20);
assertEquals(20, stack.peek(), "Top element should be 20 after pushing 10 and 20.");
}
@Test
@DisplayName("Test pop operation")
void testPop() {
NodeStack<String> stack = new NodeStack<>();
stack.push("First");
stack.push("Second");
assertEquals("Second", stack.pop(), "Pop should return 'Second', the last pushed element.");
assertEquals("First", stack.pop(), "Pop should return 'First' after 'Second' is removed.");
}
@Test
@DisplayName("Test pop on empty stack throws exception")
void testPopOnEmptyStack() {
NodeStack<Double> stack = new NodeStack<>();
assertThrows(IllegalStateException.class, stack::pop, "Popping an empty stack should throw IllegalStateException.");
}
@Test
@DisplayName("Test peek operation")
void testPeek() {
NodeStack<Integer> stack = new NodeStack<>();
stack.push(5);
stack.push(15);
assertEquals(15, stack.peek(), "Peek should return 15, the top element.");
stack.pop();
assertEquals(5, stack.peek(), "Peek should return 5 after 15 is popped.");
}
@Test
@DisplayName("Test peek on empty stack throws exception")
void testPeekOnEmptyStack() {
NodeStack<String> stack = new NodeStack<>();
assertThrows(IllegalStateException.class, stack::peek, "Peeking an empty stack should throw IllegalStateException.");
}
@Test
@DisplayName("Test isEmpty method")
void testIsEmpty() {
NodeStack<Character> stack = new NodeStack<>();
assertTrue(stack.isEmpty(), "Newly initialized stack should be empty.");
stack.push('A');
org.junit.jupiter.api.Assertions.assertFalse(stack.isEmpty(), "Stack should not be empty after a push operation.");
stack.pop();
assertTrue(stack.isEmpty(), "Stack should be empty after popping the only element.");
}
@Test
@DisplayName("Test size method")
void testSize() {
NodeStack<Integer> stack = new NodeStack<>();
assertEquals(0, stack.size(), "Size of empty stack should be 0.");
stack.push(3);
stack.push(6);
assertEquals(2, stack.size(), "Size should be 2 after pushing two elements.");
stack.pop();
assertEquals(1, stack.size(), "Size should be 1 after popping one element.");
stack.pop();
assertEquals(0, stack.size(), "Size should be 0 after popping all elements.");
}
@Test
@DisplayName("Test push and pop with null values")
void testPushPopWithNull() {
stringStack.push(null);
stringStack.push("not null");
stringStack.push(null);
assertEquals(3, stringStack.size(), "Stack should contain 3 elements including nulls");
org.junit.jupiter.api.Assertions.assertNull(stringStack.pop(), "Should pop null value");
assertEquals("not null", stringStack.pop(), "Should pop 'not null' value");
org.junit.jupiter.api.Assertions.assertNull(stringStack.pop(), "Should pop null value");
assertTrue(stringStack.isEmpty(), "Stack should be empty after popping all elements");
}
@Test
@DisplayName("Test LIFO (Last In First Out) behavior")
void testLifoBehavior() {
int[] values = {1, 2, 3, 4, 5};
// Push values in order
for (int value : values) {
intStack.push(value);
}
// Pop values should be in reverse order
for (int i = values.length - 1; i >= 0; i--) {
assertEquals(values[i], intStack.pop(), "Elements should be popped in LIFO order");
}
}
@Test
@DisplayName("Test peek doesn't modify stack")
void testPeekDoesNotModifyStack() {
intStack.push(1);
intStack.push(2);
intStack.push(3);
int originalSize = intStack.size();
int peekedValue = intStack.peek();
assertEquals(3, peekedValue, "Peek should return top element");
assertEquals(originalSize, intStack.size(), "Peek should not change stack size");
assertEquals(3, intStack.peek(), "Multiple peeks should return same value");
org.junit.jupiter.api.Assertions.assertFalse(intStack.isEmpty(), "Peek should not make stack empty");
}
@Test
@DisplayName("Test mixed push and pop operations")
void testMixedOperations() {
// Test interleaved push/pop operations
intStack.push(1);
assertEquals(1, intStack.pop());
assertTrue(intStack.isEmpty());
intStack.push(2);
intStack.push(3);
assertEquals(3, intStack.pop());
intStack.push(4);
assertEquals(4, intStack.peek());
assertEquals(2, intStack.size());
assertEquals(4, intStack.pop());
assertEquals(2, intStack.pop());
assertTrue(intStack.isEmpty());
}
@Test
@DisplayName("Test stack with duplicate values")
void testStackWithDuplicates() {
intStack.push(1);
intStack.push(1);
intStack.push(1);
assertEquals(3, intStack.size(), "Stack should handle duplicate values");
assertEquals(1, intStack.peek(), "Peek should return duplicate value");
assertEquals(1, intStack.pop(), "Should pop first duplicate");
assertEquals(1, intStack.pop(), "Should pop second duplicate");
assertEquals(1, intStack.pop(), "Should pop third duplicate");
assertTrue(intStack.isEmpty(), "Stack should be empty after popping all duplicates");
}
@Test
@DisplayName("Test stack with different data types")
void testDifferentDataTypes() {
NodeStack<Character> charStack = new NodeStack<>();
NodeStack<Boolean> booleanStack = new NodeStack<>();
// Test with Character
charStack.push('A');
charStack.push('Z');
assertEquals('Z', charStack.peek(), "Should handle Character values");
// Test with Boolean
booleanStack.push(Boolean.TRUE);
booleanStack.push(Boolean.FALSE);
assertEquals(Boolean.FALSE, booleanStack.peek(), "Should handle Boolean values");
}
@Test
@DisplayName("Test stack state consistency after exceptions")
void testStateConsistencyAfterExceptions() {
// Stack should remain consistent after exception-throwing operations
intStack.push(1);
intStack.push(2);
// Try to peek and pop normally first
assertEquals(2, intStack.peek());
assertEquals(2, intStack.pop());
assertEquals(1, intStack.size());
// Pop remaining element
assertEquals(1, intStack.pop());
assertTrue(intStack.isEmpty());
// Now stack is empty, operations should throw exceptions
assertThrows(IllegalStateException.class, intStack::peek);
assertThrows(IllegalStateException.class, intStack::pop);
// Stack should still be in valid empty state
assertTrue(intStack.isEmpty());
assertEquals(0, intStack.size());
// Should be able to push after exceptions
intStack.push(3);
org.junit.jupiter.api.Assertions.assertFalse(intStack.isEmpty());
assertEquals(1, intStack.size());
assertEquals(3, intStack.peek());
}
@Test
@DisplayName("Test single element stack operations")
void testSingleElementStack() {
intStack.push(2);
org.junit.jupiter.api.Assertions.assertFalse(intStack.isEmpty(), "Stack with one element should not be empty");
assertEquals(1, intStack.size(), "Size should be 1");
assertEquals(2, intStack.peek(), "Peek should return the single element");
assertEquals(1, intStack.size(), "Peek should not change size");
assertEquals(2, intStack.pop(), "Pop should return the single element");
assertTrue(intStack.isEmpty(), "Stack should be empty after popping single element");
assertEquals(0, intStack.size(), "Size should be 0 after popping single element");
}
@Test
@DisplayName("Test toString method if implemented")
void testToString() {
// This test assumes NodeStack has a toString method
// If not implemented, this test can be removed or NodeStack can be enhanced
intStack.push(1);
intStack.push(2);
intStack.push(3);
String stackString = intStack.toString();
// Basic check that toString doesn't throw exception and returns something
assertTrue(stackString != null, "toString should not return null");
assertTrue(stackString.length() > 0, "toString should return non-empty string");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java | src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java | package com.thealgorithms.datastructures.stacks;
import java.util.EmptyStackException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StackArrayListTest {
private StackArrayList<Integer> stack;
@BeforeEach
void setUp() {
stack = new StackArrayList<>();
}
@Test
void testPushAndPop() {
stack.push(1);
stack.push(2);
stack.push(3);
Assertions.assertEquals(3, stack.pop());
Assertions.assertEquals(2, stack.pop());
Assertions.assertEquals(1, stack.pop());
}
@Test
void testPeek() {
stack.push(10);
stack.push(20);
Assertions.assertEquals(20, stack.peek()); // Peek should return the top element
stack.pop(); // Remove top element
Assertions.assertEquals(10, stack.peek()); // Peek should now return the new top element
}
@Test
void testIsEmpty() {
Assertions.assertTrue(stack.isEmpty()); // Stack should initially be empty
stack.push(1);
Assertions.assertFalse(stack.isEmpty()); // After pushing, stack should not be empty
stack.pop();
Assertions.assertTrue(stack.isEmpty()); // After popping, stack should be empty again
}
@Test
void testMakeEmpty() {
stack.push(1);
stack.push(2);
stack.push(3);
stack.makeEmpty();
Assertions.assertTrue(stack.isEmpty()); // Stack should be empty after makeEmpty is called
Assertions.assertEquals(0, stack.size()); // Size should be 0 after makeEmpty
}
@Test
void testSize() {
Assertions.assertEquals(0, stack.size()); // Initial size should be 0
stack.push(1);
stack.push(2);
Assertions.assertEquals(2, stack.size()); // Size should reflect number of elements added
stack.pop();
Assertions.assertEquals(1, stack.size()); // Size should decrease with elements removed
}
@Test
void testPopEmptyStackThrowsException() {
Assertions.assertThrows(EmptyStackException.class, stack::pop); // Popping from an empty stack should throw an exception
}
@Test
void testPeekEmptyStackThrowsException() {
Assertions.assertThrows(EmptyStackException.class, stack::peek); // Peeking into an empty stack should throw an exception
}
@Test
void testMixedOperations() {
// Testing a mix of push, pop, peek, and size operations in sequence
stack.push(5);
stack.push(10);
stack.push(15);
Assertions.assertEquals(3, stack.size()); // Size should reflect number of elements
Assertions.assertEquals(15, stack.peek()); // Peek should show last element added
stack.pop(); // Remove top element
Assertions.assertEquals(10, stack.peek()); // New top should be 10
Assertions.assertEquals(2, stack.size()); // Size should reflect removal
stack.push(20); // Add a new element
Assertions.assertEquals(20, stack.peek()); // Top should be the last added element
}
@Test
void testMultipleMakeEmptyCalls() {
// Ensures calling makeEmpty multiple times does not throw errors or misbehave
stack.push(1);
stack.push(2);
stack.makeEmpty();
Assertions.assertTrue(stack.isEmpty());
stack.makeEmpty();
Assertions.assertTrue(stack.isEmpty());
Assertions.assertEquals(0, stack.size());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Random;
import org.junit.jupiter.api.Test;
abstract class MapTest {
abstract <Key extends Comparable<Key>, Value> Map<Key, Value> getMap();
@Test
void putTest() {
Map<Integer, String> map = getMap();
assertFalse(map.put(null, "-25"));
assertFalse(map.put(null, null));
assertTrue(map.put(-25, "-25"));
assertTrue(map.put(33, "33"));
assertTrue(map.put(100, "100"));
assertTrue(map.put(100, "+100"));
assertTrue(map.put(100, null));
}
@Test
void getTest() {
Map<Integer, String> map = getMap();
for (int i = -100; i < 100; i++) {
map.put(i, String.valueOf(i));
}
for (int i = -100; i < 100; i++) {
assertEquals(map.get(i), String.valueOf(i));
}
for (int i = 100; i < 200; i++) {
assertNull(map.get(i));
}
assertNull(map.get(null));
}
@Test
void deleteTest() {
Map<Integer, String> map = getMap();
for (int i = -100; i < 100; i++) {
map.put(i, String.valueOf(i));
}
for (int i = 0; i < 100; i++) {
assertTrue(map.delete(i));
}
for (int i = 100; i < 200; i++) {
assertFalse(map.delete(i));
}
assertFalse(map.delete(null));
}
@Test
void containsTest() {
Map<Integer, String> map = getMap();
for (int i = -100; i < 100; i++) {
map.put(i, String.valueOf(i));
}
for (int i = -50; i < 50; i++) {
assertTrue(map.contains(i));
}
for (int i = 100; i < 200; i++) {
assertFalse(map.contains(i));
}
assertFalse(map.contains(null));
}
@Test
void sizeTest() {
Map<Integer, String> map = getMap();
assertEquals(map.size(), 0);
for (int i = -100; i < 100; i++) {
map.put(i, String.valueOf(i));
}
assertEquals(map.size(), 200);
for (int i = -50; i < 50; i++) {
map.delete(i);
}
assertEquals(map.size(), 100);
}
@Test
void keysTest() {
Map<Integer, String> map = getMap();
Iterable<Integer> keys = map.keys();
assertFalse(keys.iterator().hasNext());
for (int i = 100; i > -100; i--) {
map.put(i, String.valueOf(i));
}
keys = map.keys();
int i = -100;
for (Integer key : keys) {
assertEquals(key, ++i);
}
}
@Test
void hashTest() {
Map<Integer, String> map = getMap();
int testSize = 100;
Random random = new Random();
for (int i = 0; i < 1000; i++) {
int randomInt = random.nextInt();
int hashIndex = map.hash(randomInt, testSize);
int negateHashIndex = map.hash(-randomInt, testSize);
assertTrue(hashIndex >= 0);
assertTrue(hashIndex < testSize);
assertTrue(negateHashIndex >= 0);
assertTrue(negateHashIndex < testSize);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/ImmutableHashMapTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/ImmutableHashMapTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ImmutableHashMapTest {
@Test
void testEmptyMap() {
ImmutableHashMap<String, Integer> map = ImmutableHashMap.<String, Integer>empty();
assertEquals(0, map.size());
assertNull(map.get("A"));
}
@Test
void testPutDoesNotModifyOriginalMap() {
ImmutableHashMap<String, Integer> map1 = ImmutableHashMap.<String, Integer>empty();
ImmutableHashMap<String, Integer> map2 = map1.put("A", 1);
assertEquals(0, map1.size());
assertEquals(1, map2.size());
assertNull(map1.get("A"));
assertEquals(1, map2.get("A"));
}
@Test
void testMultiplePuts() {
ImmutableHashMap<String, Integer> map = ImmutableHashMap.<String, Integer>empty().put("A", 1).put("B", 2);
assertEquals(2, map.size());
assertEquals(1, map.get("A"));
assertEquals(2, map.get("B"));
}
@Test
void testContainsKey() {
ImmutableHashMap<String, Integer> map = ImmutableHashMap.<String, Integer>empty().put("X", 100);
assertTrue(map.containsKey("X"));
assertFalse(map.containsKey("Y"));
}
@Test
void testNullKey() {
ImmutableHashMap<String, Integer> map = ImmutableHashMap.<String, Integer>empty().put(null, 50);
assertEquals(50, map.get(null));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class GenericHashMapUsingArrayListTest {
@Test
void testGenericHashmapWhichUsesArrayAndBothKeyAndValueAreStrings() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
map.put("USA", "Washington DC");
map.put("Nepal", "Kathmandu");
map.put("India", "New Delhi");
map.put("Australia", "Sydney");
assertNotNull(map);
assertEquals(4, map.size());
assertEquals("Kathmandu", map.get("Nepal"));
assertEquals("Sydney", map.get("Australia"));
}
@Test
void testGenericHashmapWhichUsesArrayAndKeyIsStringValueIsInteger() {
GenericHashMapUsingArrayList<String, Integer> map = new GenericHashMapUsingArrayList<>();
map.put("USA", 87);
map.put("Nepal", 25);
map.put("India", 101);
map.put("Australia", 99);
assertNotNull(map);
assertEquals(4, map.size());
assertEquals(25, map.get("Nepal"));
assertEquals(99, map.get("Australia"));
map.remove("Nepal");
assertFalse(map.containsKey("Nepal"));
}
@Test
void testGenericHashmapWhichUsesArrayAndKeyIsIntegerValueIsString() {
GenericHashMapUsingArrayList<Integer, String> map = new GenericHashMapUsingArrayList<>();
map.put(101, "Washington DC");
map.put(34, "Kathmandu");
map.put(46, "New Delhi");
map.put(89, "Sydney");
assertNotNull(map);
assertEquals(4, map.size());
assertEquals("Sydney", map.get(89));
assertEquals("Washington DC", map.get(101));
assertTrue(map.containsKey(46));
}
@Test
void testRemoveNonExistentKey() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
map.put("USA", "Washington DC");
map.remove("Nepal"); // Attempting to remove a non-existent key
assertEquals(1, map.size()); // Size should remain the same
}
@Test
void testRehashing() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
for (int i = 0; i < 20; i++) {
map.put("Key" + i, "Value" + i);
}
assertEquals(20, map.size()); // Ensure all items were added
assertEquals("Value5", map.get("Key5")); // Check retrieval after rehash
}
@Test
void testUpdateValueForExistingKey() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
map.put("USA", "Washington DC");
map.put("USA", "New Washington DC"); // Updating value for existing key
assertEquals("New Washington DC", map.get("USA"));
}
@Test
void testToStringMethod() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
map.put("USA", "Washington DC");
map.put("Nepal", "Kathmandu");
String expected = "{USA : Washington DC, Nepal : Kathmandu}";
assertEquals(expected, map.toString());
}
@Test
void testContainsKey() {
GenericHashMapUsingArrayList<String, String> map = new GenericHashMapUsingArrayList<>();
map.put("USA", "Washington DC");
assertTrue(map.containsKey("USA"));
assertFalse(map.containsKey("Nepal"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class GenericHashMapUsingArrayTest {
@Test
void testGenericHashmapWhichUsesArrayAndBothKeyAndValueAreStrings() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
map.put("USA", "Washington DC");
map.put("Nepal", "Kathmandu");
map.put("India", "New Delhi");
map.put("Australia", "Sydney");
assertNotNull(map);
assertEquals(4, map.size());
assertEquals("Kathmandu", map.get("Nepal"));
assertEquals("Sydney", map.get("Australia"));
}
@Test
void testGenericHashmapWhichUsesArrayAndKeyIsStringValueIsInteger() {
GenericHashMapUsingArray<String, Integer> map = new GenericHashMapUsingArray<>();
map.put("USA", 87);
map.put("Nepal", 25);
map.put("India", 101);
map.put("Australia", 99);
assertNotNull(map);
assertEquals(4, map.size());
assertEquals(25, map.get("Nepal"));
assertEquals(99, map.get("Australia"));
map.remove("Nepal");
assertFalse(map.containsKey("Nepal"));
}
@Test
void testGenericHashmapWhichUsesArrayAndKeyIsIntegerValueIsString() {
GenericHashMapUsingArray<Integer, String> map = new GenericHashMapUsingArray<>();
map.put(101, "Washington DC");
map.put(34, "Kathmandu");
map.put(46, "New Delhi");
map.put(89, "Sydney");
assertNotNull(map);
assertEquals(4, map.size());
assertEquals("Sydney", map.get(89));
assertEquals("Washington DC", map.get(101));
assertTrue(map.containsKey(46));
}
@Test
void testRemoveNonExistentKey() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
map.put("USA", "Washington DC");
map.remove("Nepal"); // Attempting to remove a non-existent key
assertEquals(1, map.size()); // Size should remain the same
}
@Test
void testRehashing() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
for (int i = 0; i < 20; i++) {
map.put("Key" + i, "Value" + i);
}
assertEquals(20, map.size()); // Ensure all items were added
assertEquals("Value5", map.get("Key5")); // Check retrieval after rehash
}
@Test
void testUpdateValueForExistingKey() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
map.put("USA", "Washington DC");
map.put("USA", "New Washington DC"); // Updating value for existing key
assertEquals("New Washington DC", map.get("USA"));
}
@Test
void testToStringMethod() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
map.put("USA", "Washington DC");
map.put("Nepal", "Kathmandu");
String expected = "{USA : Washington DC, Nepal : Kathmandu}";
assertEquals(expected, map.toString());
}
@Test
void testContainsKey() {
GenericHashMapUsingArray<String, String> map = new GenericHashMapUsingArray<>();
map.put("USA", "Washington DC");
assertTrue(map.containsKey("USA"));
assertFalse(map.containsKey("Nepal"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashingTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashingTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class HashMapCuckooHashingTest {
@Test
void insertKey() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
assertEquals(0, hashTable.getNumberOfKeysInTable());
hashTable.insertKey2HashTable(3);
assertEquals(1, hashTable.getNumberOfKeysInTable());
}
@Test
void getKeyIndex() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(8);
hashTable.insertKey2HashTable(4);
assertNotEquals(-1, hashTable.findKeyInTable(8));
}
@Test
void containsKey() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(8);
boolean contains = hashTable.checkTableContainsKey(8);
assertTrue(contains);
}
@Test
void removeKey() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(3);
int initialSize = hashTable.getNumberOfKeysInTable();
hashTable.deleteKeyFromHashTable(3);
assertEquals(initialSize - 1, hashTable.getNumberOfKeysInTable());
}
@Test
void removeNone() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
try {
hashTable.deleteKeyFromHashTable(3);
} catch (Exception e) {
assertTrue(true);
return;
}
Assertions.fail("Expected exception when trying to delete a non-existing key.");
}
@Test
void reHashTableIncreasesTableSize() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(1);
hashTable.insertKey2HashTable(2);
hashTable.insertKey2HashTable(3);
hashTable.insertKey2HashTable(4);
hashTable.insertKey2HashTable(5);
hashTable.insertKey2HashTable(6);
hashTable.insertKey2HashTable(7);
hashTable.insertKey2HashTable(8);
hashTable.insertKey2HashTable(9);
hashTable.insertKey2HashTable(10); // This should trigger rehashing
assertEquals(10, hashTable.getNumberOfKeysInTable());
}
@Test
void hashFunctionsAreDifferent() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(33);
assertNotEquals(hashTable.hashFunction1(3), hashTable.hashFunction2(3), "Hash functions should produce different indices.");
}
@Test
void avoidInfiniteLoops() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(0);
hashTable.insertKey2HashTable(10);
hashTable.insertKey2HashTable(100);
assertTrue(hashTable.checkTableContainsKey(0));
assertTrue(hashTable.checkTableContainsKey(10));
assertTrue(hashTable.checkTableContainsKey(100));
}
@Test
void testLoadFactor() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
for (int i = 1; i <= 8; i++) { // Insert 8 keys to test load factor
hashTable.insertKey2HashTable(i);
}
assertEquals(8, hashTable.getNumberOfKeysInTable());
// Check that rehashing occurs when a 9th key is added
hashTable.insertKey2HashTable(9);
assertTrue(hashTable.getNumberOfKeysInTable() > 8, "Load factor exceeded, table should have been resized.");
}
@Test
void testDeleteNonExistentKey() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(1);
hashTable.insertKey2HashTable(2);
Exception exception = null;
try {
hashTable.deleteKeyFromHashTable(3); // Try deleting a non-existent key
} catch (IllegalArgumentException e) {
exception = e; // Capture the exception
}
assertNotNull(exception, "Expected an IllegalArgumentException when deleting a non-existent key.");
}
@Test
void testInsertDuplicateKey() {
HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10);
hashTable.insertKey2HashTable(1);
Exception exception = null;
try {
hashTable.insertKey2HashTable(1); // Attempt to insert duplicate key
} catch (IllegalArgumentException e) {
exception = e; // Capture the exception
}
assertNotNull(exception, "Expected an IllegalArgumentException for duplicate key insertion.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
public class MajorityElementTest {
@Test
void testMajorityWithSingleMajorityElement() {
int[] nums = {1, 2, 3, 9, 9, 6, 7, 8, 9, 9, 9, 9};
List<Integer> expected = new ArrayList<>();
expected.add(9);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithMultipleMajorityElements() {
int[] nums = {1, 2, 3, 3, 4, 4, 4, 4};
List<Integer> expected = new ArrayList<>();
expected.add(4);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithNoMajorityElement() {
int[] nums = {1, 2, 4, 4, 5, 4};
List<Integer> expected = new ArrayList<>();
expected.add(4);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithEmptyArray() {
int[] nums = {};
List<Integer> expected = Collections.emptyList();
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithAllElementsSame() {
int[] nums = {5, 5, 5, 5, 5};
List<Integer> expected = new ArrayList<>();
expected.add(5);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithEvenCountAndOneMajorityElement() {
int[] nums = {1, 2, 2, 3, 3, 2};
List<Integer> expected = new ArrayList<>();
expected.add(2);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithNoElementsEqualToHalf() {
int[] nums = {1, 1, 2, 2, 3, 3, 4};
List<Integer> expected = Collections.emptyList();
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
@Test
void testMajorityWithLargeArray() {
int[] nums = {1, 2, 3, 1, 1, 1, 2, 1, 1};
List<Integer> expected = new ArrayList<>();
expected.add(1);
List<Integer> actual = MajorityElement.majority(nums);
assertEquals(expected, actual);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/IntersectionTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
public class IntersectionTest {
@Test
void testBasicIntersection() {
int[] arr1 = {1, 2, 2, 1};
int[] arr2 = {2, 2};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertEquals(List.of(2, 2), result, "Intersection should return [2, 2]");
}
@Test
void testNoIntersection() {
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertTrue(result.isEmpty(), "Intersection should be empty for disjoint sets");
}
@Test
void testEmptyArray() {
int[] arr1 = {};
int[] arr2 = {1, 2, 3};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertTrue(result.isEmpty(), "Intersection should be empty when first array is empty");
result = Intersection.intersection(arr2, arr1);
assertTrue(result.isEmpty(), "Intersection should be empty when second array is empty");
}
@Test
void testNullArray() {
int[] arr1 = null;
int[] arr2 = {1, 2, 3};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertTrue(result.isEmpty(), "Intersection should be empty when first array is null");
result = Intersection.intersection(arr2, arr1);
assertTrue(result.isEmpty(), "Intersection should be empty when second array is null");
}
@Test
void testMultipleOccurrences() {
int[] arr1 = {5, 5, 5, 6};
int[] arr2 = {5, 5, 6, 6, 6};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertEquals(List.of(5, 5, 6), result, "Intersection should return [5, 5, 6]");
}
@Test
void testSameElements() {
int[] arr1 = {1, 1, 1};
int[] arr2 = {1, 1, 1};
List<Integer> result = Intersection.intersection(arr1, arr2);
assertEquals(List.of(1, 1, 1), result, "Intersection should return [1, 1, 1] for same elements");
}
@Test
void testLargeArrays() {
int[] arr1 = new int[1000];
int[] arr2 = new int[1000];
for (int i = 0; i < 1000; i++) {
arr1[i] = i;
arr2[i] = i;
}
List<Integer> result = Intersection.intersection(arr1, arr2);
assertEquals(1000, result.size(), "Intersection should return all elements for identical large arrays");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
public class HashMapTest {
@Test
public void testInsertAndSearch() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(15, "Value15");
hashMap.insert(25, "Value25");
hashMap.insert(35, "Value35");
assertEquals("Value15", hashMap.search(15));
assertEquals("Value25", hashMap.search(25));
assertEquals("Value35", hashMap.search(35));
assertNull(hashMap.search(45)); // Test for non-existent key
}
@Test
public void testDelete() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(15, "Value15");
hashMap.insert(25, "Value25");
hashMap.insert(35, "Value35");
assertEquals("Value25", hashMap.search(25));
hashMap.delete(25);
assertNull(hashMap.search(25)); // Confirm deletion
}
@Test
public void testDisplay() {
HashMap<Integer, String> hashMap = new HashMap<>(5);
hashMap.insert(15, "Value15");
hashMap.insert(25, "Value25");
hashMap.insert(35, "Value35");
// Optionally verify display functionality if it returns a string
hashMap.display(); // Manual check during test execution
}
@Test
public void testInsertNullKey() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(null, "NullValue");
assertEquals("NullValue", hashMap.search(null)); // Verify null key handling
}
@Test
public void testInsertNullValue() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(15, null);
assertNull(hashMap.search(15)); // Verify null value handling
}
@Test
public void testUpdateExistingKey() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(15, "Value15");
hashMap.insert(15, "UpdatedValue15");
assertEquals("UpdatedValue15", hashMap.search(15)); // Verify update
}
@Test
public void testHandleCollisions() {
HashMap<Integer, String> hashMap = new HashMap<>(3); // Create a small bucket size to force collisions
// These keys should collide if the hash function is modulo 3
hashMap.insert(1, "Value1");
hashMap.insert(4, "Value4");
hashMap.insert(7, "Value7");
assertEquals("Value1", hashMap.search(1));
assertEquals("Value4", hashMap.search(4));
assertEquals("Value7", hashMap.search(7));
}
@Test
public void testSearchInEmptyHashMap() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
assertNull(hashMap.search(10)); // Confirm search returns null in empty map
}
@Test
public void testDeleteNonExistentKey() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(15, "Value15");
hashMap.delete(25); // Delete non-existent key
assertEquals("Value15", hashMap.search(15)); // Ensure existing key remains
assertNull(hashMap.search(25)); // Confirm non-existent key remains null
}
@Test
public void testInsertLargeNumberOfElements() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
for (int i = 0; i < 100; i++) {
hashMap.insert(i, "Value" + i);
}
for (int i = 0; i < 100; i++) {
assertEquals("Value" + i, hashMap.search(i)); // Verify all inserted values
}
}
@Test
public void testDeleteHeadOfBucket() {
HashMap<Integer, String> hashMap = new HashMap<>(3);
hashMap.insert(1, "Value1");
hashMap.insert(4, "Value4");
hashMap.insert(7, "Value7");
hashMap.delete(1);
assertNull(hashMap.search(1)); // Verify head deletion
assertEquals("Value4", hashMap.search(4));
assertEquals("Value7", hashMap.search(7));
}
@Test
public void testDeleteTailOfBucket() {
HashMap<Integer, String> hashMap = new HashMap<>(3);
hashMap.insert(1, "Value1");
hashMap.insert(4, "Value4");
hashMap.insert(7, "Value7");
hashMap.delete(7);
assertNull(hashMap.search(7)); // Verify tail deletion
assertEquals("Value1", hashMap.search(1));
assertEquals("Value4", hashMap.search(4));
}
@Test
public void testDeleteMiddleElementOfBucket() {
HashMap<Integer, String> hashMap = new HashMap<>(3);
hashMap.insert(1, "Value1");
hashMap.insert(4, "Value4");
hashMap.insert(7, "Value7");
hashMap.delete(4);
assertNull(hashMap.search(4)); // Verify middle element deletion
assertEquals("Value1", hashMap.search(1));
assertEquals("Value7", hashMap.search(7));
}
@Test
public void testResizeHashMap() {
HashMap<Integer, String> hashMap = new HashMap<>(2); // Small initial size to force rehashing
for (int i = 0; i < 10; i++) {
hashMap.insert(i, "Value" + i);
}
// Verify all values after resizing
for (int i = 0; i < 10; i++) {
assertEquals("Value" + i, hashMap.search(i));
}
}
@Test
public void testCollisionResolution() {
HashMap<String, String> hashMap = new HashMap<>(3);
hashMap.insert("abc", "Value1"); // Hash index 0
hashMap.insert("cab", "Value2"); // Hash index 0 (collision)
hashMap.insert("bac", "Value3"); // Hash index 0 (collision)
assertEquals("Value1", hashMap.search("abc"));
assertEquals("Value2", hashMap.search("cab"));
assertEquals("Value3", hashMap.search("bac"));
}
@Test
public void testClearHashMap() {
HashMap<Integer, String> hashMap = new HashMap<>(10);
hashMap.insert(1, "Value1");
hashMap.insert(2, "Value2");
hashMap.clear(); // Assuming clear method resets the hash map
assertNull(hashMap.search(1));
assertNull(hashMap.search(2));
assertEquals(0, hashMap.size()); // Verify size is reset
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java | src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java | package com.thealgorithms.datastructures.hashmap.hashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class LinearProbingHashMapTest extends MapTest {
@Override
<Key extends Comparable<Key>, Value> Map<Key, Value> getMap() {
return new LinearProbingHashMap<>();
}
@Test
void putNullKey() {
Map<Integer, String> map = getMap();
assertFalse(map.put(null, "value"), "Putting a null key should return false");
}
@Test
void putDuplicateKeys() {
Map<Integer, String> map = getMap();
map.put(1, "one");
map.put(1, "uno");
assertEquals("uno", map.get(1), "Value should be updated to 'uno'");
}
@Test
void putResizeTest() {
Map<Integer, String> map = getMap();
for (int i = 0; i < 20; i++) {
map.put(i, String.valueOf(i));
}
assertEquals(20, map.size(), "Map size should be 20 after inserting 20 elements");
}
@Test
void deleteNonExistentKey() {
Map<Integer, String> map = getMap();
assertFalse(map.delete(999), "Deleting a non-existent key should return false");
}
@Test
void deleteAndReinsert() {
Map<Integer, String> map = getMap();
map.put(1, "one");
map.delete(1);
assertFalse(map.contains(1), "Map should not contain the deleted key");
map.put(1, "one again");
assertTrue(map.contains(1), "Map should contain the key after reinsertion");
}
@Test
void resizeDown() {
Map<Integer, String> map = getMap();
for (int i = 0; i < 16; i++) {
map.put(i, String.valueOf(i));
}
for (int i = 0; i < 12; i++) {
map.delete(i);
}
assertEquals(4, map.size(), "Map size should be 4 after deleting 12 elements");
}
@Test
void keysOrderTest() {
Map<Integer, String> map = getMap();
for (int i = 10; i > 0; i--) {
map.put(i, String.valueOf(i));
}
int expectedKey = 1;
for (Integer key : map.keys()) {
assertEquals(expectedKey++, key, "Keys should be in sorted order");
}
}
@Test
void stressTest() {
Map<Integer, String> map = getMap();
for (int i = 0; i < 1000; i++) {
map.put(i, String.valueOf(i));
assertEquals(i + 1, map.size(), "Size should match number of inserted elements");
}
for (int i = 0; i < 500; i++) {
map.delete(i);
assertEquals(1000 - (i + 1), map.size(), "Size should decrease correctly");
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java | src/test/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximumTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class SlidingWindowMaximumTest {
@ParameterizedTest
@MethodSource("provideTestCases")
public void testMaxSlidingWindow(int[] nums, int k, int[] expected) {
assertArrayEquals(expected, SlidingWindowMaximum.maxSlidingWindow(nums, k));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(
// Test case 1: Example from the problem statement
Arguments.of(new int[] {1, 3, -1, -3, 5, 3, 6, 7}, 3, new int[] {3, 3, 5, 5, 6, 7}),
// Test case 2: All elements are the same
Arguments.of(new int[] {4, 4, 4, 4, 4}, 2, new int[] {4, 4, 4, 4}),
// Test case 3: Window size equals the array length
Arguments.of(new int[] {2, 1, 5, 3, 6}, 5, new int[] {6}),
// Test case 4: Single element array with window size 1
Arguments.of(new int[] {7}, 1, new int[] {7}),
// Test case 5: Window size larger than the array length
Arguments.of(new int[] {1, 2, 3}, 4, new int[] {}),
// Test case 6: Decreasing sequence
Arguments.of(new int[] {9, 8, 7, 6, 5, 4}, 3, new int[] {9, 8, 7, 6}),
// Test case 7: Increasing sequence
Arguments.of(new int[] {1, 2, 3, 4, 5}, 2, new int[] {2, 3, 4, 5}),
// Test case 8: k is zero
Arguments.of(new int[] {1, 3, -1, -3, 5, 3, 6, 7}, 0, new int[] {}),
// Test case 9: Array with negative numbers
Arguments.of(new int[] {-4, -2, -5, -1, -3}, 3, new int[] {-2, -1, -1}),
// Test case 10: Empty array
Arguments.of(new int[] {}, 3, new int[] {}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java | src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class QueueByTwoStacksTest {
private QueueByTwoStacks<Integer> queue;
@BeforeEach
public void setUp() {
queue = new QueueByTwoStacks<>();
}
@Test
public void testEmptyQueue() {
assertEquals(0, queue.size());
}
@Test
public void testEnqueue() {
queue.put(10);
queue.put(20);
assertEquals(2, queue.size());
}
@Test
public void testDequeue() {
queue.put(10);
queue.put(20);
queue.put(30);
assertEquals(10, queue.get());
assertEquals(20, queue.get());
assertEquals(30, queue.get());
}
@Test
public void testInterleavedOperations() {
queue.put(10);
queue.put(20);
assertEquals(10, queue.get());
queue.put(30);
assertEquals(20, queue.get());
assertEquals(30, queue.get());
}
@Test
public void testQueueSize() {
assertEquals(0, queue.size());
queue.put(1);
assertEquals(1, queue.size());
queue.put(2);
queue.put(3);
assertEquals(3, queue.size());
queue.get();
assertEquals(2, queue.size());
}
@Test
public void testEmptyQueueException() {
assertThrows(NoSuchElementException.class, () -> queue.get());
}
@Test
public void testDequeueAllElements() {
for (int i = 1; i <= 5; i++) {
queue.put(i);
}
for (int i = 1; i <= 5; i++) {
assertEquals(i, queue.get());
}
assertEquals(0, queue.size());
}
@Test
public void testLargeNumberOfOperations() {
int n = 1000;
for (int i = 0; i < n; i++) {
queue.put(i);
}
for (int i = 0; i < n; i++) {
assertEquals(i, queue.get());
}
assertEquals(0, queue.size());
}
@Test
public void testRefillDuringDequeue() {
queue.put(1);
queue.put(2);
assertEquals(1, queue.get());
queue.put(3);
queue.put(4);
assertEquals(2, queue.get());
assertEquals(3, queue.get());
assertEquals(4, queue.get());
}
@Test
public void testAlternatingPutAndGet() {
queue.put(1);
assertEquals(1, queue.get());
queue.put(2);
queue.put(3);
assertEquals(2, queue.get());
queue.put(4);
assertEquals(3, queue.get());
assertEquals(4, queue.get());
}
@Test
public void testSizeStability() {
queue.put(100);
int size1 = queue.size();
int size2 = queue.size();
assertEquals(size1, size2);
}
@Test
public void testMultipleEmptyDequeues() {
assertThrows(NoSuchElementException.class, () -> queue.get());
assertThrows(NoSuchElementException.class, () -> queue.get());
}
@Test
public void testQueueWithStrings() {
QueueByTwoStacks<String> stringQueue = new QueueByTwoStacks<>();
stringQueue.put("a");
stringQueue.put("b");
assertEquals("a", stringQueue.get());
assertEquals("b", stringQueue.get());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java | src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class LinkedQueueTest {
private LinkedQueue<Integer> queue;
@BeforeEach
void setUp() {
queue = new LinkedQueue<>();
}
@Test
void testIsEmptyOnNewQueue() {
assertTrue(queue.isEmpty(), "Queue should be empty on initialization.");
}
@Test
void testEnqueueAndSize() {
queue.enqueue(10);
assertFalse(queue.isEmpty(), "Queue should not be empty after enqueue.");
assertEquals(1, queue.size(), "Queue size should be 1 after one enqueue.");
queue.enqueue(20);
queue.enqueue(30);
assertEquals(3, queue.size(), "Queue size should be 3 after three enqueues.");
}
@Test
void testDequeueOnSingleElementQueue() {
queue.enqueue(10);
assertEquals(10, queue.dequeue(), "Dequeued element should be the same as the enqueued one.");
assertTrue(queue.isEmpty(), "Queue should be empty after dequeueing the only element.");
}
@Test
void testDequeueMultipleElements() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals(10, queue.dequeue(), "First dequeued element should be the first enqueued one.");
assertEquals(20, queue.dequeue(), "Second dequeued element should be the second enqueued one.");
assertEquals(30, queue.dequeue(), "Third dequeued element should be the third enqueued one.");
assertTrue(queue.isEmpty(), "Queue should be empty after dequeueing all elements.");
}
@Test
void testDequeueOnEmptyQueue() {
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, () -> queue.dequeue(), "Dequeueing from an empty queue should throw NoSuchElementException.");
}
@Test
void testPeekFrontOnEmptyQueue() {
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, () -> queue.peekFront(), "Peeking front on an empty queue should throw NoSuchElementException.");
}
@Test
void testPeekRearOnEmptyQueue() {
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, () -> queue.peekRear(), "Peeking rear on an empty queue should throw NoSuchElementException.");
}
@Test
void testPeekFront() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals(10, queue.peekFront(), "Peek front should return the first enqueued element.");
assertEquals(10, queue.peekFront(), "Peek front should not remove the element.");
assertEquals(3, queue.size(), "Queue size should remain unchanged after peek.");
}
@Test
void testPeekRear() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals(30, queue.peekRear(), "Peek rear should return the last enqueued element.");
assertEquals(30, queue.peekRear(), "Peek rear should not remove the element.");
assertEquals(3, queue.size(), "Queue size should remain unchanged after peek.");
}
@Test
void testPeekAtPosition() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals(10, queue.peek(1), "Peek at position 1 should return the first enqueued element.");
assertEquals(20, queue.peek(2), "Peek at position 2 should return the second enqueued element.");
assertEquals(30, queue.peek(3), "Peek at position 3 should return the third enqueued element.");
}
@Test
void testPeekAtInvalidPosition() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
org.junit.jupiter.api.Assertions.assertThrows(IndexOutOfBoundsException.class, () -> queue.peek(4), "Peeking at a position greater than size should throw IndexOutOfBoundsException.");
org.junit.jupiter.api.Assertions.assertThrows(IndexOutOfBoundsException.class, () -> queue.peek(0), "Peeking at position 0 should throw IndexOutOfBoundsException.");
}
@Test
void testClearQueue() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.clear();
assertTrue(queue.isEmpty(), "Queue should be empty after clear.");
assertEquals(0, queue.size(), "Queue size should be 0 after clear.");
}
@Test
void testIterator() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
Iterator<Integer> it = queue.iterator();
assertTrue(it.hasNext(), "Iterator should have next element.");
assertEquals(10, it.next(), "First iterator value should be the first enqueued element.");
assertEquals(20, it.next(), "Second iterator value should be the second enqueued element.");
assertEquals(30, it.next(), "Third iterator value should be the third enqueued element.");
assertFalse(it.hasNext(), "Iterator should not have next element after last element.");
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, it::next, "Calling next() on exhausted iterator should throw NoSuchElementException.");
}
@Test
void testToString() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals("[10, 20, 30]", queue.toString(), "toString should return a properly formatted string representation of the queue.");
}
@Test
void testEnqueueAfterDequeue() {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
assertEquals(10, queue.dequeue(), "Dequeued element should be 10.");
assertEquals(20, queue.dequeue(), "Dequeued element should be 20.");
queue.enqueue(40);
assertEquals(30, queue.peekFront(), "Peek front should return 30 after dequeuing and enqueuing new elements.");
assertEquals(40, queue.peekRear(), "Peek rear should return 40 after enqueuing new elements.");
}
@Test
void testQueueMaintainsOrder() {
for (int i = 1; i <= 100; i++) {
queue.enqueue(i);
}
for (int i = 1; i <= 100; i++) {
assertEquals(i, queue.dequeue(), "Queue should maintain the correct order of elements.");
}
assertTrue(queue.isEmpty(), "Queue should be empty after dequeuing all elements.");
}
@Test
void testSizeAfterOperations() {
assertEquals(0, queue.size(), "Initial queue size should be 0.");
queue.enqueue(10);
assertEquals(1, queue.size(), "Queue size should be 1 after one enqueue.");
queue.enqueue(20);
assertEquals(2, queue.size(), "Queue size should be 2 after two enqueues.");
queue.dequeue();
assertEquals(1, queue.size(), "Queue size should be 1 after one dequeue.");
queue.clear();
assertEquals(0, queue.size(), "Queue size should be 0 after clear.");
}
@Test
void testQueueToStringOnEmptyQueue() {
assertEquals("[]", queue.toString(), "toString on empty queue should return '[]'.");
}
@Test
void testEnqueueNull() {
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> queue.enqueue(null), "Cannot enqueue null data.");
}
@Test
void testIteratorOnEmptyQueue() {
Iterator<Integer> it = queue.iterator();
assertFalse(it.hasNext(), "Iterator on empty queue should not have next element.");
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, it::next, "Calling next() on empty queue iterator should throw NoSuchElementException.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/TokenBucketTest.java | src/test/java/com/thealgorithms/datastructures/queues/TokenBucketTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class TokenBucketTest {
@Test
public void testRateLimiter() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 1);
for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
assertFalse(bucket.allowRequest());
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
}
@Test
public void testRateLimiterWithExceedingRequests() throws InterruptedException {
TokenBucket bucket = new TokenBucket(3, 1);
for (int i = 0; i < 3; i++) {
assertTrue(bucket.allowRequest());
}
assertFalse(bucket.allowRequest());
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());
}
@Test
public void testRateLimiterMultipleRefills() throws InterruptedException {
TokenBucket bucket = new TokenBucket(2, 1);
assertTrue(bucket.allowRequest());
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());
}
@Test
public void testRateLimiterEmptyBucket() {
TokenBucket bucket = new TokenBucket(0, 1);
assertFalse(bucket.allowRequest());
}
@Test
public void testRateLimiterWithHighRefillRate() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 10);
for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
assertFalse(bucket.allowRequest());
Thread.sleep(1000);
for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
}
@Test
public void testRateLimiterWithSlowRequests() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 1);
for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
Thread.sleep(2000);
assertTrue(bucket.allowRequest());
assertTrue(bucket.allowRequest());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java | src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java | package com.thealgorithms.datastructures.queues;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class PriorityQueuesTest {
@Test
void testPQInsertion() {
PriorityQueue myQueue = new PriorityQueue(4);
myQueue.insert(2);
Assertions.assertEquals(myQueue.peek(), 2);
myQueue.insert(5);
myQueue.insert(3);
Assertions.assertEquals(myQueue.peek(), 5);
myQueue.insert(10);
Assertions.assertEquals(myQueue.peek(), 10);
}
@Test
void testPQDeletion() {
PriorityQueue myQueue = new PriorityQueue(4);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
myQueue.insert(10);
myQueue.remove();
Assertions.assertEquals(myQueue.peek(), 5);
myQueue.remove();
myQueue.remove();
Assertions.assertEquals(myQueue.peek(), 2);
}
@Test
void testPQExtra() {
PriorityQueue myQueue = new PriorityQueue(4);
Assertions.assertEquals(myQueue.isEmpty(), true);
Assertions.assertEquals(myQueue.isFull(), false);
myQueue.insert(2);
myQueue.insert(5);
Assertions.assertEquals(myQueue.isFull(), false);
myQueue.insert(3);
myQueue.insert(10);
Assertions.assertEquals(myQueue.isEmpty(), false);
Assertions.assertEquals(myQueue.isFull(), true);
myQueue.remove();
Assertions.assertEquals(myQueue.getSize(), 3);
Assertions.assertEquals(myQueue.peek(), 5);
myQueue.remove();
myQueue.remove();
Assertions.assertEquals(myQueue.peek(), 2);
Assertions.assertEquals(myQueue.getSize(), 1);
}
@Test
void testInsertUntilFull() {
PriorityQueue pq = new PriorityQueue(3);
pq.insert(1);
pq.insert(4);
pq.insert(2);
Assertions.assertTrue(pq.isFull());
Assertions.assertEquals(4, pq.peek());
}
@Test
void testRemoveFromEmpty() {
PriorityQueue pq = new PriorityQueue(3);
Assertions.assertThrows(RuntimeException.class, pq::remove);
}
@Test
void testInsertDuplicateValues() {
PriorityQueue pq = new PriorityQueue(5);
pq.insert(5);
pq.insert(5);
pq.insert(3);
Assertions.assertEquals(5, pq.peek());
pq.remove();
Assertions.assertEquals(5, pq.peek());
pq.remove();
Assertions.assertEquals(3, pq.peek());
}
@Test
void testSizeAfterInsertAndRemove() {
PriorityQueue pq = new PriorityQueue(4);
Assertions.assertEquals(0, pq.getSize());
pq.insert(2);
Assertions.assertEquals(1, pq.getSize());
pq.insert(10);
Assertions.assertEquals(2, pq.getSize());
pq.remove();
Assertions.assertEquals(1, pq.getSize());
pq.remove();
Assertions.assertEquals(0, pq.getSize());
}
@Test
void testInsertAndRemoveAll() {
PriorityQueue pq = new PriorityQueue(3);
pq.insert(8);
pq.insert(1);
pq.insert(6);
Assertions.assertTrue(pq.isFull());
pq.remove();
pq.remove();
pq.remove();
Assertions.assertTrue(pq.isEmpty());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/QueueTest.java | src/test/java/com/thealgorithms/datastructures/queues/QueueTest.java | package com.thealgorithms.datastructures.queues;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class QueueTest {
private static final int INITIAL_CAPACITY = 3;
private Queue<Integer> queue;
@BeforeEach
void setUp() {
queue = new Queue<>(INITIAL_CAPACITY);
}
@Test
void testQueueInsertion() {
Assertions.assertTrue(queue.insert(1));
Assertions.assertTrue(queue.insert(2));
Assertions.assertTrue(queue.insert(3));
Assertions.assertFalse(queue.insert(4)); // Queue is full
Assertions.assertEquals(1, queue.peekFront());
Assertions.assertEquals(3, queue.peekRear());
Assertions.assertEquals(3, queue.getSize());
}
@Test
void testQueueRemoval() {
queue.insert(1);
queue.insert(2);
queue.insert(3);
Assertions.assertEquals(1, queue.remove());
Assertions.assertEquals(2, queue.peekFront());
Assertions.assertEquals(2, queue.getSize());
Assertions.assertEquals(2, queue.remove());
Assertions.assertEquals(3, queue.peekFront());
Assertions.assertEquals(1, queue.getSize());
Assertions.assertEquals(3, queue.remove());
Assertions.assertTrue(queue.isEmpty());
Assertions.assertThrows(IllegalStateException.class, queue::remove); // Queue is empty
}
@Test
void testPeekFrontAndRear() {
queue.insert(1);
queue.insert(2);
Assertions.assertEquals(1, queue.peekFront());
Assertions.assertEquals(2, queue.peekRear());
queue.insert(3);
Assertions.assertEquals(1, queue.peekFront());
Assertions.assertEquals(3, queue.peekRear());
}
@Test
void testQueueIsEmptyAndIsFull() {
Assertions.assertTrue(queue.isEmpty());
Assertions.assertFalse(queue.isFull());
queue.insert(1);
queue.insert(2);
queue.insert(3);
Assertions.assertFalse(queue.isEmpty());
Assertions.assertTrue(queue.isFull());
queue.remove();
Assertions.assertFalse(queue.isFull());
Assertions.assertFalse(queue.isEmpty());
}
@Test
void testQueueSize() {
Assertions.assertEquals(0, queue.getSize());
queue.insert(1);
Assertions.assertEquals(1, queue.getSize());
queue.insert(2);
Assertions.assertEquals(2, queue.getSize());
queue.insert(3);
Assertions.assertEquals(3, queue.getSize());
queue.remove();
Assertions.assertEquals(2, queue.getSize());
}
@Test
void testQueueToString() {
Assertions.assertEquals("[]", queue.toString());
queue.insert(1);
queue.insert(2);
Assertions.assertEquals("[1, 2]", queue.toString());
queue.insert(3);
Assertions.assertEquals("[1, 2, 3]", queue.toString());
queue.remove();
Assertions.assertEquals("[2, 3]", queue.toString());
queue.remove();
queue.remove();
Assertions.assertEquals("[]", queue.toString());
}
@Test
void testQueueThrowsExceptionOnEmptyPeek() {
Assertions.assertThrows(IllegalStateException.class, queue::peekFront);
Assertions.assertThrows(IllegalStateException.class, queue::peekRear);
}
@Test
void testQueueThrowsExceptionOnRemoveFromEmptyQueue() {
Assertions.assertThrows(IllegalStateException.class, queue::remove);
}
@Test
void testQueueCapacityException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new Queue<>(0));
Assertions.assertThrows(IllegalArgumentException.class, () -> new Queue<>(-5));
}
@Test
void testCircularBehavior() {
// Test that queue behaves correctly after multiple insert/remove cycles
queue.insert(1);
queue.insert(2);
queue.insert(3);
// Remove all elements
queue.remove(); // removes 1
queue.remove(); // removes 2
queue.remove(); // removes 3
// Add elements again to test circular behavior
queue.insert(4);
queue.insert(5);
queue.insert(6);
Assertions.assertEquals(4, queue.peekFront());
Assertions.assertEquals(6, queue.peekRear());
Assertions.assertEquals(3, queue.getSize());
Assertions.assertTrue(queue.isFull());
}
@Test
void testMixedInsertRemoveOperations() {
// Test interleaved insert and remove operations
queue.insert(1);
queue.insert(2);
Assertions.assertEquals(1, queue.remove());
queue.insert(3);
queue.insert(4);
Assertions.assertEquals(2, queue.remove());
Assertions.assertEquals(3, queue.remove());
queue.insert(5);
queue.insert(6);
Assertions.assertEquals(4, queue.peekFront());
Assertions.assertEquals(6, queue.peekRear());
Assertions.assertEquals(3, queue.getSize());
}
@Test
void testSingleElementOperations() {
// Test operations with single element
queue.insert(42);
Assertions.assertEquals(42, queue.peekFront());
Assertions.assertEquals(42, queue.peekRear());
Assertions.assertEquals(1, queue.getSize());
Assertions.assertFalse(queue.isEmpty());
Assertions.assertFalse(queue.isFull());
Assertions.assertEquals(42, queue.remove());
Assertions.assertTrue(queue.isEmpty());
Assertions.assertEquals(0, queue.getSize());
}
@Test
void testNullValueHandling() {
// Test queue with null values (if supported)
Queue<String> stringQueue = new Queue<>(3);
Assertions.assertTrue(stringQueue.insert(null));
Assertions.assertTrue(stringQueue.insert("test"));
Assertions.assertTrue(stringQueue.insert(null));
Assertions.assertNull(stringQueue.peekFront());
Assertions.assertNull(stringQueue.peekRear());
Assertions.assertEquals(3, stringQueue.getSize());
Assertions.assertNull(stringQueue.remove());
Assertions.assertEquals("test", stringQueue.peekFront());
}
@Test
void testStringDataType() {
// Test queue with String data type
Queue<String> stringQueue = new Queue<>(2);
stringQueue.insert("first");
stringQueue.insert("second");
Assertions.assertEquals("first", stringQueue.peekFront());
Assertions.assertEquals("second", stringQueue.peekRear());
}
@Test
void testLargerCapacityQueue() {
// Test queue with larger capacity
Queue<Integer> largeQueue = new Queue<>(10);
// Fill the queue
for (int i = 1; i <= 10; i++) {
Assertions.assertTrue(largeQueue.insert(i));
}
Assertions.assertTrue(largeQueue.isFull());
Assertions.assertFalse(largeQueue.insert(11));
// Remove half the elements
for (int i = 1; i <= 5; i++) {
Assertions.assertEquals(i, largeQueue.remove());
}
Assertions.assertEquals(6, largeQueue.peekFront());
Assertions.assertEquals(10, largeQueue.peekRear());
Assertions.assertEquals(5, largeQueue.getSize());
}
@Test
void testQueueCapacityOne() {
// Test queue with capacity of 1
Queue<Integer> singleQueue = new Queue<>(1);
Assertions.assertTrue(singleQueue.isEmpty());
Assertions.assertFalse(singleQueue.isFull());
Assertions.assertTrue(singleQueue.insert(100));
Assertions.assertTrue(singleQueue.isFull());
Assertions.assertFalse(singleQueue.isEmpty());
Assertions.assertFalse(singleQueue.insert(200));
Assertions.assertEquals(100, singleQueue.peekFront());
Assertions.assertEquals(100, singleQueue.peekRear());
Assertions.assertEquals(100, singleQueue.remove());
Assertions.assertTrue(singleQueue.isEmpty());
}
@Test
void testQueueWraparoundIndexing() {
// Test that internal array indexing wraps around correctly
queue.insert(1);
queue.insert(2);
queue.insert(3); // Queue full
// Remove one element
queue.remove(); // removes 1
// Add another element (should wrap around)
queue.insert(4);
Assertions.assertEquals("[2, 3, 4]", queue.toString());
Assertions.assertEquals(2, queue.peekFront());
Assertions.assertEquals(4, queue.peekRear());
// Continue the pattern
queue.remove(); // removes 2
queue.insert(5);
Assertions.assertEquals(3, queue.peekFront());
Assertions.assertEquals(5, queue.peekRear());
}
@Test
void testQueueStateAfterMultipleCycles() {
// Test queue state after multiple complete fill/empty cycles
for (int cycle = 0; cycle < 3; cycle++) {
// Fill the queue
for (int i = 1; i <= 3; i++) {
queue.insert(i + cycle * 10);
}
// Verify state
Assertions.assertTrue(queue.isFull());
Assertions.assertEquals(3, queue.getSize());
// Empty the queue
for (int i = 1; i <= 3; i++) {
queue.remove();
}
// Verify empty state
Assertions.assertTrue(queue.isEmpty());
Assertions.assertEquals(0, queue.getSize());
}
}
@Test
void testQueueConsistencyAfterOperations() {
// Test that queue maintains consistency after various operations
queue.insert(10);
queue.insert(20);
int firstRemoved = queue.remove();
queue.insert(30);
queue.insert(40);
int secondRemoved = queue.remove();
queue.insert(50);
// Verify the order is maintained
Assertions.assertEquals(10, firstRemoved);
Assertions.assertEquals(20, secondRemoved);
Assertions.assertEquals(30, queue.peekFront());
Assertions.assertEquals(50, queue.peekRear());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java | src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class CircularQueueTest {
@Test
void testEnQueue() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
cq.enQueue(3);
assertEquals(1, cq.peek());
assertTrue(cq.isFull());
}
@Test
void testDeQueue() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
cq.enQueue(3);
assertEquals(1, cq.deQueue());
assertEquals(2, cq.peek());
assertFalse(cq.isFull());
}
@Test
void testIsEmpty() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
assertTrue(cq.isEmpty());
cq.enQueue(1);
assertFalse(cq.isEmpty());
}
@Test
void testIsFull() {
CircularQueue<Integer> cq = new CircularQueue<>(2);
cq.enQueue(1);
cq.enQueue(2);
assertTrue(cq.isFull());
cq.deQueue();
assertFalse(cq.isFull());
}
@Test
void testPeek() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
assertEquals(1, cq.peek());
assertEquals(1, cq.peek()); // Ensure peek doesn't remove the element
}
@Test
void testDeleteQueue() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
cq.deleteQueue();
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::peek);
}
@Test
void testEnQueueOnFull() {
CircularQueue<Integer> cq = new CircularQueue<>(2);
cq.enQueue(1);
cq.enQueue(2);
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, () -> cq.enQueue(3));
}
@Test
void testDeQueueOnEmpty() {
CircularQueue<Integer> cq = new CircularQueue<>(2);
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::deQueue);
}
@Test
void testPeekOnEmpty() {
CircularQueue<Integer> cq = new CircularQueue<>(2);
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::peek);
}
@Test
void testSize() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
assertEquals(2, cq.size());
cq.deQueue();
assertEquals(1, cq.size());
}
@Test
void testCircularWrapAround() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
cq.enQueue(3);
cq.deQueue();
cq.enQueue(4);
assertEquals(2, cq.deQueue());
assertEquals(3, cq.deQueue());
assertEquals(4, cq.deQueue());
assertTrue(cq.isEmpty());
}
@Test
void testEnQueueDeQueueMultipleTimes() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.enQueue(2);
cq.deQueue();
cq.enQueue(3);
cq.enQueue(4);
assertTrue(cq.isFull());
assertEquals(2, cq.deQueue());
assertEquals(3, cq.deQueue());
assertEquals(4, cq.deQueue());
assertTrue(cq.isEmpty());
}
@Test
void testMultipleWrapArounds() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
cq.enQueue(1);
cq.deQueue();
cq.enQueue(2);
cq.deQueue();
cq.enQueue(3);
cq.deQueue();
cq.enQueue(4);
assertEquals(4, cq.peek());
}
@Test
void testSizeDuringOperations() {
CircularQueue<Integer> cq = new CircularQueue<>(3);
assertEquals(0, cq.size());
cq.enQueue(1);
cq.enQueue(2);
assertEquals(2, cq.size());
cq.deQueue();
assertEquals(1, cq.size());
cq.enQueue(3);
cq.enQueue(4);
assertEquals(3, cq.size());
cq.deQueue();
cq.deQueue();
assertEquals(1, cq.size());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/GenericArrayListQueueTest.java | src/test/java/com/thealgorithms/datastructures/queues/GenericArrayListQueueTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class GenericArrayListQueueTest {
@Test
void testAdd() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
assertTrue(queue.add(10));
assertTrue(queue.add(20));
assertEquals(10, queue.peek()); // Ensure the first added element is at the front
}
@Test
void testPeek() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
assertNull(queue.peek(), "Peek should return null for an empty queue");
queue.add(10);
queue.add(20);
assertEquals(10, queue.peek(), "Peek should return the first element (10)");
queue.poll();
assertEquals(20, queue.peek(), "Peek should return the next element (20) after poll");
}
@Test
void testPoll() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
assertNull(queue.poll(), "Poll should return null for an empty queue");
queue.add(10);
queue.add(20);
assertEquals(10, queue.poll(), "Poll should return and remove the first element (10)");
assertEquals(20, queue.poll(), "Poll should return and remove the next element (20)");
assertNull(queue.poll(), "Poll should return null when queue is empty after removals");
}
@Test
void testIsEmpty() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
assertTrue(queue.isEmpty(), "Queue should initially be empty");
queue.add(30);
assertFalse(queue.isEmpty(), "Queue should not be empty after adding an element");
queue.poll();
assertTrue(queue.isEmpty(), "Queue should be empty after removing the only element");
}
@Test
void testClearQueueAndReuse() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
queue.add(5);
queue.add(10);
queue.poll();
queue.poll(); // Remove all elements
assertTrue(queue.isEmpty(), "Queue should be empty after all elements are removed");
assertNull(queue.peek(), "Peek should return null on an empty queue after clear");
assertTrue(queue.add(15), "Queue should be reusable after being emptied");
assertEquals(15, queue.peek(), "Newly added element should be accessible in the empty queue");
}
@Test
void testOrderMaintained() {
GenericArrayListQueue<String> queue = new GenericArrayListQueue<>();
queue.add("First");
queue.add("Second");
queue.add("Third");
assertEquals("First", queue.poll(), "Order should be maintained; expected 'First'");
assertEquals("Second", queue.poll(), "Order should be maintained; expected 'Second'");
assertEquals("Third", queue.poll(), "Order should be maintained; expected 'Third'");
}
@Test
void testVariousDataTypes() {
GenericArrayListQueue<Double> queue = new GenericArrayListQueue<>();
queue.add(1.1);
queue.add(2.2);
assertEquals(1.1, queue.peek(), "Queue should handle Double data type correctly");
assertEquals(1.1, queue.poll(), "Poll should return correct Double value");
assertEquals(2.2, queue.peek(), "Peek should show next Double value in the queue");
}
@Test
void testEmptyPollAndPeekBehavior() {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
assertNull(queue.peek(), "Peek on an empty queue should return null");
assertNull(queue.poll(), "Poll on an empty queue should return null");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java | src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java | package com.thealgorithms.datastructures.queues;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
class DequeTest {
@Test
void testAddFirst() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(10);
assertEquals(10, deque.peekFirst());
assertEquals(10, deque.peekLast());
assertEquals(1, deque.size());
}
@Test
void testAddLast() {
Deque<Integer> deque = new Deque<>();
deque.addLast(20);
assertEquals(20, deque.peekFirst());
assertEquals(20, deque.peekLast());
assertEquals(1, deque.size());
}
@Test
void testPollFirst() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(10);
deque.addLast(20);
assertEquals(10, deque.pollFirst());
assertEquals(20, deque.peekFirst());
assertEquals(1, deque.size());
}
@Test
void testPollLast() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(10);
deque.addLast(20);
assertEquals(20, deque.pollLast());
assertEquals(10, deque.peekLast());
assertEquals(1, deque.size());
}
@Test
void testIsEmpty() {
Deque<Integer> deque = new Deque<>();
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty());
deque.addFirst(10);
assertFalse(deque.isEmpty());
}
@Test
void testPeekFirstEmpty() {
Deque<Integer> deque = new Deque<>();
assertNull(deque.peekFirst());
}
@Test
void testPeekLastEmpty() {
Deque<Integer> deque = new Deque<>();
assertNull(deque.peekLast());
}
@Test
void testPollFirstEmpty() {
Deque<Integer> deque = new Deque<>();
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, deque::pollFirst);
}
@Test
void testPollLastEmpty() {
Deque<Integer> deque = new Deque<>();
org.junit.jupiter.api.Assertions.assertThrows(NoSuchElementException.class, deque::pollLast);
}
@Test
void testToString() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(10);
deque.addLast(20);
deque.addFirst(5);
assertEquals("Head -> 5 <-> 10 <-> 20 <- Tail", deque.toString());
}
@Test
void testAlternatingAddRemove() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(1);
deque.addLast(2);
deque.addFirst(0);
assertEquals(0, deque.pollFirst());
assertEquals(2, deque.pollLast());
assertEquals(1, deque.pollFirst());
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty());
}
@Test
void testSizeAfterOperations() {
Deque<Integer> deque = new Deque<>();
assertEquals(0, deque.size());
deque.addFirst(1);
deque.addLast(2);
deque.addFirst(3);
assertEquals(3, deque.size());
deque.pollFirst();
deque.pollLast();
assertEquals(1, deque.size());
}
@Test
void testNullValues() {
Deque<String> deque = new Deque<>();
deque.addFirst(null);
assertNull(deque.peekFirst());
assertNull(deque.pollFirst());
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty());
}
@Test
void testMultipleAddFirst() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(1);
deque.addFirst(2);
deque.addFirst(3);
assertEquals(3, deque.peekFirst(), "First element should be the last added to front");
assertEquals(1, deque.peekLast(), "Last element should be the first added to front");
assertEquals(3, deque.size(), "Size should reflect all additions");
}
@Test
void testMultipleAddLast() {
Deque<Integer> deque = new Deque<>();
deque.addLast(1);
deque.addLast(2);
deque.addLast(3);
assertEquals(1, deque.peekFirst(), "First element should be the first added to back");
assertEquals(3, deque.peekLast(), "Last element should be the last added to back");
assertEquals(3, deque.size(), "Size should reflect all additions");
}
@Test
void testSingleElementOperations() {
Deque<Integer> deque = new Deque<>();
deque.addFirst(1);
assertEquals(1, deque.peekFirst(), "Single element should be both first and last");
assertEquals(1, deque.peekLast(), "Single element should be both first and last");
assertEquals(1, deque.size());
assertEquals(1, deque.pollFirst(), "Should be able to poll single element from front");
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty(), "Deque should be empty after polling single element");
}
@Test
void testSingleElementPollLast() {
Deque<Integer> deque = new Deque<>();
deque.addLast(1);
assertEquals(1, deque.pollLast(), "Should be able to poll single element from back");
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty(), "Deque should be empty after polling single element");
}
@Test
void testMixedNullAndValues() {
Deque<String> deque = new Deque<>();
deque.addFirst("first");
deque.addLast(null);
deque.addFirst(null);
deque.addLast("last");
assertEquals(4, deque.size(), "Should handle mixed null and non-null values");
assertNull(deque.pollFirst(), "Should poll null from front");
assertEquals("first", deque.pollFirst(), "Should poll non-null value");
assertNull(deque.pollLast().equals("last") ? null : deque.peekLast(), "Should handle null correctly");
}
@Test
void testSymmetricOperations() {
Deque<Integer> deque = new Deque<>();
// Test that addFirst/pollFirst and addLast/pollLast are symmetric
deque.addFirst(1);
deque.addLast(2);
assertEquals(1, deque.pollFirst(), "addFirst/pollFirst should be symmetric");
assertEquals(2, deque.pollLast(), "addLast/pollLast should be symmetric");
org.junit.jupiter.api.Assertions.assertTrue(deque.isEmpty(), "Deque should be empty after symmetric operations");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/LWWElementSetTest.java | src/test/java/com/thealgorithms/datastructures/crdt/LWWElementSetTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import org.junit.jupiter.api.Test;
class LWWElementSetTest {
@Test
void testAddElement() {
LWWElementSet<String> set = new LWWElementSet<>();
set.add("A");
assertTrue(set.lookup("A"));
}
@Test
void testRemoveElement() {
LWWElementSet<String> set = new LWWElementSet<>();
set.add("A");
set.remove("A");
assertFalse(set.lookup("A"));
}
@Test
void testLookupWithoutAdding() {
LWWElementSet<String> set = new LWWElementSet<>();
assertFalse(set.lookup("A"));
}
@Test
void testLookupLaterTimestampsFalse() {
LWWElementSet<String> set = new LWWElementSet<>();
set.addSet.put("A", new Element<>("A", Instant.now()));
set.removeSet.put("A", new Element<>("A", Instant.now().plusSeconds(10)));
assertFalse(set.lookup("A"));
}
@Test
void testLookupEarlierTimestampsTrue() {
LWWElementSet<String> set = new LWWElementSet<>();
set.addSet.put("A", new Element<>("A", Instant.now()));
set.removeSet.put("A", new Element<>("A", Instant.now().minusSeconds(10)));
assertTrue(set.lookup("A"));
}
@Test
void testLookupWithConcurrentTimestamps() {
LWWElementSet<String> set = new LWWElementSet<>();
Instant now = Instant.now();
set.addSet.put("A", new Element<>("A", now));
set.removeSet.put("A", new Element<>("A", now));
assertFalse(set.lookup("A"));
}
@Test
void testMergeTwoSets() {
LWWElementSet<String> set1 = new LWWElementSet<>();
LWWElementSet<String> set2 = new LWWElementSet<>();
set1.add("A");
set2.add("B");
set2.remove("A");
set1.merge(set2);
assertFalse(set1.lookup("A"));
assertTrue(set1.lookup("B"));
}
@Test
void testMergeWithConflictingTimestamps() {
LWWElementSet<String> set1 = new LWWElementSet<>();
LWWElementSet<String> set2 = new LWWElementSet<>();
Instant now = Instant.now();
set1.addSet.put("A", new Element<>("A", now.minusSeconds(10)));
set2.addSet.put("A", new Element<>("A", now));
set1.merge(set2);
assertTrue(set1.lookup("A"));
}
@Test
void testRemoveOlderThanAdd() {
LWWElementSet<String> set = new LWWElementSet<>();
Instant now = Instant.now();
set.addSet.put("A", new Element<>("A", now));
set.removeSet.put("A", new Element<>("A", now.minusSeconds(10)));
assertTrue(set.lookup("A"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/PNCounterTest.java | src/test/java/com/thealgorithms/datastructures/crdt/PNCounterTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class PNCounterTest {
@Test
public void testIncrement() {
PNCounter counter = new PNCounter(0, 3);
counter.increment();
assertEquals(1, counter.value());
}
@Test
public void testDecrement() {
PNCounter counter = new PNCounter(0, 3);
counter.decrement();
assertEquals(-1, counter.value());
}
@Test
public void testIncrementAndDecrement() {
PNCounter counter = new PNCounter(0, 3);
counter.increment();
counter.increment();
counter.decrement();
assertEquals(1, counter.value());
}
@Test
public void testCompare() {
PNCounter counter1 = new PNCounter(0, 3);
counter1.increment();
PNCounter counter2 = new PNCounter(1, 3);
assertTrue(counter1.compare(counter2));
counter2.increment();
assertTrue(counter2.compare(counter1));
counter1.decrement();
assertFalse(counter1.compare(counter2));
}
@Test
public void testMerge() {
PNCounter counter1 = new PNCounter(0, 3);
counter1.increment();
counter1.increment();
PNCounter counter2 = new PNCounter(1, 3);
counter2.increment();
counter1.merge(counter2);
assertEquals(3, counter1.value());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java | src/test/java/com/thealgorithms/datastructures/crdt/ORSetTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Set;
import org.junit.jupiter.api.Test;
class ORSetTest {
@Test
void testContains() {
ORSet<String> orSet = new ORSet<>();
orSet.add("A");
assertTrue(orSet.contains("A"));
}
@Test
void testAdd() {
ORSet<String> orSet = new ORSet<>();
orSet.add("A");
assertTrue(orSet.contains("A"));
}
@Test
void testRemove() {
ORSet<String> orSet = new ORSet<>();
orSet.add("A");
orSet.add("A");
orSet.remove("A");
assertFalse(orSet.contains("A"));
}
@Test
void testElements() {
ORSet<String> orSet = new ORSet<>();
orSet.add("A");
orSet.add("B");
assertEquals(Set.of("A", "B"), orSet.elements());
}
@Test
void testCompareEqualSets() {
ORSet<String> orSet1 = new ORSet<>();
ORSet<String> orSet2 = new ORSet<>();
orSet1.add("A");
orSet2.add("A");
orSet2.add("B");
orSet2.add("C");
orSet2.remove("C");
orSet1.merge(orSet2);
orSet2.merge(orSet1);
orSet2.remove("B");
assertTrue(orSet1.compare(orSet2));
}
@Test
void testCompareDifferentSets() {
ORSet<String> orSet1 = new ORSet<>();
ORSet<String> orSet2 = new ORSet<>();
orSet1.add("A");
orSet2.add("B");
assertFalse(orSet1.compare(orSet2));
}
@Test
void testMerge() {
ORSet<String> orSet1 = new ORSet<>();
ORSet<String> orSet2 = new ORSet<>();
orSet1.add("A");
orSet1.add("A");
orSet1.add("B");
orSet1.remove("B");
orSet2.add("B");
orSet2.add("C");
orSet2.remove("C");
orSet1.merge(orSet2);
assertTrue(orSet1.contains("A"));
assertTrue(orSet1.contains("B"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/GCounterTest.java | src/test/java/com/thealgorithms/datastructures/crdt/GCounterTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class GCounterTest {
@Test
void increment() {
GCounter counter = new GCounter(0, 3);
counter.increment();
counter.increment();
counter.increment();
assertEquals(3, counter.value());
}
@Test
void merge() {
GCounter counter1 = new GCounter(0, 3);
counter1.increment();
GCounter counter2 = new GCounter(1, 3);
counter2.increment();
counter2.increment();
GCounter counter3 = new GCounter(2, 3);
counter3.increment();
counter3.increment();
counter3.increment();
counter1.merge(counter2);
counter1.merge(counter3);
counter2.merge(counter1);
counter3.merge(counter2);
assertEquals(6, counter1.value());
assertEquals(6, counter2.value());
assertEquals(6, counter3.value());
}
@Test
void compare() {
GCounter counter1 = new GCounter(0, 5);
GCounter counter2 = new GCounter(3, 5);
counter1.increment();
counter1.increment();
counter2.merge(counter1);
counter2.increment();
counter2.increment();
assertTrue(counter1.compare(counter2));
counter1.increment();
counter2.increment();
counter2.merge(counter1);
assertTrue(counter1.compare(counter2));
counter1.increment();
assertFalse(counter1.compare(counter2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/GSetTest.java | src/test/java/com/thealgorithms/datastructures/crdt/GSetTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class GSetTest {
@Test
void testAddElement() {
GSet<String> gSet = new GSet<>();
gSet.addElement("apple");
gSet.addElement("orange");
assertTrue(gSet.lookup("apple"));
assertTrue(gSet.lookup("orange"));
assertFalse(gSet.lookup("banana"));
}
@Test
void testLookup() {
GSet<Integer> gSet = new GSet<>();
gSet.addElement(1);
gSet.addElement(2);
assertTrue(gSet.lookup(1));
assertTrue(gSet.lookup(2));
assertFalse(gSet.lookup(3));
}
@Test
void testCompare() {
GSet<String> gSet1 = new GSet<>();
GSet<String> gSet2 = new GSet<>();
gSet1.addElement("apple");
gSet1.addElement("orange");
gSet2.addElement("orange");
assertFalse(gSet1.compare(gSet2));
gSet2.addElement("apple");
assertTrue(gSet1.compare(gSet2));
gSet2.addElement("banana");
assertTrue(gSet1.compare(gSet2));
}
@Test
void testMerge() {
GSet<String> gSet1 = new GSet<>();
GSet<String> gSet2 = new GSet<>();
gSet1.addElement("apple");
gSet1.addElement("orange");
gSet2.addElement("orange");
gSet2.addElement("banana");
GSet<String> mergedSet = new GSet<>();
mergedSet.merge(gSet1);
mergedSet.merge(gSet2);
assertTrue(mergedSet.lookup("apple"));
assertTrue(mergedSet.lookup("orange"));
assertTrue(mergedSet.lookup("banana"));
assertFalse(mergedSet.lookup("grape"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/crdt/TwoPSetTest.java | src/test/java/com/thealgorithms/datastructures/crdt/TwoPSetTest.java | package com.thealgorithms.datastructures.crdt;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class TwoPSetTest {
private TwoPSet<String> set;
@BeforeEach
void setUp() {
set = new TwoPSet<>();
}
@Test
void testLookup() {
set.add("A");
assertTrue(set.lookup("A"));
assertFalse(set.lookup("B"));
set.remove("A");
assertFalse(set.lookup("A"));
}
@Test
void testAdd() {
set.add("A");
assertTrue(set.lookup("A"));
}
@Test
void testRemove() {
set.add("A");
set.remove("A");
assertFalse(set.lookup("A"));
}
@Test
void testCompare() {
TwoPSet<String> set1 = new TwoPSet<>();
set1.add("A");
set1.add("B");
TwoPSet<String> set2 = new TwoPSet<>();
set2.add("A");
assertFalse(set1.compare(set2));
set2.add("B");
assertTrue(set1.compare(set2));
set1.remove("A");
assertFalse(set1.compare(set2));
set2.remove("A");
assertTrue(set1.compare(set2));
}
@Test
void testMerge() {
TwoPSet<String> set1 = new TwoPSet<>();
set1.add("A");
set1.add("B");
TwoPSet<String> set2 = new TwoPSet<>();
set2.add("B");
set2.add("C");
TwoPSet<String> mergedSet = set1.merge(set2);
assertTrue(mergedSet.lookup("A"));
assertTrue(mergedSet.lookup("B"));
assertTrue(mergedSet.lookup("C"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java | src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java | package com.thealgorithms.datastructures.buffers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class CircularBufferTest {
@Test
void testInitialization() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(5);
assertTrue(buffer.isEmpty());
assertEquals(Boolean.FALSE, buffer.isFull());
}
@Test
void testPutAndGet() {
CircularBuffer<String> buffer = new CircularBuffer<>(3);
assertTrue(buffer.put("A"));
assertEquals(Boolean.FALSE, buffer.isEmpty());
assertEquals(Boolean.FALSE, buffer.isFull());
buffer.put("B");
buffer.put("C");
assertTrue(buffer.isFull());
assertEquals("A", buffer.get());
assertEquals("B", buffer.get());
assertEquals("C", buffer.get());
assertTrue(buffer.isEmpty());
}
@Test
void testOverwrite() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(3);
buffer.put(1);
buffer.put(2);
buffer.put(3);
assertEquals(Boolean.FALSE, buffer.put(4)); // This should overwrite 1
assertEquals(2, buffer.get());
assertEquals(3, buffer.get());
assertEquals(4, buffer.get());
assertNull(buffer.get());
}
@Test
void testEmptyBuffer() {
CircularBuffer<Double> buffer = new CircularBuffer<>(2);
assertNull(buffer.get());
}
@Test
void testFullBuffer() {
CircularBuffer<Character> buffer = new CircularBuffer<>(2);
buffer.put('A');
buffer.put('B');
assertTrue(buffer.isFull());
assertEquals(Boolean.FALSE, buffer.put('C')); // This should overwrite 'A'
assertEquals('B', buffer.get());
assertEquals('C', buffer.get());
}
@Test
void testIllegalArguments() {
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> new CircularBuffer<>(0));
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> new CircularBuffer<>(-1));
CircularBuffer<String> buffer = new CircularBuffer<>(1);
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> buffer.put(null));
}
@Test
void testLargeBuffer() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(1000);
for (int i = 0; i < 1000; i++) {
buffer.put(i);
}
assertTrue(buffer.isFull());
buffer.put(1000); // This should overwrite 0
assertEquals(1, buffer.get());
}
@Test
void testPutAfterGet() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(2);
buffer.put(10);
buffer.put(20);
assertEquals(10, buffer.get());
buffer.put(30);
assertEquals(20, buffer.get());
assertEquals(30, buffer.get());
assertNull(buffer.get());
}
@Test
void testMultipleWrapArounds() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(3);
for (int i = 1; i <= 6; i++) {
buffer.put(i);
buffer.get(); // add and immediately remove
}
assertTrue(buffer.isEmpty());
assertNull(buffer.get());
}
@Test
void testOverwriteMultipleTimes() {
CircularBuffer<String> buffer = new CircularBuffer<>(2);
buffer.put("X");
buffer.put("Y");
buffer.put("Z"); // overwrites "X"
buffer.put("W"); // overwrites "Y"
assertEquals("Z", buffer.get());
assertEquals("W", buffer.get());
assertNull(buffer.get());
}
@Test
void testIsEmptyAndIsFullTransitions() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(2);
assertTrue(buffer.isEmpty());
org.junit.jupiter.api.Assertions.assertFalse(buffer.isFull());
buffer.put(1);
org.junit.jupiter.api.Assertions.assertFalse(buffer.isEmpty());
org.junit.jupiter.api.Assertions.assertFalse(buffer.isFull());
buffer.put(2);
assertTrue(buffer.isFull());
buffer.get();
org.junit.jupiter.api.Assertions.assertFalse(buffer.isFull());
buffer.get();
assertTrue(buffer.isEmpty());
}
@Test
void testInterleavedPutAndGet() {
CircularBuffer<String> buffer = new CircularBuffer<>(3);
buffer.put("A");
buffer.put("B");
assertEquals("A", buffer.get());
buffer.put("C");
assertEquals("B", buffer.get());
assertEquals("C", buffer.get());
assertNull(buffer.get());
}
@Test
void testRepeatedNullInsertionThrows() {
CircularBuffer<Object> buffer = new CircularBuffer<>(5);
for (int i = 0; i < 3; i++) {
int finalI = i;
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> buffer.put(null), "Iteration: " + finalI);
}
}
@Test
void testFillThenEmptyThenReuseBuffer() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(3);
buffer.put(1);
buffer.put(2);
buffer.put(3);
assertTrue(buffer.isFull());
assertEquals(1, buffer.get());
assertEquals(2, buffer.get());
assertEquals(3, buffer.get());
assertTrue(buffer.isEmpty());
buffer.put(4);
buffer.put(5);
assertEquals(4, buffer.get());
assertEquals(5, buffer.get());
assertTrue(buffer.isEmpty());
}
@Test
void testPutReturnsTrueOnlyIfPreviouslyEmpty() {
CircularBuffer<String> buffer = new CircularBuffer<>(2);
assertTrue(buffer.put("one")); // was empty
org.junit.jupiter.api.Assertions.assertFalse(buffer.put("two")); // not empty
org.junit.jupiter.api.Assertions.assertFalse(buffer.put("three")); // overwrite
}
@Test
void testOverwriteAndGetAllElementsCorrectly() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(3);
buffer.put(1);
buffer.put(2);
buffer.put(3);
buffer.put(4); // Overwrites 1
buffer.put(5); // Overwrites 2
assertEquals(3, buffer.get());
assertEquals(4, buffer.get());
assertEquals(5, buffer.get());
assertNull(buffer.get());
}
@Test
void testBufferWithOneElementCapacity() {
CircularBuffer<String> buffer = new CircularBuffer<>(1);
assertTrue(buffer.put("first"));
assertEquals("first", buffer.get());
assertNull(buffer.get());
assertTrue(buffer.put("second"));
assertEquals("second", buffer.get());
}
@Test
void testPointerWraparoundWithExactMultipleOfCapacity() {
CircularBuffer<Integer> buffer = new CircularBuffer<>(3);
for (int i = 0; i < 6; i++) {
buffer.put(i);
buffer.get(); // keep buffer size at 0
}
assertTrue(buffer.isEmpty());
assertNull(buffer.get());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/BellmanFordTest.java | src/test/java/com/thealgorithms/datastructures/graphs/BellmanFordTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the BellmanFord algorithm implementation.
* Tests cover various graph scenarios including:
* - Simple weighted graphs
* - Graphs with negative weights
* - Single vertex graphs
* - Disconnected graphs
* - Linear path graphs
*/
class BellmanFordTest {
@Test
void testSimpleGraph() {
// Create a simple graph with 5 vertices and 8 edges
// Graph visualization:
// 1
// /|\
// 6 | 7
// / | \
// 0 5 2
// \ | /
// 8 | -2
// \|/
// 4---3
// 9
BellmanFord bellmanFord = new BellmanFord(5, 8);
bellmanFord.addEdge(0, 1, 6);
bellmanFord.addEdge(0, 4, 8);
bellmanFord.addEdge(1, 2, 7);
bellmanFord.addEdge(1, 4, 5);
bellmanFord.addEdge(2, 3, -2);
bellmanFord.addEdge(2, 4, -3);
bellmanFord.addEdge(3, 4, 9);
bellmanFord.addEdge(4, 3, 7);
// Verify edge array creation
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(8, bellmanFord.getEdgeArray().length);
}
@Test
void testGraphWithNegativeWeights() {
// Graph with negative edge weights (but no negative cycle)
BellmanFord bellmanFord = new BellmanFord(4, 5);
bellmanFord.addEdge(0, 1, 4);
bellmanFord.addEdge(0, 2, 5);
bellmanFord.addEdge(1, 2, -3);
bellmanFord.addEdge(2, 3, 4);
bellmanFord.addEdge(1, 3, 6);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(5, bellmanFord.getEdgeArray().length);
}
@Test
void testSingleVertexGraph() {
// Graph with single vertex and no edges
BellmanFord bellmanFord = new BellmanFord(1, 0);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(0, bellmanFord.getEdgeArray().length);
}
@Test
void testLinearGraph() {
// Linear graph: 0 -> 1 -> 2 -> 3
BellmanFord bellmanFord = new BellmanFord(4, 3);
bellmanFord.addEdge(0, 1, 2);
bellmanFord.addEdge(1, 2, 3);
bellmanFord.addEdge(2, 3, 4);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(3, bellmanFord.getEdgeArray().length);
}
@Test
void testEdgeAddition() {
BellmanFord bellmanFord = new BellmanFord(3, 3);
bellmanFord.addEdge(0, 1, 5);
bellmanFord.addEdge(1, 2, 3);
bellmanFord.addEdge(0, 2, 10);
// Verify all edges were added
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(3, bellmanFord.getEdgeArray().length);
}
@Test
void testGraphWithZeroWeightEdges() {
// Graph with zero weight edges
BellmanFord bellmanFord = new BellmanFord(3, 3);
bellmanFord.addEdge(0, 1, 0);
bellmanFord.addEdge(1, 2, 0);
bellmanFord.addEdge(0, 2, 1);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(3, bellmanFord.getEdgeArray().length);
}
@Test
void testLargerGraph() {
// Larger graph with 6 vertices
BellmanFord bellmanFord = new BellmanFord(6, 9);
bellmanFord.addEdge(0, 1, 5);
bellmanFord.addEdge(0, 2, 3);
bellmanFord.addEdge(1, 3, 6);
bellmanFord.addEdge(1, 2, 2);
bellmanFord.addEdge(2, 4, 4);
bellmanFord.addEdge(2, 5, 2);
bellmanFord.addEdge(2, 3, 7);
bellmanFord.addEdge(3, 4, -1);
bellmanFord.addEdge(4, 5, -2);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(9, bellmanFord.getEdgeArray().length);
}
@Test
void testVertexAndEdgeCount() {
BellmanFord bellmanFord = new BellmanFord(10, 15);
assertEquals(10, bellmanFord.vertex);
assertEquals(15, bellmanFord.edge);
}
@Test
void testMultipleEdgesBetweenSameVertices() {
// Graph allowing multiple edges between same vertices
BellmanFord bellmanFord = new BellmanFord(2, 3);
bellmanFord.addEdge(0, 1, 5);
bellmanFord.addEdge(0, 1, 3);
bellmanFord.addEdge(1, 0, 2);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(3, bellmanFord.getEdgeArray().length);
}
@Test
void testCompleteGraph() {
// Complete graph with 4 vertices (6 edges for undirected equivalent)
BellmanFord bellmanFord = new BellmanFord(4, 6);
bellmanFord.addEdge(0, 1, 1);
bellmanFord.addEdge(0, 2, 2);
bellmanFord.addEdge(0, 3, 3);
bellmanFord.addEdge(1, 2, 4);
bellmanFord.addEdge(1, 3, 5);
bellmanFord.addEdge(2, 3, 6);
assertNotNull(bellmanFord.getEdgeArray());
assertEquals(6, bellmanFord.getEdgeArray().length);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/PrimMSTTest.java | src/test/java/com/thealgorithms/datastructures/graphs/PrimMSTTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class PrimMSTTest {
private final PrimMST primMST = new PrimMST();
@Test
public void testSimpleGraph() {
// Test graph with 5 nodes and weighted edges
int[][] graph = {{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0}};
int[] expectedParent = {-1, 0, 1, 0, 1};
int[] actualParent = primMST.primMST(graph);
assertArrayEquals(expectedParent, actualParent);
}
@Test
public void testDisconnectedGraph() {
// Test case with a disconnected graph (no valid MST)
int[][] graph = {{0, 1, 0, 0, 0}, {1, 0, 2, 0, 0}, {0, 2, 0, 3, 0}, {0, 0, 3, 0, 4}, {0, 0, 0, 4, 0}};
int[] expectedParent = {-1, 0, 1, 2, 3}; // Expected MST parent array
int[] actualParent = primMST.primMST(graph);
assertArrayEquals(expectedParent, actualParent);
}
@Test
public void testAllEqualWeightsGraph() {
// Test case where all edges have equal weight
int[][] graph = {{0, 1, 1, 1, 1}, {1, 0, 1, 1, 1}, {1, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {1, 1, 1, 1, 0}};
int[] expectedParent = {-1, 0, 0, 0, 0}; // Expected MST parent array (any valid spanning tree)
int[] actualParent = primMST.primMST(graph);
assertArrayEquals(expectedParent, actualParent);
}
@Test
public void testSparseGraph() {
// Test case with a sparse graph (few edges)
int[][] graph = {{0, 1, 0, 0, 0}, {1, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 0, 1, 0, 1}, {0, 0, 0, 1, 0}};
int[] expectedParent = {-1, 0, 1, 2, 3}; // Expected MST parent array
int[] actualParent = primMST.primMST(graph);
assertArrayEquals(expectedParent, actualParent);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link JohnsonsAlgorithm} class. This class
* contains test cases to verify the correct implementation of
* various methods used in Johnson's Algorithm such as shortest path
* calculations, graph reweighting, and more.
*/
class JohnsonsAlgorithmTest {
// Constant representing infinity
private static final double INF = Double.POSITIVE_INFINITY;
/**
* Tests the Johnson's Algorithm with a simple graph without negative edges.
* Verifies that the algorithm returns the correct shortest path distances.
*/
@Test
void testSimpleGraph() {
double[][] graph = {{0, 4, INF, INF}, {INF, 0, 1, INF}, {INF, INF, 0, 2}, {INF, INF, INF, 0}};
double[][] result = JohnsonsAlgorithm.johnsonAlgorithm(graph);
double[][] expected = {{0, 4, 5, 7}, {INF, 0, 1, 3}, {INF, INF, 0, 2}, {INF, INF, INF, 0}};
assertArrayEquals(expected, result);
}
/**
* Tests Johnson's Algorithm on a graph with negative edges but no negative weight cycles.
*/
@Test
void testGraphWithNegativeEdges() {
double[][] graph = {{0, -1, 4}, {INF, 0, 3}, {INF, INF, 0}};
double[][] result = JohnsonsAlgorithm.johnsonAlgorithm(graph);
double[][] expected = {{0, INF, 4}, {INF, 0, 3}, {INF, INF, 0}};
assertArrayEquals(expected, result);
}
/**
* Tests Johnson's Algorithm on a graph with a negative weight cycle.
*/
@Test
void testNegativeWeightCycle() {
double[][] graph = {{0, 1, INF}, {INF, 0, -1}, {-1, INF, 0}};
assertThrows(IllegalArgumentException.class, () -> JohnsonsAlgorithm.johnsonAlgorithm(graph));
}
/**
* Tests Dijkstra's algorithm on a small graph as part of Johnson's Algorithm.
*/
@Test
void testDijkstra() {
double[][] graph = {{0, 1, 2}, {INF, 0, 3}, {INF, INF, 0}};
double[] modifiedWeights = {0, 0, 0};
double[] result = JohnsonsAlgorithm.dijkstra(graph, 0, modifiedWeights);
double[] expected = {0, 1, 2};
assertArrayEquals(expected, result);
}
/**
* Tests the conversion of an adjacency matrix to an edge list.
*/
@Test
void testEdgeListConversion() {
double[][] graph = {{0, 5, INF}, {INF, 0, 2}, {INF, INF, 0}};
double[][] edges = JohnsonsAlgorithm.convertToEdgeList(graph);
double[][] expected = {{0, 1, 5}, {1, 2, 2}};
assertArrayEquals(expected, edges);
}
/**
* Tests the reweighting of a graph.
*/
@Test
void testReweightGraph() {
double[][] graph = {{0, 2, 9}, {INF, 0, 1}, {INF, INF, 0}};
double[] modifiedWeights = {1, 2, 3};
double[][] reweightedGraph = JohnsonsAlgorithm.reweightGraph(graph, modifiedWeights);
double[][] expected = {{0, 1, 7}, {INF, 0, 0}, {INF, INF, 0}};
assertArrayEquals(expected, reweightedGraph);
}
/**
* Tests the minDistance method used in Dijkstra's algorithm.
*/
@Test
void testMinDistance() {
double[] dist = {INF, 3, 1, INF};
boolean[] visited = {false, false, false, false};
int minIndex = JohnsonsAlgorithm.minDistance(dist, visited);
assertEquals(2, minIndex);
}
/**
* Tests Johnson's Algorithm on a graph where all vertices are disconnected.
*/
@Test
void testDisconnectedGraph() {
double[][] graph = {{0, INF, INF}, {INF, 0, INF}, {INF, INF, 0}};
double[][] result = JohnsonsAlgorithm.johnsonAlgorithm(graph);
double[][] expected = {{0, INF, INF}, {INF, 0, INF}, {INF, INF, 0}};
assertArrayEquals(expected, result);
}
/**
* Tests Johnson's Algorithm on a fully connected graph.
*/
@Test
void testFullyConnectedGraph() {
double[][] graph = {{0, 1, 2}, {1, 0, 1}, {2, 1, 0}};
double[][] result = JohnsonsAlgorithm.johnsonAlgorithm(graph);
double[][] expected = {{0, 1, 2}, {1, 0, 1}, {2, 1, 0}};
assertArrayEquals(expected, result);
}
/**
* Tests Dijkstra's algorithm on a graph with multiple shortest paths.
*/
@Test
void testDijkstraMultipleShortestPaths() {
double[][] graph = {{0, 1, 2, INF}, {INF, 0, INF, 1}, {INF, INF, 0, 1}, {INF, INF, INF, 0}};
double[] modifiedWeights = {0, 0, 0, 0};
double[] result = JohnsonsAlgorithm.dijkstra(graph, 0, modifiedWeights);
double[] expected = {0, 1, 2, 2};
assertArrayEquals(expected, result);
}
/**
* Tests Johnson's Algorithm with a graph where all edge weights are zero.
*/
@Test
void testGraphWithZeroWeights() {
double[][] graph = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
double[][] result = JohnsonsAlgorithm.johnsonAlgorithm(graph);
double[][] expected = {{0, INF, INF}, {INF, 0, INF}, {INF, INF, 0}};
assertArrayEquals(expected, result);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
class KahnsAlgorithmTest {
@Test
void testBasicGraph() {
// Test case with a basic directed acyclic graph (DAG)
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "b");
graph.addEdge("c", "a");
graph.addEdge("a", "d");
graph.addEdge("b", "d");
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
ArrayList<String> result = topSort.topSortOrder();
String[] expectedOrder = {"c", "a", "b", "d"};
assertArrayEquals(expectedOrder, result.toArray());
}
@Test
void testGraphWithMultipleSources() {
// Test case where graph has multiple independent sources
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "c");
graph.addEdge("b", "c");
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
ArrayList<String> result = topSort.topSortOrder();
String[] expectedOrder = {"a", "b", "c"};
assertArrayEquals(expectedOrder, result.toArray());
}
@Test
void testDisconnectedGraph() {
// Test case for disconnected graph
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "b");
graph.addEdge("c", "d");
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
ArrayList<String> result = topSort.topSortOrder();
String[] expectedOrder = {"a", "c", "b", "d"};
assertArrayEquals(expectedOrder, result.toArray());
}
@Test
void testGraphWithCycle() {
// Test case for a graph with a cycle - topological sorting is not possible
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "b");
graph.addEdge("b", "c");
graph.addEdge("c", "a");
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
assertThrows(IllegalStateException.class, () -> topSort.topSortOrder());
}
@Test
void testSingleNodeGraph() {
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "a"); // self-loop
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
assertThrows(IllegalStateException.class, () -> topSort.topSortOrder());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DijkstraAlgorithmTest {
private DijkstraAlgorithm dijkstraAlgorithm;
private int[][] graph;
@BeforeEach
void setUp() {
graph = new int[][] {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
};
dijkstraAlgorithm = new DijkstraAlgorithm(graph.length);
}
@Test
void testRunAlgorithm() {
int[] expectedDistances = {0, 4, 12, 19, 21, 11, 9, 8, 14};
assertArrayEquals(expectedDistances, dijkstraAlgorithm.run(graph, 0));
}
@Test
void testGraphWithDisconnectedNodes() {
int[][] disconnectedGraph = {
{0, 3, 0, 0}, {3, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0} // Node 3 is disconnected
};
DijkstraAlgorithm dijkstraDisconnected = new DijkstraAlgorithm(disconnectedGraph.length);
// Testing from vertex 0
int[] expectedDistances = {0, 3, 4, Integer.MAX_VALUE}; // Node 3 is unreachable
assertArrayEquals(expectedDistances, dijkstraDisconnected.run(disconnectedGraph, 0));
}
@Test
void testSingleVertexGraph() {
int[][] singleVertexGraph = {{0}};
DijkstraAlgorithm dijkstraSingleVertex = new DijkstraAlgorithm(1);
int[] expectedDistances = {0}; // The only vertex's distance to itself is 0
assertArrayEquals(expectedDistances, dijkstraSingleVertex.run(singleVertexGraph, 0));
}
@Test
void testInvalidSourceVertex() {
assertThrows(IllegalArgumentException.class, () -> dijkstraAlgorithm.run(graph, -1));
assertThrows(IllegalArgumentException.class, () -> dijkstraAlgorithm.run(graph, graph.length));
}
@Test
void testLinearGraph() {
// Linear graph: 0 - 1 - 2 - 3
// with weights: 2 3 4
int[][] linearGraph = {{0, 2, 0, 0}, {2, 0, 3, 0}, {0, 3, 0, 4}, {0, 0, 4, 0}};
DijkstraAlgorithm dijkstraLinear = new DijkstraAlgorithm(4);
int[] distances = dijkstraLinear.run(linearGraph, 0);
assertArrayEquals(new int[] {0, 2, 5, 9}, distances);
}
@Test
void testStarTopology() {
// Star graph: center node 0 connected to all others
// 1(2)
// |
// 3(4)-0-2(3)
// |
// 4(5)
int[][] starGraph = {{0, 2, 3, 4, 5}, {2, 0, 0, 0, 0}, {3, 0, 0, 0, 0}, {4, 0, 0, 0, 0}, {5, 0, 0, 0, 0}};
DijkstraAlgorithm dijkstraStar = new DijkstraAlgorithm(5);
int[] distances = dijkstraStar.run(starGraph, 0);
assertArrayEquals(new int[] {0, 2, 3, 4, 5}, distances);
}
@Test
void testCompleteGraphK4() {
// Complete graph K4 with varying weights
int[][] completeGraph = {{0, 1, 2, 3}, {1, 0, 4, 5}, {2, 4, 0, 6}, {3, 5, 6, 0}};
DijkstraAlgorithm dijkstraComplete = new DijkstraAlgorithm(4);
int[] distances = dijkstraComplete.run(completeGraph, 0);
// Direct paths from 0 are shortest
assertArrayEquals(new int[] {0, 1, 2, 3}, distances);
}
@Test
void testDifferentSourceVertex() {
// Test running from different source vertices
int[][] simpleGraph = {{0, 5, 0, 0}, {5, 0, 3, 0}, {0, 3, 0, 2}, {0, 0, 2, 0}};
DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(4);
// From vertex 0
int[] distFrom0 = dijkstra.run(simpleGraph, 0);
assertArrayEquals(new int[] {0, 5, 8, 10}, distFrom0);
// From vertex 2
int[] distFrom2 = dijkstra.run(simpleGraph, 2);
assertArrayEquals(new int[] {8, 3, 0, 2}, distFrom2);
// From vertex 3
int[] distFrom3 = dijkstra.run(simpleGraph, 3);
assertArrayEquals(new int[] {10, 5, 2, 0}, distFrom3);
}
@Test
void testUnitWeightGraph() {
// Graph with all unit weights (like BFS distance)
int[][] unitGraph = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}};
DijkstraAlgorithm dijkstraUnit = new DijkstraAlgorithm(4);
int[] distances = dijkstraUnit.run(unitGraph, 0);
assertArrayEquals(new int[] {0, 1, 1, 2}, distances);
}
@Test
void testTwoVertexGraph() {
int[][] twoVertexGraph = {{0, 7}, {7, 0}};
DijkstraAlgorithm dijkstraTwo = new DijkstraAlgorithm(2);
int[] distances = dijkstraTwo.run(twoVertexGraph, 0);
assertArrayEquals(new int[] {0, 7}, distances);
}
@Test
void testShortcutPath() {
// Graph where direct path is longer than indirect path
// 0 --(10)--> 2
// 0 --(1)--> 1 --(2)--> 2
int[][] shortcutGraph = {{0, 1, 10}, {1, 0, 2}, {10, 2, 0}};
DijkstraAlgorithm dijkstraShortcut = new DijkstraAlgorithm(3);
int[] distances = dijkstraShortcut.run(shortcutGraph, 0);
// The shortest path to vertex 2 should be 3 (via vertex 1), not 10 (direct)
assertArrayEquals(new int[] {0, 1, 3}, distances);
}
@Test
void testSourceToSourceDistanceIsZero() {
// Verify distance from source to itself is always 0
int[] distances = dijkstraAlgorithm.run(graph, 0);
assertEquals(0, distances[0]);
distances = dijkstraAlgorithm.run(graph, 5);
assertEquals(0, distances[5]);
}
@Test
void testLargeWeights() {
// Graph with large weights
int[][] largeWeightGraph = {{0, 1000, 0}, {1000, 0, 2000}, {0, 2000, 0}};
DijkstraAlgorithm dijkstraLarge = new DijkstraAlgorithm(3);
int[] distances = dijkstraLarge.run(largeWeightGraph, 0);
assertArrayEquals(new int[] {0, 1000, 3000}, distances);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java | src/test/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFSTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
public class BipartiteGraphDFSTest {
// Helper method to create an adjacency list from edges
private ArrayList<ArrayList<Integer>> createAdjacencyList(int numVertices, int[][] edges) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numVertices; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
int vertexU = edge[0];
int vertexV = edge[1];
adj.get(vertexU).add(vertexV);
adj.get(vertexV).add(vertexU);
}
return adj;
}
@Test
public void testBipartiteGraphEvenCycle() {
int numVertices = 4;
int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 0}}; // Even cycle
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertTrue(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should be bipartite (even cycle)");
}
@Test
public void testBipartiteGraphOddCycle() {
int numVertices = 5;
int[][] edges = {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 4}}; // Odd cycle
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertFalse(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should not be bipartite (odd cycle)");
}
@Test
public void testBipartiteGraphDisconnected() {
int numVertices = 6;
int[][] edges = {{0, 1}, {2, 3}, {4, 5}}; // Disconnected bipartite graphs
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertTrue(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should be bipartite (disconnected)");
}
@Test
public void testBipartiteGraphSingleVertex() {
int numVertices = 1;
int[][] edges = {}; // Single vertex, no edges
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertTrue(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should be bipartite (single vertex)");
}
@Test
public void testBipartiteGraphCompleteBipartite() {
int numVertices = 4;
int[][] edges = {{0, 2}, {0, 3}, {1, 2}, {1, 3}}; // K2,2 (Complete bipartite graph)
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertTrue(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should be bipartite (complete bipartite)");
}
@Test
public void testBipartiteGraphNonBipartite() {
int numVertices = 3;
int[][] edges = {{0, 1}, {1, 2}, {2, 0}}; // Triangle (odd cycle)
ArrayList<ArrayList<Integer>> adj = createAdjacencyList(numVertices, edges);
assertFalse(BipartiteGraphDFS.isBipartite(numVertices, adj), "Graph should not be bipartite (triangle)");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class TarjansAlgorithmTest {
private final TarjansAlgorithm tarjansAlgo = new TarjansAlgorithm();
@Test
public void testFindStronglyConnectedComponents() {
int v = 5;
var graph = new ArrayList<List<Integer>>();
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(1);
graph.get(1).add(2);
graph.get(2).add(0);
graph.get(1).add(3);
graph.get(3).add(4);
var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph);
/*
Expected result:
0, 1, 2
3
4
*/
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(List.of(4));
expectedResult.add(List.of(3));
expectedResult.add(Arrays.asList(2, 1, 0));
assertEquals(expectedResult, actualResult);
}
@Test
public void testFindStronglyConnectedComponentsWithSingleNodes() {
// Create a graph where each node is its own SCC
int n = 8;
var adjList = new ArrayList<List<Integer>>(n);
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
adjList.get(0).add(1);
adjList.get(1).add(2);
adjList.get(2).add(3);
adjList.get(3).add(4);
adjList.get(4).add(5);
adjList.get(5).add(6);
adjList.get(6).add(7);
adjList.get(7).add(0);
List<List<Integer>> actualResult = tarjansAlgo.stronglyConnectedComponents(n, adjList);
List<List<Integer>> expectedResult = new ArrayList<>();
/*
Expected result:
7, 6, 5, 4, 3, 2, 1, 0
*/
expectedResult.add(Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0));
assertEquals(expectedResult, actualResult);
}
@Test
public void testGraphWithMultipleSCCs() {
int v = 6;
var graph = new ArrayList<List<Integer>>();
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(1);
graph.get(1).add(2);
graph.get(2).add(0);
graph.get(3).add(4);
graph.get(4).add(5);
graph.get(5).add(3);
var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph);
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(Arrays.asList(2, 1, 0)); // SCC containing 0, 1, 2
expectedResult.add(Arrays.asList(5, 4, 3)); // SCC containing 3, 4, 5
assertEquals(expectedResult, actualResult);
}
@Test
public void testDisconnectedGraph() {
int v = 7;
var graph = new ArrayList<List<Integer>>();
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(1);
graph.get(1).add(0);
graph.get(2).add(3);
graph.get(3).add(4);
graph.get(4).add(2);
var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph);
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(Arrays.asList(1, 0)); // SCC containing 0, 1
expectedResult.add(Arrays.asList(4, 3, 2)); // SCC containing 2, 3, 4
expectedResult.add(List.of(5)); // SCC containing 5
expectedResult.add(List.of(6)); // SCC containing 6
assertEquals(expectedResult, actualResult);
}
@Test
public void testSingleNodeGraph() {
int v = 1;
var graph = new ArrayList<List<Integer>>();
graph.add(new ArrayList<>());
var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph);
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(List.of(0)); // SCC with a single node
assertEquals(expectedResult, actualResult);
}
@Test
public void testEmptyGraph() {
int v = 0;
var graph = new ArrayList<List<Integer>>();
var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph);
List<List<Integer>> expectedResult = new ArrayList<>(); // No SCCs in an empty graph
assertEquals(expectedResult, actualResult);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java | src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class KosarajuTest {
private final Kosaraju kosaraju = new Kosaraju();
@Test
public void testFindStronglyConnectedComponents() {
// Create a graph using adjacency list
int n = 8;
List<List<Integer>> adjList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
adjList.get(0).add(1);
adjList.get(1).add(2);
adjList.get(2).add(0);
adjList.get(2).add(3);
adjList.get(3).add(4);
adjList.get(4).add(5);
adjList.get(4).add(7);
adjList.get(5).add(6);
adjList.get(6).add(4);
adjList.get(6).add(7);
List<List<Integer>> actualResult = kosaraju.kosaraju(n, adjList);
List<List<Integer>> expectedResult = new ArrayList<>();
/*
Expected result:
{0, 1, 2}
{3}
{5, 4, 6}
{7}
*/
expectedResult.add(Arrays.asList(1, 2, 0));
expectedResult.add(List.of(3));
expectedResult.add(Arrays.asList(5, 6, 4));
expectedResult.add(List.of(7));
assertEquals(expectedResult, actualResult);
}
@Test
public void testFindSingleNodeSCC() {
// Create a simple graph using adjacency list
int n = 8;
List<List<Integer>> adjList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
adjList.get(0).add(1);
adjList.get(1).add(2);
adjList.get(2).add(3);
adjList.get(3).add(4);
adjList.get(4).add(5);
adjList.get(5).add(6);
adjList.get(6).add(7);
adjList.get(7).add(0);
List<List<Integer>> actualResult = kosaraju.kosaraju(n, adjList);
List<List<Integer>> expectedResult = new ArrayList<>();
/*
Expected result:
{0, 1, 2, 3, 4, 5, 6, 7}
*/
expectedResult.add(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 0));
assertEquals(expectedResult, actualResult);
}
@Test
public void testDisconnectedGraph() {
// Create a disconnected graph (two separate components)
int n = 5;
List<List<Integer>> adjList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
// Add edges for first component
adjList.get(0).add(1);
adjList.get(1).add(2);
adjList.get(2).add(0);
// Add edges for second component
adjList.get(3).add(4);
adjList.get(4).add(3);
List<List<Integer>> actualResult = kosaraju.kosaraju(n, adjList);
List<List<Integer>> expectedResult = new ArrayList<>();
/*
Expected result:
{0, 1, 2}
{3, 4}
*/
expectedResult.add(Arrays.asList(4, 3));
expectedResult.add(Arrays.asList(1, 2, 0));
assertEquals(expectedResult, actualResult);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java | src/test/java/com/thealgorithms/datastructures/graphs/KruskalTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@SuppressWarnings({"rawtypes", "unchecked"})
public class KruskalTest {
private Kruskal kruskal;
private HashSet<Kruskal.Edge>[] graph;
@BeforeEach
public void setUp() {
kruskal = new Kruskal();
int n = 7;
graph = new HashSet[n];
for (int i = 0; i < n; i++) {
graph[i] = new HashSet<>();
}
// Add edges to the graph
Kruskal.addEdge(graph, 0, 1, 2);
Kruskal.addEdge(graph, 0, 2, 3);
Kruskal.addEdge(graph, 0, 3, 3);
Kruskal.addEdge(graph, 1, 2, 4);
Kruskal.addEdge(graph, 2, 3, 5);
Kruskal.addEdge(graph, 1, 4, 3);
Kruskal.addEdge(graph, 2, 4, 1);
Kruskal.addEdge(graph, 3, 5, 7);
Kruskal.addEdge(graph, 4, 5, 8);
Kruskal.addEdge(graph, 5, 6, 9);
}
@Test
public void testKruskal() {
int n = 6;
HashSet<Kruskal.Edge>[] graph = new HashSet[n];
for (int i = 0; i < n; i++) {
graph[i] = new HashSet<>();
}
Kruskal.addEdge(graph, 0, 1, 4);
Kruskal.addEdge(graph, 0, 2, 2);
Kruskal.addEdge(graph, 1, 2, 1);
Kruskal.addEdge(graph, 1, 3, 5);
Kruskal.addEdge(graph, 2, 3, 8);
Kruskal.addEdge(graph, 2, 4, 10);
Kruskal.addEdge(graph, 3, 4, 2);
Kruskal.addEdge(graph, 3, 5, 6);
Kruskal.addEdge(graph, 4, 5, 3);
HashSet<Kruskal.Edge>[] result = kruskal.kruskal(graph);
List<List<Integer>> actualEdges = new ArrayList<>();
for (HashSet<Kruskal.Edge> edges : result) {
for (Kruskal.Edge edge : edges) {
actualEdges.add(Arrays.asList(edge.from, edge.to, edge.weight));
}
}
List<List<Integer>> expectedEdges = Arrays.asList(Arrays.asList(1, 2, 1), Arrays.asList(0, 2, 2), Arrays.asList(3, 4, 2), Arrays.asList(4, 5, 3), Arrays.asList(1, 3, 5));
assertTrue(actualEdges.containsAll(expectedEdges) && expectedEdges.containsAll(actualEdges));
}
@Test
public void testEmptyGraph() {
HashSet<Kruskal.Edge>[] emptyGraph = new HashSet[0];
HashSet<Kruskal.Edge>[] result = kruskal.kruskal(emptyGraph);
assertEquals(0, result.length);
}
@Test
public void testSingleNodeGraph() {
HashSet<Kruskal.Edge>[] singleNodeGraph = new HashSet[1];
singleNodeGraph[0] = new HashSet<>();
HashSet<Kruskal.Edge>[] result = kruskal.kruskal(singleNodeGraph);
assertTrue(result[0].isEmpty());
}
@Test
public void testGraphWithDisconnectedNodes() {
int n = 5;
HashSet<Kruskal.Edge>[] disconnectedGraph = new HashSet[n];
for (int i = 0; i < n; i++) {
disconnectedGraph[i] = new HashSet<>();
}
Kruskal.addEdge(disconnectedGraph, 0, 1, 2);
Kruskal.addEdge(disconnectedGraph, 2, 3, 4);
HashSet<Kruskal.Edge>[] result = kruskal.kruskal(disconnectedGraph);
List<List<Integer>> actualEdges = new ArrayList<>();
for (HashSet<Kruskal.Edge> edges : result) {
for (Kruskal.Edge edge : edges) {
actualEdges.add(Arrays.asList(edge.from, edge.to, edge.weight));
}
}
List<List<Integer>> expectedEdges = Arrays.asList(Arrays.asList(0, 1, 2), Arrays.asList(2, 3, 4));
assertTrue(actualEdges.containsAll(expectedEdges) && expectedEdges.containsAll(actualEdges));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java | src/test/java/com/thealgorithms/datastructures/graphs/AStarTest.java | package com.thealgorithms.datastructures.graphs;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class AStarTest {
private AStar.Graph graph;
private int[] heuristic;
@BeforeEach
public void setUp() {
// Initialize graph and heuristic values for testing
graph = new AStar.Graph(5);
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 1, 1, null, 0, 2, 2, null, 1, 3, 1, null, 2, 3, 1, null, 3, 4, 1, null));
AStar.initializeGraph(graph, graphData);
heuristic = new int[] {5, 4, 3, 2, 0}; // Heuristic values for each node
}
@Test
public void testAStarFindsPath() {
AStar.PathAndDistance result = AStar.aStar(0, 4, graph, heuristic);
assertEquals(3, result.getDistance(), "Expected distance from 0 to 4 is 3");
assertEquals(Arrays.asList(0, 1, 3, 4), result.getPath(), "Expected path from 0 to 4");
}
@Test
public void testAStarPathNotFound() {
AStar.PathAndDistance result = AStar.aStar(0, 5, graph, heuristic); // Node 5 does not exist
assertEquals(-1, result.getDistance(), "Expected distance when path not found is -1");
assertNull(result.getPath(), "Expected path should be null when no path exists");
}
@Test
public void testAStarSameNode() {
AStar.PathAndDistance result = AStar.aStar(0, 0, graph, heuristic);
assertEquals(0, result.getDistance(), "Expected distance from 0 to 0 is 0");
assertEquals(singletonList(0), result.getPath(), "Expected path should only contain the start node");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java | src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class HamiltonianCycleTest {
private final HamiltonianCycle hamiltonianCycle = new HamiltonianCycle();
@Test
void testFindHamiltonianCycleShouldReturnHamiltonianCycle() {
int[] expectedArray = {0, 1, 2, 4, 3, 0};
int[][] inputArray = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testFindHamiltonianCycleShouldReturnInfinityArray() {
int[] expectedArray = {-1, -1, -1, -1, -1, -1};
int[][] inputArray = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testSingleVertexGraph() {
int[] expectedArray = {0, 0};
int[][] inputArray = {{0}};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testDisconnectedGraphShouldReturnInfinityArray() {
int[] expectedArray = {-1, -1, -1, -1, -1};
int[][] inputArray = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testCompleteGraphShouldReturnHamiltonianCycle() {
int[] expectedArray = {0, 1, 2, 3, 4, 0};
int[][] inputArray = {
{0, 1, 1, 1, 1},
{1, 0, 1, 1, 1},
{1, 1, 0, 1, 1},
{1, 1, 1, 0, 1},
{1, 1, 1, 1, 0},
};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testGraphWithNoEdgesShouldReturnInfinityArray() {
int[] expectedArray = {-1, -1, -1, -1, -1, -1};
int[][] inputArray = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
@Test
void testLargeGraphWithHamiltonianCycle() {
int[] expectedArray = {0, 1, 2, 3, 4, 0};
int[][] inputArray = {
{0, 1, 0, 1, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 1, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 1, 0},
};
assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/ConnectedComponentTest.java | src/test/java/com/thealgorithms/datastructures/graphs/ConnectedComponentTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the Graph class in ConnectedComponent.java.
* Tests the depth-first search implementation and connected component counting.
* Covers various graph topologies including:
* - Single connected components
* - Multiple disconnected components
* - Self-loops
* - Linear chains
* - Cyclic graphs
*/
class ConnectedComponentTest {
@Test
void testSingleConnectedComponent() {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
assertEquals(1, graph.countGraphs());
}
@Test
void testTwoDisconnectedComponents() {
Graph<Integer> graph = new Graph<>();
// Component 1: 1-2-3
graph.addEdge(1, 2);
graph.addEdge(2, 3);
// Component 2: 4-5
graph.addEdge(4, 5);
assertEquals(2, graph.countGraphs());
}
@Test
void testThreeDisconnectedComponents() {
Graph<Character> graph = new Graph<>();
// Component 1: a-b-c-d-e
graph.addEdge('a', 'b');
graph.addEdge('a', 'e');
graph.addEdge('b', 'e');
graph.addEdge('b', 'c');
graph.addEdge('c', 'd');
graph.addEdge('d', 'a');
// Component 2: x-y-z
graph.addEdge('x', 'y');
graph.addEdge('x', 'z');
// Component 3: w (self-loop)
graph.addEdge('w', 'w');
assertEquals(3, graph.countGraphs());
}
@Test
void testSingleNodeSelfLoop() {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 1);
assertEquals(1, graph.countGraphs());
}
@Test
void testLinearChain() {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 5);
assertEquals(1, graph.countGraphs());
}
@Test
void testStarTopology() {
// Star graph with center node 0 connected to nodes 1, 2, 3, 4
Graph<Integer> graph = new Graph<>();
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
assertEquals(1, graph.countGraphs());
}
@Test
void testCompleteGraph() {
// Complete graph K4: every node connected to every other node
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
assertEquals(1, graph.countGraphs());
}
@Test
void testStringVertices() {
Graph<String> graph = new Graph<>();
// Component 1
graph.addEdge("New York", "Los Angeles");
graph.addEdge("Los Angeles", "Chicago");
// Component 2
graph.addEdge("London", "Paris");
// Component 3
graph.addEdge("Tokyo", "Tokyo");
assertEquals(3, graph.countGraphs());
}
@Test
void testEmptyGraph() {
Graph<Integer> graph = new Graph<>();
assertEquals(0, graph.countGraphs());
}
@Test
void testDepthFirstSearchBasic() {
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
// Get the first node and perform DFS
assertNotNull(graph.nodeList);
assertEquals(3, graph.nodeList.size());
}
@Test
void testManyIsolatedComponents() {
Graph<Integer> graph = new Graph<>();
// Create 5 isolated components (each is a self-loop)
graph.addEdge(1, 1);
graph.addEdge(2, 2);
graph.addEdge(3, 3);
graph.addEdge(4, 4);
graph.addEdge(5, 5);
assertEquals(5, graph.countGraphs());
}
@Test
void testBidirectionalEdges() {
Graph<Integer> graph = new Graph<>();
// Note: This is a directed graph representation
// Adding edge 1->2 does not automatically add 2->1
graph.addEdge(1, 2);
graph.addEdge(2, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 2);
assertEquals(1, graph.countGraphs());
}
@Test
void testCyclicGraph() {
Graph<Integer> graph = new Graph<>();
// Create a cycle: 1 -> 2 -> 3 -> 4 -> 1
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
assertEquals(1, graph.countGraphs());
}
@Test
void testMultipleCycles() {
Graph<Integer> graph = new Graph<>();
// Cycle 1: 1 -> 2 -> 3 -> 1
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 1);
// Cycle 2: 4 -> 5 -> 4
graph.addEdge(4, 5);
graph.addEdge(5, 4);
assertEquals(2, graph.countGraphs());
}
@Test
void testIntegerGraphFromMainExample() {
// Recreate the example from main method
Graph<Integer> graph = new Graph<>();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
graph.addEdge(7, 8);
graph.addEdge(8, 10);
graph.addEdge(10, 8);
assertEquals(2, graph.countGraphs());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.datastructures.graphs.BoruvkaAlgorithm.Graph;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class BoruvkaAlgorithmTest {
@Test
public void testBoruvkaMSTV9E14() {
List<BoruvkaAlgorithm.Edge> edges = new ArrayList<>();
edges.add(new BoruvkaAlgorithm.Edge(0, 1, 10));
edges.add(new BoruvkaAlgorithm.Edge(0, 2, 12));
edges.add(new BoruvkaAlgorithm.Edge(1, 2, 9));
edges.add(new BoruvkaAlgorithm.Edge(1, 3, 8));
edges.add(new BoruvkaAlgorithm.Edge(2, 4, 3));
edges.add(new BoruvkaAlgorithm.Edge(2, 5, 1));
edges.add(new BoruvkaAlgorithm.Edge(4, 5, 3));
edges.add(new BoruvkaAlgorithm.Edge(4, 3, 7));
edges.add(new BoruvkaAlgorithm.Edge(3, 6, 8));
edges.add(new BoruvkaAlgorithm.Edge(3, 7, 5));
edges.add(new BoruvkaAlgorithm.Edge(5, 7, 6));
edges.add(new BoruvkaAlgorithm.Edge(6, 7, 9));
edges.add(new BoruvkaAlgorithm.Edge(6, 8, 2));
edges.add(new BoruvkaAlgorithm.Edge(7, 8, 11));
final var graph = new Graph(9, edges);
/*
* Adjacency matrix
* 0 1 2 3 4 5 6 7 8
* 0 0 10 12 0 0 0 0 0 0
* 1 10 0 9 8 0 0 0 0 0
* 2 12 9 0 0 3 1 0 0 0
* 3 0 8 0 0 7 0 8 5 0
* 4 0 0 3 7 0 3 0 0 0
* 5 0 0 1 0 3 0 0 6 0
* 6 0 0 0 8 0 0 0 9 2
* 7 0 0 0 5 0 6 9 0 11
* 8 0 0 0 0 0 0 2 11 0
*/
final var result = BoruvkaAlgorithm.boruvkaMST(graph);
assertEquals(8, result.size());
assertEquals(43, computeTotalWeight(result));
}
@Test
void testBoruvkaMSTV2E1() {
List<BoruvkaAlgorithm.Edge> edges = new ArrayList<>();
edges.add(new BoruvkaAlgorithm.Edge(0, 1, 10));
final var graph = new Graph(2, edges);
/*
* Adjacency matrix
* 0 1
* 0 0 10
* 1 10 0
*/
final var result = BoruvkaAlgorithm.boruvkaMST(graph);
assertEquals(1, result.size());
assertEquals(10, computeTotalWeight(result));
}
@Test
void testCompleteGraphK4() {
List<BoruvkaAlgorithm.Edge> edges = new ArrayList<>();
edges.add(new BoruvkaAlgorithm.Edge(0, 1, 7));
edges.add(new BoruvkaAlgorithm.Edge(0, 2, 2));
edges.add(new BoruvkaAlgorithm.Edge(0, 3, 5));
edges.add(new BoruvkaAlgorithm.Edge(1, 2, 3));
edges.add(new BoruvkaAlgorithm.Edge(1, 3, 4));
edges.add(new BoruvkaAlgorithm.Edge(2, 3, 1));
final var graph = new Graph(4, edges);
/*
* Adjacency matrix
* 0 1 2 3
* 0 0 7 2 5
* 1 7 0 3 4
* 2 2 3 0 1
* 3 5 4 1 0
*/
final var result = BoruvkaAlgorithm.boruvkaMST(graph);
assertEquals(3, result.size());
assertEquals(6, computeTotalWeight(result));
}
@Test
void testNegativeVertices() {
Exception exception1 = assertThrows(IllegalArgumentException.class, () -> new Graph(-1, null));
String expectedMessage = "Number of vertices must be positive";
String actualMessage = exception1.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
void testEdgesNull() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> new Graph(0, null));
String expectedMessage = "Edges list must not be null or empty";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
void testEdgesEmpty() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> new Graph(0, new ArrayList<>()));
String expectedMessage = "Edges list must not be null or empty";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
void testEdgesRange() {
// Valid input
List<BoruvkaAlgorithm.Edge> validEdges = new ArrayList<>();
validEdges.add(new BoruvkaAlgorithm.Edge(0, 1, 2));
validEdges.add(new BoruvkaAlgorithm.Edge(1, 2, 3));
final var validGraph = new BoruvkaAlgorithm.Graph(3, validEdges);
assertEquals(validEdges, validGraph.edges);
// Edge source out of range
Exception exception1 = assertThrows(IllegalArgumentException.class, () -> {
List<BoruvkaAlgorithm.Edge> invalidEdges = new ArrayList<>();
invalidEdges.add(new BoruvkaAlgorithm.Edge(-1, 1, 2));
final var invalidGraph = new BoruvkaAlgorithm.Graph(1, invalidEdges);
assertEquals(invalidEdges, invalidGraph.edges);
});
String expectedMessage1 = "Edge vertex out of range";
String actualMessage1 = exception1.getMessage();
assertTrue(actualMessage1.contains(expectedMessage1));
// Edge source out of range
Exception exception2 = assertThrows(IllegalArgumentException.class, () -> {
List<BoruvkaAlgorithm.Edge> invalidEdges = new ArrayList<>();
invalidEdges.add(new BoruvkaAlgorithm.Edge(1, 0, 2));
final var invalidGraph = new BoruvkaAlgorithm.Graph(1, invalidEdges);
assertEquals(invalidEdges, invalidGraph.edges);
});
String expectedMessage2 = "Edge vertex out of range";
String actualMessage2 = exception2.getMessage();
assertTrue(actualMessage2.contains(expectedMessage2));
// Edge destination out of range
Exception exception3 = assertThrows(IllegalArgumentException.class, () -> {
List<BoruvkaAlgorithm.Edge> invalidEdges = new ArrayList<>();
invalidEdges.add(new BoruvkaAlgorithm.Edge(0, -1, 2));
final var invalidGraph = new BoruvkaAlgorithm.Graph(1, invalidEdges);
assertEquals(invalidEdges, invalidGraph.edges);
});
String expectedMessage3 = "Edge vertex out of range";
String actualMessage3 = exception3.getMessage();
assertTrue(actualMessage3.contains(expectedMessage3));
// Edge destination out of range
Exception exception4 = assertThrows(IllegalArgumentException.class, () -> {
List<BoruvkaAlgorithm.Edge> invalidEdges = new ArrayList<>();
invalidEdges.add(new BoruvkaAlgorithm.Edge(0, 1, 2));
final var invalidGraph = new BoruvkaAlgorithm.Graph(1, invalidEdges);
assertEquals(invalidEdges, invalidGraph.edges);
});
String expectedMessage4 = "Edge vertex out of range";
String actualMessage4 = exception4.getMessage();
assertTrue(actualMessage4.contains(expectedMessage4));
}
/**
* Computes the total weight of the Minimum Spanning Tree
*
* @param result list of edges in the Minimum Spanning Tree
* @return the total weight of the Minimum Spanning Tree
*/
int computeTotalWeight(final Iterable<BoruvkaAlgorithm.Edge> result) {
int totalWeight = 0;
for (final var edge : result) {
totalWeight += edge.weight;
}
return totalWeight;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java | src/test/java/com/thealgorithms/datastructures/graphs/FloydWarshallTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class FloydWarshallTest {
@Test
void testSmallGraph() {
int[][] adjacencyMatrix = {{0, 0, 0, 0}, // Ignored row (0 index)
{0, 0, 3, FloydWarshall.INFINITY}, {0, FloydWarshall.INFINITY, 0, 1}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}};
FloydWarshall fw = new FloydWarshall(3);
fw.floydwarshall(adjacencyMatrix);
int[][] expectedDistanceMatrix = {{0, 0, 0, 0}, {0, 0, 3, 4}, {0, FloydWarshall.INFINITY, 0, 1}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}};
assertArrayEquals(expectedDistanceMatrix, fw.getDistanceMatrix());
}
@Test
void testLargerGraph() {
int[][] adjacencyMatrix = {{0, 0, 0, 0, 0}, {0, 0, 1, FloydWarshall.INFINITY, 2}, {0, FloydWarshall.INFINITY, 0, 4, FloydWarshall.INFINITY}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0, 3}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}};
FloydWarshall fw = new FloydWarshall(4);
fw.floydwarshall(adjacencyMatrix);
int[][] expectedDistanceMatrix = {{0, 0, 0, 0, 0}, {0, 0, 1, 5, 2}, {0, FloydWarshall.INFINITY, 0, 4, 7}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0, 3}, {0, FloydWarshall.INFINITY, FloydWarshall.INFINITY, FloydWarshall.INFINITY, 0}};
assertArrayEquals(expectedDistanceMatrix, fw.getDistanceMatrix());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/DialsAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/DialsAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
final class DialsAlgorithmTest {
private List<List<DialsAlgorithm.Edge>> graph;
private static final int NUM_VERTICES = 6;
private static final int MAX_EDGE_WEIGHT = 10;
@BeforeEach
void setUp() {
graph = new ArrayList<>();
for (int i = 0; i < NUM_VERTICES; i++) {
graph.add(new ArrayList<>());
}
}
private void addEdge(int u, int v, int weight) {
graph.get(u).add(new DialsAlgorithm.Edge(v, weight));
}
@Test
@DisplayName("Test with a simple connected graph")
void testSimpleGraph() {
// Build graph from a standard example
addEdge(0, 1, 2);
addEdge(0, 2, 4);
addEdge(1, 2, 1);
addEdge(1, 3, 7);
addEdge(2, 4, 3);
addEdge(3, 5, 1);
addEdge(4, 3, 2);
addEdge(4, 5, 5);
int[] expectedDistances = {0, 2, 3, 8, 6, 9};
int[] actualDistances = DialsAlgorithm.run(graph, 0, MAX_EDGE_WEIGHT);
assertArrayEquals(expectedDistances, actualDistances);
}
@Test
@DisplayName("Test with a disconnected node")
void testDisconnectedNode() {
addEdge(0, 1, 5);
addEdge(1, 2, 5);
// Node 3, 4, 5 are disconnected
int[] expectedDistances = {0, 5, 10, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
int[] actualDistances = DialsAlgorithm.run(graph, 0, MAX_EDGE_WEIGHT);
assertArrayEquals(expectedDistances, actualDistances);
}
@Test
@DisplayName("Test with source as destination")
void testSourceIsDestination() {
addEdge(0, 1, 10);
int[] expectedDistances = {0, 10, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
// Run with source 0
int[] actualDistances = DialsAlgorithm.run(graph, 0, MAX_EDGE_WEIGHT);
assertArrayEquals(expectedDistances, actualDistances);
}
@Test
@DisplayName("Test graph with multiple paths to a node")
void testMultiplePaths() {
addEdge(0, 1, 10);
addEdge(0, 2, 3);
addEdge(2, 1, 2); // Shorter path to 1 is via 2 (3+2=5)
int[] expectedDistances = {0, 5, 3, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
int[] actualDistances = DialsAlgorithm.run(graph, 0, MAX_EDGE_WEIGHT);
assertArrayEquals(expectedDistances, actualDistances);
}
@Test
@DisplayName("Test with an invalid source vertex")
void testInvalidSource() {
assertThrows(IllegalArgumentException.class, () -> DialsAlgorithm.run(graph, -1, MAX_EDGE_WEIGHT));
assertThrows(IllegalArgumentException.class, () -> DialsAlgorithm.run(graph, NUM_VERTICES, MAX_EDGE_WEIGHT));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java | src/test/java/com/thealgorithms/datastructures/graphs/MatrixGraphsTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MatrixGraphsTest {
@Test
void testGraphConstruction() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
assertEquals(5, graph.numberOfVertices());
assertEquals(0, graph.numberOfEdges());
}
@Test
void testAddEdge() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
assertTrue(graph.addEdge(0, 1));
assertTrue(graph.edgeDoesExist(0, 1));
assertTrue(graph.edgeDoesExist(1, 0));
assertEquals(1, graph.numberOfEdges());
// Adding the same edge again should return false
assertFalse(graph.addEdge(0, 1));
assertFalse(graph.addEdge(5, 1));
assertFalse(graph.addEdge(-1, 1));
}
@Test
void testRemoveEdge() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
assertTrue(graph.removeEdge(0, 1));
assertFalse(graph.edgeDoesExist(0, 1));
assertFalse(graph.edgeDoesExist(1, 0));
assertEquals(1, graph.numberOfEdges());
assertFalse(graph.removeEdge(0, 3));
assertFalse(graph.removeEdge(5, 1));
assertFalse(graph.removeEdge(-1, 1));
}
@Test
void testVertexDoesExist() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
assertTrue(graph.vertexDoesExist(0));
assertTrue(graph.vertexDoesExist(4));
assertFalse(graph.vertexDoesExist(5));
assertFalse(graph.vertexDoesExist(-1));
}
@Test
void testDepthFirstOrder() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
List<Integer> dfs = graph.depthFirstOrder(0);
assertEquals(5, dfs.size());
assertEquals(0, dfs.getFirst());
assertTrue(dfs.containsAll(Arrays.asList(0, 1, 2, 3, 4)));
List<Integer> emptyDfs = graph.depthFirstOrder(5);
assertTrue(emptyDfs.isEmpty());
}
@Test
void testBreadthFirstOrder() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(5, bfs.size());
assertEquals(0, bfs.getFirst());
assertTrue(bfs.containsAll(Arrays.asList(0, 1, 2, 3, 4)));
List<Integer> emptyBfs = graph.breadthFirstOrder(5);
assertTrue(emptyBfs.isEmpty());
}
@Test
void testToString() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(3);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
String expected = " 0 1 2 \n"
+ "0 : 0 1 0 \n"
+ "1 : 1 0 1 \n"
+ "2 : 0 1 0 \n";
assertEquals(expected, graph.toString());
}
@Test
void testCyclicGraph() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 0);
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(4, dfs.size());
assertEquals(4, bfs.size());
assertTrue(dfs.containsAll(Arrays.asList(0, 1, 2, 3)));
assertTrue(bfs.containsAll(Arrays.asList(0, 1, 2, 3)));
}
@Test
void testDisconnectedGraph() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(2, 3);
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(2, dfs.size());
assertEquals(2, bfs.size());
assertTrue(dfs.containsAll(Arrays.asList(0, 1)));
assertTrue(bfs.containsAll(Arrays.asList(0, 1)));
}
@Test
void testSingleVertexGraphDfs() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(1);
List<Integer> dfs = graph.depthFirstOrder(0);
assertEquals(1, dfs.size());
assertEquals(0, dfs.getFirst());
}
@Test
void testSingleVertexGraphBfs() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(1);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(1, bfs.size());
assertEquals(0, bfs.getFirst());
}
@Test
void testBfsLevelOrder() {
// Create a graph where BFS should visit level by level
// 0
// /|\
// 1 2 3
// |
// 4
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 4);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(5, bfs.size());
assertEquals(0, bfs.get(0));
// Level 1 vertices (1, 2, 3) should appear before level 2 vertex (4)
int indexOf4 = bfs.indexOf(4);
assertTrue(bfs.indexOf(1) < indexOf4);
assertTrue(bfs.indexOf(2) < indexOf4);
assertTrue(bfs.indexOf(3) < indexOf4);
}
@Test
void testDfsStartFromDifferentVertices() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
// DFS from vertex 0
List<Integer> dfs0 = graph.depthFirstOrder(0);
assertEquals(4, dfs0.size());
assertEquals(0, dfs0.get(0));
// DFS from vertex 2
List<Integer> dfs2 = graph.depthFirstOrder(2);
assertEquals(4, dfs2.size());
assertEquals(2, dfs2.get(0));
// DFS from vertex 3
List<Integer> dfs3 = graph.depthFirstOrder(3);
assertEquals(4, dfs3.size());
assertEquals(3, dfs3.get(0));
}
@Test
void testBfsStartFromDifferentVertices() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
// BFS from vertex 0
List<Integer> bfs0 = graph.breadthFirstOrder(0);
assertEquals(4, bfs0.size());
assertEquals(0, bfs0.get(0));
// BFS from vertex 2
List<Integer> bfs2 = graph.breadthFirstOrder(2);
assertEquals(4, bfs2.size());
assertEquals(2, bfs2.get(0));
}
@Test
void testStarTopologyBfs() {
// Star graph: 0 is center connected to 1, 2, 3, 4
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(5, bfs.size());
assertEquals(0, bfs.get(0));
// All neighbors should be at distance 1
assertTrue(bfs.containsAll(Arrays.asList(1, 2, 3, 4)));
}
@Test
void testStarTopologyDfs() {
// Star graph: 0 is center connected to 1, 2, 3, 4
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
List<Integer> dfs = graph.depthFirstOrder(0);
assertEquals(5, dfs.size());
assertEquals(0, dfs.get(0));
assertTrue(dfs.containsAll(Arrays.asList(1, 2, 3, 4)));
}
@Test
void testNegativeStartVertexDfs() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
List<Integer> dfs = graph.depthFirstOrder(-1);
assertTrue(dfs.isEmpty());
}
@Test
void testNegativeStartVertexBfs() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
List<Integer> bfs = graph.breadthFirstOrder(-1);
assertTrue(bfs.isEmpty());
}
@Test
void testCompleteGraphKFour() {
// Complete graph K4: every vertex connected to every other vertex
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
assertEquals(6, graph.numberOfEdges());
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(4, dfs.size());
assertEquals(4, bfs.size());
assertTrue(dfs.containsAll(Arrays.asList(0, 1, 2, 3)));
assertTrue(bfs.containsAll(Arrays.asList(0, 1, 2, 3)));
}
@Test
void testLargerGraphTraversal() {
// Create a larger graph with 10 vertices
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
graph.addEdge(2, 6);
graph.addEdge(3, 7);
graph.addEdge(4, 8);
graph.addEdge(5, 9);
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(10, dfs.size());
assertEquals(10, bfs.size());
assertEquals(0, dfs.get(0));
assertEquals(0, bfs.get(0));
}
@Test
void testSelfLoop() {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(3);
graph.addEdge(0, 0); // Self loop
graph.addEdge(0, 1);
graph.addEdge(1, 2);
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(3, dfs.size());
assertEquals(3, bfs.size());
}
@Test
void testLinearGraphTraversal() {
// Linear graph: 0 - 1 - 2 - 3 - 4
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(5);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
List<Integer> dfs = graph.depthFirstOrder(0);
List<Integer> bfs = graph.breadthFirstOrder(0);
assertEquals(5, dfs.size());
assertEquals(5, bfs.size());
// In a linear graph, BFS and DFS starting from 0 should be the same
assertEquals(Arrays.asList(0, 1, 2, 3, 4), dfs);
assertEquals(Arrays.asList(0, 1, 2, 3, 4), bfs);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/TwoSatTest.java | src/test/java/com/thealgorithms/datastructures/graphs/TwoSatTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Testcases for 2-SAT.
* Please note thea while checking for boolean assignments always keep n + 1 elements and the first element should be always false.
*/
public class TwoSatTest {
private TwoSat twoSat;
/**
* Case 1: Basic satisfiable case.
* Simple 3 clauses with consistent assignments.
*/
@Test
public void testSatisfiableBasicCase() {
twoSat = new TwoSat(5);
twoSat.addClause(1, false, 2, false); // (x1 ∨ x2)
twoSat.addClause(3, true, 2, false); // (¬x3 ∨ x2)
twoSat.addClause(4, false, 5, true); // (x4 ∨ ¬x5)
twoSat.solve();
assertTrue(twoSat.isSolutionExists(), "Expected solution to exist");
boolean[] expected = {false, true, true, true, true, true};
assertArrayEquals(expected, twoSat.getSolutions());
}
/**
* Case 2: Unsatisfiable due to direct contradiction.
* (x1 ∨ x1) ∧ (¬x1 ∨ ¬x1) makes x1 and ¬x1 both required.
*/
@Test
public void testUnsatisfiableContradiction() {
twoSat = new TwoSat(1);
twoSat.addClause(1, false, 1, false); // (x1 ∨ x1)
twoSat.addClause(1, true, 1, true); // (¬x1 ∨ ¬x1)
twoSat.solve();
assertFalse(twoSat.isSolutionExists(), "Expected no solution (contradiction)");
}
/**
* Case 3: Single variable, trivially satisfiable.
* Only (x1 ∨ x1) exists.
*/
@Test
public void testSingleVariableTrivialSatisfiable() {
twoSat = new TwoSat(1);
twoSat.addClause(1, false, 1, false); // (x1 ∨ x1)
twoSat.solve();
assertTrue(twoSat.isSolutionExists(), "Expected solution to exist");
boolean[] expected = {false, true};
assertArrayEquals(expected, twoSat.getSolutions());
}
/**
* Case 4: Larger satisfiable system with dependencies.
* (x1 ∨ x2), (¬x2 ∨ x3), (¬x3 ∨ x4), (¬x4 ∨ x5)
*/
@Test
public void testChainedDependenciesSatisfiable() {
twoSat = new TwoSat(5);
twoSat.addClause(1, false, 2, false);
twoSat.addClause(2, true, 3, false);
twoSat.addClause(3, true, 4, false);
twoSat.addClause(4, true, 5, false);
twoSat.solve();
assertTrue(twoSat.isSolutionExists(), "Expected solution to exist");
boolean[] solution = twoSat.getSolutions();
for (int i = 1; i <= 5; i++) {
assertTrue(solution[i], "Expected x" + i + " to be true");
}
}
/**
* Case 5: Contradiction due to dependency cycle.
* (x1 ∨ x2), (¬x1 ∨ ¬x2), (x1 ∨ ¬x2), (¬x1 ∨ x2)
* These clauses form a circular dependency making it impossible.
*/
@Test
public void testUnsatisfiableCycle() {
twoSat = new TwoSat(2);
twoSat.addClause(1, false, 2, false);
twoSat.addClause(1, true, 2, true);
twoSat.addClause(1, false, 2, true);
twoSat.addClause(1, true, 2, false);
twoSat.solve();
assertFalse(twoSat.isSolutionExists(), "Expected no solution due to contradictory cycle");
}
/**
* Testcase from CSES
*/
@Test
public void test6() {
twoSat = new TwoSat(2);
twoSat.addClause(1, true, 2, false);
twoSat.addClause(2, true, 1, false);
twoSat.addClause(1, true, 1, true);
twoSat.addClause(2, false, 2, false);
twoSat.solve();
assertFalse(twoSat.isSolutionExists(), "Expected no solution.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java | src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.datastructures.graphs.WelshPowell.Graph;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class WelshPowellTest {
@Test
void testSimpleGraph() {
final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}});
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertEquals(2, countDistinctColors(colors));
}
@Test
void testDisconnectedGraph() {
final var graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertEquals(1, countDistinctColors(colors));
}
@Test
void testCompleteGraph() {
final var graph = WelshPowell.makeGraph(3, new int[][] {{0, 1}, {1, 2}, {2, 0}});
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertEquals(3, countDistinctColors(colors));
}
@Test
void testComplexGraph() {
int[][] edges = {
{0, 7},
{0, 1},
{1, 3},
{2, 3},
{3, 8},
{3, 10},
{4, 10},
{4, 5},
{5, 6},
{6, 10},
{6, 7},
{7, 8},
{7, 9},
{7, 10},
{8, 9},
{9, 10},
};
final var graph = WelshPowell.makeGraph(11, edges); // 11 vertices from A (0) to K (10)
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors), "The coloring should be valid with no adjacent vertices sharing the same color.");
assertEquals(3, countDistinctColors(colors), "The chromatic number of the graph should be 3.");
}
@Test
void testNegativeVertices() {
assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(-1, new int[][] {}); }, "Number of vertices cannot be negative");
}
@Test
void testSelfLoop() {
assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 0}}); }, "Self-loops are not allowed");
}
@Test
void testInvalidVertex() {
assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 3}}); }, "Vertex out of bounds");
assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, -1}}); }, "Vertex out of bounds");
}
@Test
void testInvalidEdgeArray() {
assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0}}); }, "Edge array must have exactly two elements");
}
@Test
void testWithPreColoredVertex() {
final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}});
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertTrue(countDistinctColors(colors) >= 2);
for (int color : colors) {
assertTrue(color >= 0);
}
}
@Test
void testLargeGraph() {
int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 0}, {6, 7}, {7, 8}, {8, 6}, {9, 10}, {10, 11}, {11, 9}, {12, 13}, {13, 14}, {14, 15}};
final var graph = WelshPowell.makeGraph(16, edges); // 16 vertices
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertEquals(3, countDistinctColors(colors)); // Expecting a maximum of 3 colors
}
@Test
void testStarGraph() {
int[][] edges = {{0, 1}, {0, 2}, {0, 3}, {0, 4}};
final var graph = WelshPowell.makeGraph(5, edges); // 5 vertices in a star formation
int[] colors = WelshPowell.findColoring(graph);
assertTrue(isColoringValid(graph, colors));
assertEquals(2, countDistinctColors(colors)); // Star graph can be colored with 2 colors
}
private boolean isColoringValid(Graph graph, int[] colors) {
if (Arrays.stream(colors).anyMatch(n -> n < 0)) {
return false;
}
for (int i = 0; i < graph.getNumVertices(); i++) {
for (int neighbor : graph.getAdjacencyList(i)) {
if (i != neighbor && colors[i] == colors[neighbor]) {
return false; // Adjacent vertices have the same color
}
}
}
return true; // No adjacent vertices share the same color
}
private int countDistinctColors(int[] colors) {
return (int) Arrays.stream(colors).distinct().count();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the EdmondsBlossomAlgorithm class.
*
* These tests ensure that the Edmonds' Blossom Algorithm implementation
* works as expected for various graph structures, returning the correct
* maximum matching.
*/
public class EdmondsBlossomAlgorithmTest {
/**
* Helper method to convert a list of matching pairs into a sorted 2D array.
* Sorting ensures consistent ordering of pairs and vertices for easier comparison in tests.
*
* @param matching List of matched pairs returned by the algorithm.
* @return A sorted 2D array of matching pairs.
*/
private int[][] convertMatchingToArray(Collection<int[]> matching) {
// Convert the list of pairs into an array
int[][] result = matching.toArray(new int[0][]);
// Sort each individual pair for consistency
for (int[] pair : result) {
Arrays.sort(pair);
}
// Sort the array of pairs to ensure consistent order
Arrays.sort(result, (a, b) -> Integer.compare(a[0], b[0]));
return result;
}
/**
* Test Case 1: A triangle graph where vertices 0, 1, and 2 form a cycle.
* The expected maximum matching is a single pair (0, 1) or any equivalent pair from the cycle.
*/
@Test
public void testCase1() {
List<int[]> edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 0});
List<int[]> matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 3);
int[][] expected = new int[][] {{0, 1}};
assertArrayEquals(expected, convertMatchingToArray(matching));
}
/**
* Test Case 2: A disconnected graph where vertices 0, 1, 2 form one component,
* and vertices 3, 4 form another. The expected maximum matching is two pairs:
* (0, 1) and (3, 4).
*/
@Test
public void testCase2() {
List<int[]> edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {3, 4});
List<int[]> matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 5);
int[][] expected = new int[][] {{0, 1}, {3, 4}};
assertArrayEquals(expected, convertMatchingToArray(matching));
}
/**
* Test Case 3: A cycle graph involving vertices 0, 1, 2, 3 forming a cycle,
* with an additional edge (4, 5) outside the cycle.
* The expected maximum matching is (0, 1) and (4, 5).
*/
@Test
public void testCase3() {
List<int[]> edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 0}, new int[] {4, 5});
List<int[]> matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 6);
// Updated expected output to include the maximum matching pairs
int[][] expected = new int[][] {{0, 1}, {2, 3}, {4, 5}};
assertArrayEquals(expected, convertMatchingToArray(matching));
}
/**
* Test Case 4: A graph with no edges.
* Since there are no edges, the expected matching is an empty set.
*/
@Test
public void testCaseNoMatching() {
List<int[]> edges = Collections.emptyList(); // No edges
List<int[]> matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 3);
int[][] expected = new int[][] {}; // No pairs expected
assertArrayEquals(expected, convertMatchingToArray(matching));
}
/**
* Test Case 5: A more complex graph with multiple cycles and extra edges.
* This tests the algorithm's ability to handle larger, more intricate graphs.
* The expected matching is {{0, 1}, {2, 5}, {3, 4}}.
*/
@Test
public void testCaseLargeGraph() {
List<int[]> edges = Arrays.asList(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 4}, new int[] {4, 5}, new int[] {5, 0}, new int[] {1, 4}, new int[] {2, 5});
List<int[]> matching = EdmondsBlossomAlgorithm.maximumMatching(edges, 6);
// Check if the size of the matching is correct (i.e., 3 pairs)
assertEquals(3, matching.size());
// Check that the result contains valid pairs (any order is fine)
// Valid maximum matchings could be {{0, 1}, {2, 5}, {3, 4}} or {{0, 1}, {2, 3}, {4, 5}}, etc.
int[][] possibleMatching1 = new int[][] {{0, 1}, {2, 5}, {3, 4}};
int[][] possibleMatching2 = new int[][] {{0, 1}, {2, 3}, {4, 5}};
int[][] result = convertMatchingToArray(matching);
// Assert that the result is one of the valid maximum matchings
assertTrue(Arrays.deepEquals(result, possibleMatching1) || Arrays.deepEquals(result, possibleMatching2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithmTest.java | src/test/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithmTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DijkstraOptimizedAlgorithmTest {
private DijkstraOptimizedAlgorithm dijkstraOptimizedAlgorithm;
private int[][] graph;
@BeforeEach
void setUp() {
graph = new int[][] {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
};
dijkstraOptimizedAlgorithm = new DijkstraOptimizedAlgorithm(graph.length);
}
@Test
void testRunAlgorithm() {
int[] expectedDistances = {0, 4, 12, 19, 21, 11, 9, 8, 14};
assertArrayEquals(expectedDistances, dijkstraOptimizedAlgorithm.run(graph, 0));
}
@Test
void testGraphWithDisconnectedNodes() {
int[][] disconnectedGraph = {
{0, 3, 0, 0}, {3, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0} // Node 3 is disconnected
};
DijkstraOptimizedAlgorithm dijkstraDisconnected = new DijkstraOptimizedAlgorithm(disconnectedGraph.length);
// Testing from vertex 0
int[] expectedDistances = {0, 3, 4, Integer.MAX_VALUE}; // Node 3 is unreachable
assertArrayEquals(expectedDistances, dijkstraDisconnected.run(disconnectedGraph, 0));
}
@Test
void testSingleVertexGraph() {
int[][] singleVertexGraph = {{0}};
DijkstraOptimizedAlgorithm dijkstraSingleVertex = new DijkstraOptimizedAlgorithm(1);
int[] expectedDistances = {0}; // The only vertex's distance to itself is 0
assertArrayEquals(expectedDistances, dijkstraSingleVertex.run(singleVertexGraph, 0));
}
@Test
void testInvalidSourceVertex() {
assertThrows(IllegalArgumentException.class, () -> dijkstraOptimizedAlgorithm.run(graph, -1));
assertThrows(IllegalArgumentException.class, () -> dijkstraOptimizedAlgorithm.run(graph, graph.length));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/graphs/FordFulkersonTest.java | src/test/java/com/thealgorithms/datastructures/graphs/FordFulkersonTest.java | package com.thealgorithms.datastructures.graphs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class FordFulkersonTest {
@Test
public void testMaxFlow() {
int vertexCount = 6;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Setting up the capacity graph
capacity[0][1] = 12;
capacity[0][3] = 13;
capacity[1][2] = 10;
capacity[2][3] = 13;
capacity[2][4] = 3;
capacity[2][5] = 15;
capacity[3][2] = 7;
capacity[3][4] = 15;
capacity[4][5] = 17;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 5);
assertEquals(23, maxFlow);
}
@Test
public void testNoFlow() {
int vertexCount = 6;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// No connections between source and sink
capacity[0][1] = 10;
capacity[2][3] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 1, 4);
assertEquals(0, maxFlow);
}
@Test
public void testSinglePath() {
int vertexCount = 6;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Setting up a single path from source to sink
capacity[0][1] = 5;
capacity[1][2] = 5;
capacity[2][3] = 5;
capacity[3][4] = 5;
capacity[4][5] = 5;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 5);
assertEquals(5, maxFlow);
}
@Test
public void testParallelPaths() {
int vertexCount = 4;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Setting up parallel paths from source to sink
capacity[0][1] = 10;
capacity[0][2] = 10;
capacity[1][3] = 10;
capacity[2][3] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 3);
assertEquals(20, maxFlow);
}
@Test
public void testComplexNetwork() {
int vertexCount = 5;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Complex network
capacity[0][1] = 10;
capacity[0][2] = 10;
capacity[1][3] = 4;
capacity[1][4] = 8;
capacity[2][4] = 9;
capacity[3][2] = 6;
capacity[3][4] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 4);
assertEquals(19, maxFlow);
}
@Test
public void testLargeNetwork() {
int vertexCount = 8;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Setting up a large network
capacity[0][1] = 10;
capacity[0][2] = 5;
capacity[1][3] = 15;
capacity[2][3] = 10;
capacity[1][4] = 10;
capacity[3][5] = 10;
capacity[4][5] = 5;
capacity[4][6] = 10;
capacity[5][7] = 10;
capacity[6][7] = 15;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 7);
assertEquals(15, maxFlow); // Maximum flow should be 15
}
@Test
public void testMultipleSourcesAndSinks() {
int vertexCount = 7;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Creating multiple sources and sinks scenario
capacity[0][1] = 10; // Source 1
capacity[0][2] = 5;
capacity[1][3] = 15;
capacity[2][3] = 10;
capacity[3][4] = 10; // Sink 1
capacity[3][5] = 5;
capacity[3][6] = 10; // Sink 2
capacity[5][6] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 4);
assertEquals(10, maxFlow); // Maximum flow should be 10
}
@Test
public void testDisconnectedGraph() {
int vertexCount = 6;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// No connection between source and sink
capacity[0][1] = 10; // Only one edge not connected to the sink
capacity[1][2] = 10;
capacity[3][4] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 5);
assertEquals(0, maxFlow); // No flow should be possible
}
@Test
public void testZeroCapacityEdge() {
int vertexCount = 4;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Including a zero capacity edge
capacity[0][1] = 10;
capacity[0][2] = 0; // Zero capacity
capacity[1][3] = 5;
capacity[2][3] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 3);
assertEquals(5, maxFlow); // Flow only possible through 0 -> 1 -> 3
}
@Test
public void testAllEdgesZeroCapacity() {
int vertexCount = 5;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// All edges with zero capacity
capacity[0][1] = 0;
capacity[1][2] = 0;
capacity[2][3] = 0;
capacity[3][4] = 0;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 4);
assertEquals(0, maxFlow); // No flow should be possible
}
@Test
public void testCycleGraph() {
int vertexCount = 4;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Setting up a cycle
capacity[0][1] = 10;
capacity[1][2] = 5;
capacity[2][0] = 5; // This creates a cycle
capacity[1][3] = 15;
capacity[2][3] = 10;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 3);
assertEquals(10, maxFlow); // Maximum flow should be 10
}
@Test
public void testFlowWithExcessCapacity() {
int vertexCount = 5;
int[][] capacity = new int[vertexCount][vertexCount];
int[][] flow = new int[vertexCount][vertexCount];
// Extra capacity in the flow
capacity[0][1] = 20;
capacity[1][2] = 10;
capacity[2][3] = 15;
capacity[1][3] = 5;
int maxFlow = FordFulkerson.networkFlow(vertexCount, capacity, flow, 0, 3);
assertEquals(15, maxFlow); // Maximum flow should be 15 (20 from 0->1 and 10->2, limited by 15->3)
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java | package com.thealgorithms.datastructures.caches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class LFUCacheTest {
@Test
void testLFUCacheWithIntegerValueShouldPass() {
LFUCache<Integer, Integer> lfuCache = new LFUCache<>(5);
lfuCache.put(1, 10);
lfuCache.put(2, 20);
lfuCache.put(3, 30);
lfuCache.put(4, 40);
lfuCache.put(5, 50);
// get method call will increase frequency of key 1 by 1
assertEquals(10, lfuCache.get(1));
// this operation will remove value with key as 2
lfuCache.put(6, 60);
// will return null as value with key 2 is now evicted
assertNull(lfuCache.get(2));
// should return 60
assertEquals(60, lfuCache.get(6));
// this operation will remove value with key as 3
lfuCache.put(7, 70);
assertNull(lfuCache.get(2));
assertEquals(70, lfuCache.get(7));
}
@Test
void testLFUCacheWithStringValueShouldPass() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(5);
lfuCache.put(1, "Alpha");
lfuCache.put(2, "Beta");
lfuCache.put(3, "Gamma");
lfuCache.put(4, "Delta");
lfuCache.put(5, "Epsilon");
// get method call will increase frequency of key 1 by 1
assertEquals("Alpha", lfuCache.get(1));
// this operation will remove value with key as 2
lfuCache.put(6, "Digamma");
// will return null as value with key 2 is now evicted
assertNull(lfuCache.get(2));
// should return string Digamma
assertEquals("Digamma", lfuCache.get(6));
// this operation will remove value with key as 3
lfuCache.put(7, "Zeta");
assertNull(lfuCache.get(2));
assertEquals("Zeta", lfuCache.get(7));
}
@Test
void testUpdateValueShouldPreserveFrequency() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
lfuCache.put(1, "A");
lfuCache.put(2, "B");
lfuCache.put(3, "C");
assertEquals("A", lfuCache.get(1)); // Accessing key 1
lfuCache.put(4, "D"); // This should evict key 2
assertNull(lfuCache.get(2)); // Key 2 should be evicted
assertEquals("C", lfuCache.get(3)); // Key 3 should still exist
assertEquals("A", lfuCache.get(1)); // Key 1 should still exist
lfuCache.put(1, "Updated A"); // Update the value of key 1
assertEquals("Updated A", lfuCache.get(1)); // Check if the update was successful
}
@Test
void testEvictionPolicyWhenFull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(2);
lfuCache.put(1, "One");
lfuCache.put(2, "Two");
assertEquals("One", lfuCache.get(1)); // Access key 1
lfuCache.put(3, "Three"); // This should evict key 2 (least frequently used)
assertNull(lfuCache.get(2)); // Key 2 should be evicted
assertEquals("One", lfuCache.get(1)); // Key 1 should still exist
assertEquals("Three", lfuCache.get(3)); // Check if key 3 exists
}
@Test
void testGetFromEmptyCacheShouldReturnNull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
assertNull(lfuCache.get(1)); // Should return null as the cache is empty
}
@Test
void testPutNullValueShouldStoreNull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
lfuCache.put(1, null); // Store a null value
assertNull(lfuCache.get(1)); // Should return null
}
@Test
void testInvalidCacheCapacityShouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(0));
assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(-1));
}
@Test
void testMultipleAccessPatterns() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(5);
lfuCache.put(1, "A");
lfuCache.put(2, "B");
lfuCache.put(3, "C");
lfuCache.put(4, "D");
assertEquals("A", lfuCache.get(1)); // Access 1
lfuCache.put(5, "E"); // Should not evict anything yet
lfuCache.put(6, "F"); // Evict B
assertNull(lfuCache.get(2)); // B should be evicted
assertEquals("C", lfuCache.get(3)); // C should still exist
assertEquals("D", lfuCache.get(4)); // D should still exist
assertEquals("A", lfuCache.get(1)); // A should still exist
assertEquals("E", lfuCache.get(5)); // E should exist
assertEquals("F", lfuCache.get(6)); // F should exist
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java | package com.thealgorithms.datastructures.caches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
public class MRUCacheTest {
private static final int SIZE = 5;
@Test
public void putAndGetIntegerValues() {
MRUCache<Integer, Integer> mruCache = new MRUCache<>(SIZE);
for (int i = 0; i < SIZE; i++) {
mruCache.put(i, i);
}
for (int i = 0; i < SIZE; i++) {
assertEquals(i, mruCache.get(i));
}
}
@Test
public void putAndGetStringValues() {
MRUCache<String, String> mruCache = new MRUCache<>(SIZE);
for (int i = 0; i < SIZE; i++) {
mruCache.put("key" + i, "value" + i);
}
for (int i = 0; i < SIZE; i++) {
assertEquals("value" + i, mruCache.get("key" + i));
}
}
@Test
public void nullKeysAndValues() {
MRUCache<Integer, Integer> mruCache = new MRUCache<>(SIZE);
mruCache.put(null, 2);
mruCache.put(6, null);
assertEquals(2, mruCache.get(null));
assertNull(mruCache.get(6));
}
@Test
public void overCapacity() {
MRUCache<Integer, Integer> mruCache = new MRUCache<>(SIZE);
for (int i = 0; i < 10; i++) {
mruCache.put(i, i);
}
// After inserting 10 items, the cache should have evicted the least recently used ones.
assertEquals(9, mruCache.get(9)); // Most recently used
assertEquals(0, mruCache.get(0)); // Least recently used, should be evicted
}
@Test
public void overwriteExistingKey() {
MRUCache<Integer, String> mruCache = new MRUCache<>(SIZE);
mruCache.put(1, "one");
mruCache.put(1, "uno"); // Overwriting the value for key 1
assertEquals("uno", mruCache.get(1));
assertNull(mruCache.get(2)); // Ensure other keys are unaffected
}
@Test
public void evictionOrder() {
MRUCache<Integer, Integer> mruCache = new MRUCache<>(SIZE);
for (int i = 0; i < SIZE; i++) {
mruCache.put(i, i);
}
// Access a key to make it most recently used
mruCache.get(2);
// Add new items to trigger eviction
mruCache.put(5, 5);
mruCache.put(6, 6);
// Key 3 should be evicted since 2 is the most recently used
assertEquals(3, mruCache.get(3));
assertEquals(4, mruCache.get(4)); // Key 4 should still be available
assertEquals(6, mruCache.get(6)); // Key 6 should be available
}
@Test
public void cacheHandlesLargeValues() {
MRUCache<String, String> mruCache = new MRUCache<>(SIZE);
for (int i = 0; i < SIZE; i++) {
mruCache.put("key" + i, "value" + i);
}
// Verify values
for (int i = 0; i < SIZE; i++) {
assertEquals("value" + i, mruCache.get("key" + i));
}
// Add large value
mruCache.put("largeKey", "largeValue");
// Verify eviction of the least recently used (key 0 should be evicted)
assertEquals("value0", mruCache.get("key0"));
assertEquals("largeValue", mruCache.get("largeKey"));
}
@Test
public void testEmptyCacheBehavior() {
MRUCache<Integer, Integer> mruCache = new MRUCache<>(SIZE);
// Verify that accessing any key returns null
assertNull(mruCache.get(1));
assertNull(mruCache.get(100));
// Adding to cache and checking again
mruCache.put(1, 10);
assertEquals(10, mruCache.get(1));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/LRUCacheTest.java | package com.thealgorithms.datastructures.caches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LRUCacheTest {
private static final int SIZE = 5;
private LRUCache<Integer, Integer> cache;
@BeforeEach
void setUp() {
cache = new LRUCache<>(SIZE);
}
@Test
public void testBasicOperations() {
cache.put(1, 100);
assertEquals(100, cache.get(1));
assertNull(cache.get(2));
}
@Test
public void testEvictionPolicy() {
// Fill cache to capacity
for (int i = 0; i < SIZE; i++) {
cache.put(i, i * 100);
}
// Verify all elements are present
for (int i = 0; i < SIZE; i++) {
assertEquals(i * 100, cache.get(i));
}
// Add one more element, causing eviction of least recently used
cache.put(SIZE, SIZE * 100);
// First element should be evicted
assertNull(cache.get(0));
assertEquals(SIZE * 100, cache.get(SIZE));
}
@Test
public void testAccessOrder() {
// Fill cache
for (int i = 0; i < SIZE; i++) {
cache.put(i, i);
}
// Access first element, making it most recently used
cache.get(0);
// Add new element, should evict second element (1)
cache.put(SIZE, SIZE);
assertEquals(0, cache.get(0)); // Should still exist
assertNull(cache.get(1)); // Should be evicted
assertEquals(SIZE, cache.get(SIZE)); // Should exist
}
@Test
public void testUpdateExistingKey() {
cache.put(1, 100);
assertEquals(100, cache.get(1));
// Update existing key
cache.put(1, 200);
assertEquals(200, cache.get(1));
}
@Test
public void testNullValues() {
cache.put(1, null);
assertNull(cache.get(1));
// Update null to non-null
cache.put(1, 100);
assertEquals(100, cache.get(1));
// Update non-null to null
cache.put(1, null);
assertNull(cache.get(1));
}
@Test
public void testStringKeysAndValues() {
LRUCache<String, String> stringCache = new LRUCache<>(SIZE);
stringCache.put("key1", "value1");
stringCache.put("key2", "value2");
assertEquals("value1", stringCache.get("key1"));
assertEquals("value2", stringCache.get("key2"));
}
@Test
public void testLongSequenceOfOperations() {
// Add elements beyond capacity multiple times
for (int i = 0; i < SIZE * 3; i++) {
cache.put(i, i * 100);
// Verify only the last SIZE elements are present
for (int j = Math.max(0, i - SIZE + 1); j <= i; j++) {
assertEquals(j * 100, cache.get(j));
}
// Verify elements before the window are evicted
if (i >= SIZE) {
assertNull(cache.get(i - SIZE));
}
}
}
@Test
void testCustomObjects() {
class TestObject {
private final String value;
TestObject(String value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TestObject) {
return value.equals(((TestObject) obj).value);
}
return false;
}
@Override
public int hashCode() {
return value == null ? 0 : value.hashCode();
}
}
LRUCache<Integer, TestObject> objectCache = new LRUCache<>(SIZE);
TestObject obj1 = new TestObject("test1");
TestObject obj2 = new TestObject("test2");
objectCache.put(1, obj1);
objectCache.put(2, obj2);
assertEquals(obj1, objectCache.get(1));
assertEquals(obj2, objectCache.get(2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/RRCacheTest.java | package com.thealgorithms.datastructures.caches;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
class RRCacheTest {
private RRCache<String, String> cache;
private Set<String> evictedKeys;
private List<String> evictedValues;
@BeforeEach
void setUp() {
evictedKeys = new HashSet<>();
evictedValues = new ArrayList<>();
cache = new RRCache.Builder<String, String>(3)
.defaultTTL(1000)
.random(new Random(0))
.evictionListener((k, v) -> {
evictedKeys.add(k);
evictedValues.add(v);
})
.build();
}
@Test
void testPutAndGet() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
}
@Test
void testOverwriteValue() {
cache.put("a", "apple");
cache.put("a", "avocado");
Assertions.assertEquals("avocado", cache.get("a"));
}
@Test
void testExpiration() throws InterruptedException {
cache.put("temp", "value", 100); // short TTL
Thread.sleep(200);
Assertions.assertNull(cache.get("temp"));
Assertions.assertTrue(evictedKeys.contains("temp"));
}
@Test
void testEvictionOnCapacity() {
cache.put("a", "alpha");
cache.put("b", "bravo");
cache.put("c", "charlie");
cache.put("d", "delta"); // triggers eviction
int size = cache.size();
Assertions.assertEquals(3, size);
Assertions.assertEquals(1, evictedKeys.size());
Assertions.assertEquals(1, evictedValues.size());
}
@Test
void testEvictionListener() {
cache.put("x", "one");
cache.put("y", "two");
cache.put("z", "three");
cache.put("w", "four"); // one of x, y, z will be evicted
Assertions.assertFalse(evictedKeys.isEmpty());
Assertions.assertFalse(evictedValues.isEmpty());
}
@Test
void testHitsAndMisses() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
Assertions.assertNull(cache.get("b"));
Assertions.assertEquals(1, cache.getHits());
Assertions.assertEquals(1, cache.getMisses());
}
@Test
void testSizeExcludesExpired() throws InterruptedException {
cache.put("a", "a", 100);
cache.put("b", "b", 100);
cache.put("c", "c", 100);
Thread.sleep(150);
Assertions.assertEquals(0, cache.size());
}
@Test
void testToStringDoesNotExposeExpired() throws InterruptedException {
cache.put("live", "alive");
cache.put("dead", "gone", 100);
Thread.sleep(150);
String result = cache.toString();
Assertions.assertTrue(result.contains("live"));
Assertions.assertFalse(result.contains("dead"));
}
@Test
void testNullKeyGetThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.get(null));
}
@Test
void testPutNullKeyThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put(null, "v"));
}
@Test
void testPutNullValueThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", null));
}
@Test
void testPutNegativeTTLThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", "v", -1));
}
@Test
void testBuilderNegativeCapacityThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new RRCache.Builder<>(0));
}
@Test
void testBuilderNullRandomThrows() {
RRCache.Builder<String, String> builder = new RRCache.Builder<>(1);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.random(null));
}
@Test
void testBuilderNullEvictionListenerThrows() {
RRCache.Builder<String, String> builder = new RRCache.Builder<>(1);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.evictionListener(null));
}
@Test
void testEvictionListenerExceptionDoesNotCrash() {
RRCache<String, String> listenerCache = new RRCache.Builder<String, String>(1).evictionListener((k, v) -> { throw new RuntimeException("Exception"); }).build();
listenerCache.put("a", "a");
listenerCache.put("b", "b"); // causes eviction but should not crash
Assertions.assertDoesNotThrow(() -> listenerCache.get("a"));
}
@Test
void testTtlZeroThrowsIllegalArgumentException() {
Executable exec = () -> new RRCache.Builder<String, String>(3).defaultTTL(-1).build();
Assertions.assertThrows(IllegalArgumentException.class, exec);
}
@Test
void testPeriodicEvictionStrategyEvictsAtInterval() throws InterruptedException {
RRCache<String, String> periodicCache = new RRCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new RRCache.PeriodicEvictionStrategy<>(3)).build();
periodicCache.put("x", "1");
Thread.sleep(100);
int ev1 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev2 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev3 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
Assertions.assertEquals(0, ev1);
Assertions.assertEquals(0, ev2);
Assertions.assertEquals(1, ev3, "Eviction should happen on the 3rd access");
Assertions.assertEquals(0, periodicCache.size());
}
@Test
void testPeriodicEvictionStrategyThrowsExceptionIfIntervalLessThanOrEqual0() {
Executable executable = () -> new RRCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new RRCache.PeriodicEvictionStrategy<>(0)).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testNoEvictionStrategyEvictsOnEachCall() throws InterruptedException {
RRCache<String, String> noEvictionStrategyCache = new RRCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new RRCache.NoEvictionStrategy<>()).build();
noEvictionStrategyCache.put("x", "1");
Thread.sleep(100);
int evicted = noEvictionStrategyCache.getEvictionStrategy().onAccess(noEvictionStrategyCache);
Assertions.assertEquals(1, evicted);
}
@Test
void testBuilderThrowsExceptionIfEvictionStrategyNull() {
Executable executable = () -> new RRCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(null).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testReturnsCorrectStrategyInstance() {
RRCache.EvictionStrategy<String, String> strategy = new RRCache.NoEvictionStrategy<>();
RRCache<String, String> newCache = new RRCache.Builder<String, String>(10).defaultTTL(1000).evictionStrategy(strategy).build();
Assertions.assertSame(strategy, newCache.getEvictionStrategy(), "Returned strategy should be the same instance");
}
@Test
void testDefaultStrategyIsNoEviction() {
RRCache<String, String> newCache = new RRCache.Builder<String, String>(5).defaultTTL(1000).build();
Assertions.assertTrue(newCache.getEvictionStrategy() instanceof RRCache.PeriodicEvictionStrategy<String, String>, "Default strategy should be NoEvictionStrategy");
}
@Test
void testGetEvictionStrategyIsNotNull() {
RRCache<String, String> newCache = new RRCache.Builder<String, String>(5).build();
Assertions.assertNotNull(newCache.getEvictionStrategy(), "Eviction strategy should never be null");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/FIFOCacheTest.java | package com.thealgorithms.datastructures.caches;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
class FIFOCacheTest {
private FIFOCache<String, String> cache;
private Set<String> evictedKeys;
private List<String> evictedValues;
@BeforeEach
void setUp() {
evictedKeys = new HashSet<>();
evictedValues = new ArrayList<>();
cache = new FIFOCache.Builder<String, String>(3)
.defaultTTL(1000)
.evictionListener((k, v) -> {
evictedKeys.add(k);
evictedValues.add(v);
})
.build();
}
@Test
void testPutAndGet() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
}
@Test
void testOverwriteValue() {
cache.put("a", "apple");
cache.put("a", "avocado");
Assertions.assertEquals("avocado", cache.get("a"));
}
@Test
void testExpiration() throws InterruptedException {
cache.put("temp", "value", 100);
Thread.sleep(200);
Assertions.assertNull(cache.get("temp"));
Assertions.assertTrue(evictedKeys.contains("temp"));
}
@Test
void testEvictionOnCapacity() {
cache.put("a", "alpha");
cache.put("b", "bravo");
cache.put("c", "charlie");
cache.put("d", "delta");
int size = cache.size();
Assertions.assertEquals(3, size);
Assertions.assertEquals(1, evictedKeys.size());
Assertions.assertEquals(1, evictedValues.size());
}
@Test
void testEvictionListener() {
cache.put("x", "one");
cache.put("y", "two");
cache.put("z", "three");
cache.put("w", "four");
Assertions.assertFalse(evictedKeys.isEmpty());
Assertions.assertFalse(evictedValues.isEmpty());
}
@Test
void testHitsAndMisses() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
Assertions.assertNull(cache.get("b"));
Assertions.assertEquals(1, cache.getHits());
Assertions.assertEquals(1, cache.getMisses());
}
@Test
void testSizeExcludesExpired() throws InterruptedException {
cache.put("a", "a", 100);
cache.put("b", "b", 100);
cache.put("c", "c", 100);
Thread.sleep(150);
Assertions.assertEquals(0, cache.size());
}
@Test
void testSizeIncludesFresh() {
cache.put("a", "a", 1000);
cache.put("b", "b", 1000);
cache.put("c", "c", 1000);
Assertions.assertEquals(3, cache.size());
}
@Test
void testToStringDoesNotExposeExpired() throws InterruptedException {
cache.put("live", "alive");
cache.put("dead", "gone", 100);
Thread.sleep(150);
String result = cache.toString();
Assertions.assertTrue(result.contains("live"));
Assertions.assertFalse(result.contains("dead"));
}
@Test
void testNullKeyGetThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.get(null));
}
@Test
void testPutNullKeyThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put(null, "v"));
}
@Test
void testPutNullValueThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", null));
}
@Test
void testPutNegativeTTLThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", "v", -1));
}
@Test
void testBuilderNegativeCapacityThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new FIFOCache.Builder<>(0));
}
@Test
void testBuilderNullEvictionListenerThrows() {
FIFOCache.Builder<String, String> builder = new FIFOCache.Builder<>(1);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.evictionListener(null));
}
@Test
void testEvictionListenerExceptionDoesNotCrash() {
FIFOCache<String, String> listenerCache = new FIFOCache.Builder<String, String>(1).evictionListener((k, v) -> { throw new RuntimeException("Exception"); }).build();
listenerCache.put("a", "a");
listenerCache.put("b", "b");
Assertions.assertDoesNotThrow(() -> listenerCache.get("a"));
}
@Test
void testTtlZeroThrowsIllegalArgumentException() {
Executable exec = () -> new FIFOCache.Builder<String, String>(3).defaultTTL(-1).build();
Assertions.assertThrows(IllegalArgumentException.class, exec);
}
@Test
void testPeriodicEvictionStrategyEvictsAtInterval() throws InterruptedException {
FIFOCache<String, String> periodicCache = new FIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new FIFOCache.PeriodicEvictionStrategy<>(3)).build();
periodicCache.put("x", "1");
Thread.sleep(100);
int ev1 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev2 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev3 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
Assertions.assertEquals(0, ev1);
Assertions.assertEquals(0, ev2);
Assertions.assertEquals(1, ev3, "Eviction should happen on the 3rd access");
Assertions.assertEquals(0, periodicCache.size());
}
@Test
void testPeriodicEvictionStrategyThrowsExceptionIfIntervalLessThanOrEqual0() {
Executable executable = () -> new FIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new FIFOCache.PeriodicEvictionStrategy<>(0)).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testImmediateEvictionStrategyStrategyEvictsOnEachCall() throws InterruptedException {
FIFOCache<String, String> immediateEvictionStrategy = new FIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new FIFOCache.ImmediateEvictionStrategy<>()).build();
immediateEvictionStrategy.put("x", "1");
Thread.sleep(100);
int evicted = immediateEvictionStrategy.getEvictionStrategy().onAccess(immediateEvictionStrategy);
Assertions.assertEquals(1, evicted);
}
@Test
void testBuilderThrowsExceptionIfEvictionStrategyNull() {
Executable executable = () -> new FIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(null).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testReturnsCorrectStrategyInstance() {
FIFOCache.EvictionStrategy<String, String> strategy = new FIFOCache.ImmediateEvictionStrategy<>();
FIFOCache<String, String> newCache = new FIFOCache.Builder<String, String>(10).defaultTTL(1000).evictionStrategy(strategy).build();
Assertions.assertSame(strategy, newCache.getEvictionStrategy(), "Returned strategy should be the same instance");
}
@Test
void testDefaultStrategyIsImmediateEvictionStrategy() {
FIFOCache<String, String> newCache = new FIFOCache.Builder<String, String>(5).defaultTTL(1000).build();
Assertions.assertTrue(newCache.getEvictionStrategy() instanceof FIFOCache.ImmediateEvictionStrategy<String, String>, "Default strategy should be ImmediateEvictionStrategyStrategy");
}
@Test
void testGetEvictionStrategyIsNotNull() {
FIFOCache<String, String> newCache = new FIFOCache.Builder<String, String>(5).build();
Assertions.assertNotNull(newCache.getEvictionStrategy(), "Eviction strategy should never be null");
}
@Test
void testRemoveKeyRemovesExistingKey() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
Assertions.assertEquals("Alpha", cache.get("A"));
Assertions.assertEquals("Beta", cache.get("B"));
String removed = cache.removeKey("A");
Assertions.assertEquals("Alpha", removed);
Assertions.assertNull(cache.get("A"));
Assertions.assertEquals(1, cache.size());
}
@Test
void testRemoveKeyReturnsNullIfKeyNotPresent() {
cache.put("X", "X-ray");
Assertions.assertNull(cache.removeKey("NonExistent"));
Assertions.assertEquals(1, cache.size());
}
@Test
void testRemoveKeyHandlesExpiredEntry() throws InterruptedException {
FIFOCache<String, String> expiringCache = new FIFOCache.Builder<String, String>(2).defaultTTL(100).evictionStrategy(new FIFOCache.ImmediateEvictionStrategy<>()).build();
expiringCache.put("T", "Temporary");
Thread.sleep(200);
String removed = expiringCache.removeKey("T");
Assertions.assertEquals("Temporary", removed);
Assertions.assertNull(expiringCache.get("T"));
}
@Test
void testRemoveKeyThrowsIfKeyIsNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.removeKey(null));
}
@Test
void testRemoveKeyTriggersEvictionListener() {
AtomicInteger evictedCount = new AtomicInteger();
FIFOCache<String, String> localCache = new FIFOCache.Builder<String, String>(2).evictionListener((key, value) -> evictedCount.incrementAndGet()).build();
localCache.put("A", "Apple");
localCache.put("B", "Banana");
localCache.removeKey("A");
Assertions.assertEquals(1, evictedCount.get(), "Eviction listener should have been called once");
}
@Test
void testRemoveKeyDoestNotAffectOtherKeys() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("C", "Gamma");
cache.removeKey("B");
Assertions.assertEquals("Alpha", cache.get("A"));
Assertions.assertNull(cache.get("B"));
Assertions.assertEquals("Gamma", cache.get("C"));
}
@Test
void testEvictionListenerExceptionDoesNotPropagate() {
FIFOCache<String, String> localCache = new FIFOCache.Builder<String, String>(1).evictionListener((key, value) -> { throw new RuntimeException(); }).build();
localCache.put("A", "Apple");
Assertions.assertDoesNotThrow(() -> localCache.put("B", "Beta"));
}
@Test
void testGetKeysReturnsAllFreshKeys() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma");
Set<String> expectedKeys = Set.of("A", "B", "G");
Assertions.assertEquals(expectedKeys, cache.getAllKeys());
}
@Test
void testGetKeysIgnoresExpiredKeys() throws InterruptedException {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma", 100);
Set<String> expectedKeys = Set.of("A", "B");
Thread.sleep(200);
Assertions.assertEquals(expectedKeys, cache.getAllKeys());
}
@Test
void testClearRemovesAllEntries() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma");
cache.clear();
Assertions.assertEquals(0, cache.size());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.