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/maths/ConvolutionFFTTest.java | src/test/java/com/thealgorithms/maths/ConvolutionFFTTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class ConvolutionFFTTest {
/**
* Helper method to create a complex signal from an array of doubles.
*/
private ArrayList<FFT.Complex> createComplexSignal(double[] values) {
ArrayList<FFT.Complex> signal = new ArrayList<>();
for (double value : values) {
signal.add(new FFT.Complex(value, 0));
}
return signal;
}
/**
* Helper method to compare two complex signals for equality within a small margin of error.
*/
private void assertComplexArrayEquals(List<FFT.Complex> expected, List<FFT.Complex> result, double delta) {
assertEquals(expected.size(), result.size(), "Signal lengths are not equal.");
for (int i = 0; i < expected.size(); i++) {
FFT.Complex expectedValue = expected.get(i);
FFT.Complex resultValue = result.get(i);
assertEquals(expectedValue.real(), resultValue.real(), delta, "Real part mismatch at index " + i);
assertEquals(expectedValue.imaginary(), resultValue.imaginary(), delta, "Imaginary part mismatch at index " + i);
}
}
@ParameterizedTest(name = "Test case {index}: {3}")
@MethodSource("provideTestCases")
public void testConvolutionFFT(double[] a, double[] b, double[] expectedOutput, String testDescription) {
ArrayList<FFT.Complex> signalA = createComplexSignal(a);
ArrayList<FFT.Complex> signalB = createComplexSignal(b);
ArrayList<FFT.Complex> expected = createComplexSignal(expectedOutput);
ArrayList<FFT.Complex> result = ConvolutionFFT.convolutionFFT(signalA, signalB);
assertComplexArrayEquals(expected, result, 1e-9); // Allow small margin of error
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new double[] {1, 2, 3}, new double[] {4, 5, 6}, new double[] {4, 13, 28, 27, 18}, "Basic test"), Arguments.of(new double[] {0, 0, 0}, new double[] {1, 2, 3}, new double[] {0, 0, 0, 0, 0}, "Test with zero elements"),
Arguments.of(new double[] {1, 2}, new double[] {3, 4, 5}, new double[] {3, 10, 13, 10}, "Test with different sizes"), Arguments.of(new double[] {5}, new double[] {2}, new double[] {10}, "Test with single element"),
Arguments.of(new double[] {1, -2, 3}, new double[] {-1, 2, -3}, new double[] {-1, 4, -10, 12, -9}, "Test with negative values"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/GermainPrimeAndSafePrimeTest.java | src/test/java/com/thealgorithms/maths/GermainPrimeAndSafePrimeTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class GermainPrimeAndSafePrimeTest {
static Stream<Arguments> provideNumbersForGermainPrimes() {
return Stream.of(Arguments.of(2, Boolean.TRUE), Arguments.of(3, Boolean.TRUE), Arguments.of(5, Boolean.TRUE), Arguments.of(11, Boolean.TRUE), Arguments.of(23, Boolean.TRUE), Arguments.of(293, Boolean.TRUE), Arguments.of(4, Boolean.FALSE), Arguments.of(7, Boolean.FALSE),
Arguments.of(9, Boolean.FALSE), Arguments.of(1, Boolean.FALSE));
}
static Stream<Arguments> provideNumbersForSafePrimes() {
return Stream.of(Arguments.of(5, Boolean.TRUE), Arguments.of(7, Boolean.TRUE), Arguments.of(11, Boolean.TRUE), Arguments.of(23, Boolean.TRUE), Arguments.of(1283, Boolean.TRUE), Arguments.of(4, Boolean.FALSE), Arguments.of(13, Boolean.FALSE), Arguments.of(9, Boolean.FALSE),
Arguments.of(1, Boolean.FALSE));
}
static Stream<Integer> provideNegativeNumbers() {
return Stream.of(-10, -1, 0);
}
@ParameterizedTest
@MethodSource("provideNumbersForGermainPrimes")
@DisplayName("Check whether a number is a Germain prime")
void testValidGermainPrimes(int number, boolean expected) {
assertEquals(expected, GermainPrimeAndSafePrime.isGermainPrime(number));
}
@ParameterizedTest
@MethodSource("provideNumbersForSafePrimes")
@DisplayName("Check whether a number is a Safe prime")
void testValidSafePrimes(int number, boolean expected) {
assertEquals(expected, GermainPrimeAndSafePrime.isSafePrime(number));
}
@ParameterizedTest
@MethodSource("provideNegativeNumbers")
@DisplayName("Negative numbers and zero should throw IllegalArgumentException")
void testNegativeNumbersThrowException(int number) {
assertThrows(IllegalArgumentException.class, () -> GermainPrimeAndSafePrime.isGermainPrime(number));
assertThrows(IllegalArgumentException.class, () -> GermainPrimeAndSafePrime.isSafePrime(number));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/EulerMethodTest.java | src/test/java/com/thealgorithms/maths/EulerMethodTest.java | package com.thealgorithms.maths;
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 java.util.ArrayList;
import java.util.function.BiFunction;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class EulerMethodTest {
private static class EulerFullTestCase {
double[] params;
BiFunction<Double, Double, Double> equation;
int expectedSize;
double[] expectedFirstPoint;
double[] expectedLastPoint;
EulerFullTestCase(double[] params, BiFunction<Double, Double, Double> equation, int expectedSize, double[] expectedFirstPoint, double[] expectedLastPoint) {
this.params = params;
this.equation = equation;
this.expectedSize = expectedSize;
this.expectedFirstPoint = expectedFirstPoint;
this.expectedLastPoint = expectedLastPoint;
}
}
@ParameterizedTest
@MethodSource("eulerStepTestCases")
void testEulerStep(double x, double h, double y, BiFunction<Double, Double, Double> equation, double expected) {
double result = EulerMethod.eulerStep(x, h, y, equation);
assertEquals(expected, result, 1e-9, "Euler step failed for the given equation.");
}
static Stream<Arguments> eulerStepTestCases() {
return Stream.of(Arguments.of(0.0, 0.1, 1.0, (BiFunction<Double, Double, Double>) ((x, y) -> x + y), 1.1));
}
@ParameterizedTest
@MethodSource("eulerStepInvalidCases")
void testEulerStepInvalidInput(double x, double h, double y, BiFunction<Double, Double, Double> equation, Class<? extends Exception> expectedExceptionClass) {
assertThrows(expectedExceptionClass, () -> EulerMethod.eulerStep(x, h, y, equation));
}
static Stream<Arguments> eulerStepInvalidCases() {
BiFunction<Double, Double, Double> dummyEquation = (x, y) -> x + y;
return Stream.of(Arguments.of(0.0, -0.1, 1.0, dummyEquation, IllegalArgumentException.class), Arguments.of(0.0, 0.0, 1.0, dummyEquation, IllegalArgumentException.class));
}
@ParameterizedTest
@MethodSource("eulerFullTestCases")
void testEulerFull(EulerFullTestCase testCase) {
ArrayList<double[]> result = EulerMethod.eulerFull(testCase.params[0], testCase.params[1], testCase.params[2], testCase.params[3], testCase.equation);
assertEquals(testCase.expectedSize, result.size(), "Incorrect number of points in the result.");
assertArrayEquals(testCase.expectedFirstPoint, result.get(0), 1e-9, "Incorrect first point.");
assertArrayEquals(testCase.expectedLastPoint, result.get(result.size() - 1), 1e-9, "Incorrect last point.");
}
static Stream<Arguments> eulerFullTestCases() {
return Stream.of(Arguments.of(new EulerFullTestCase(new double[] {0.0, 1.0, 0.5, 0.0}, (x, y) -> x, 3, new double[] {0.0, 0.0}, new double[] {1.0, 0.25})),
Arguments.of(new EulerFullTestCase(new double[] {0.0, 1.0, 0.1, 1.0}, (x, y) -> y, 12, new double[] {0.0, 1.0}, new double[] {1.0999999999999999, 2.8531167061100002})),
Arguments.of(new EulerFullTestCase(new double[] {0.0, 0.1, 0.1, 1.0}, (x, y) -> x + y, 2, new double[] {0.0, 1.0}, new double[] {0.1, 1.1})));
}
@ParameterizedTest
@MethodSource("eulerFullInvalidCases")
void testEulerFullInvalidInput(double xStart, double xEnd, double stepSize, double yInitial, BiFunction<Double, Double, Double> equation, Class<? extends Exception> expectedExceptionClass) {
assertThrows(expectedExceptionClass, () -> EulerMethod.eulerFull(xStart, xEnd, stepSize, yInitial, equation));
}
static Stream<Arguments> eulerFullInvalidCases() {
BiFunction<Double, Double, Double> dummyEquation = (x, y) -> x + y;
return Stream.of(Arguments.of(1.0, 0.0, 0.1, 1.0, dummyEquation, IllegalArgumentException.class), Arguments.of(0.0, 1.0, 0.0, 1.0, dummyEquation, IllegalArgumentException.class), Arguments.of(0.0, 1.0, -0.1, 1.0, dummyEquation, IllegalArgumentException.class));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java | src/test/java/com/thealgorithms/maths/PerfectNumberTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class PerfectNumberTest {
@Test
public void perfectNumber() {
int[] trueTestCases = {6, 28, 496, 8128, 33550336};
int[] falseTestCases = {-6, 0, 1, 9, 123};
for (Integer n : trueTestCases) {
assertTrue(PerfectNumber.isPerfectNumber(n));
assertTrue(PerfectNumber.isPerfectNumber2(n));
}
for (Integer n : falseTestCases) {
assertFalse(PerfectNumber.isPerfectNumber(n));
assertFalse(PerfectNumber.isPerfectNumber2(n));
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/PerfectCubeTest.java | src/test/java/com/thealgorithms/maths/PerfectCubeTest.java | package com.thealgorithms.maths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class PerfectCubeTest {
@Test
public void perfectCube() {
Assertions.assertTrue(PerfectCube.isPerfectCube(-27));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(-27));
Assertions.assertTrue(PerfectCube.isPerfectCube(-1));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(-1));
Assertions.assertTrue(PerfectCube.isPerfectCube(0));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(0));
Assertions.assertTrue(PerfectCube.isPerfectCube(1));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(1));
Assertions.assertTrue(PerfectCube.isPerfectCube(8));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(8));
Assertions.assertTrue(PerfectCube.isPerfectCube(27));
Assertions.assertTrue(PerfectCube.isPerfectCubeMathCbrt(27));
Assertions.assertFalse(PerfectCube.isPerfectCube(-9));
Assertions.assertFalse(PerfectCube.isPerfectCubeMathCbrt(-9));
Assertions.assertFalse(PerfectCube.isPerfectCube(2));
Assertions.assertFalse(PerfectCube.isPerfectCubeMathCbrt(2));
Assertions.assertFalse(PerfectCube.isPerfectCube(4));
Assertions.assertFalse(PerfectCube.isPerfectCubeMathCbrt(4));
Assertions.assertFalse(PerfectCube.isPerfectCube(30));
Assertions.assertFalse(PerfectCube.isPerfectCubeMathCbrt(30));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/FindMaxTest.java | src/test/java/com/thealgorithms/maths/FindMaxTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class FindMaxTest {
@ParameterizedTest
@MethodSource("inputStream")
void numberTests(int expected, int[] input) {
Assertions.assertEquals(expected, FindMax.findMax(input));
}
private static Stream<Arguments> inputStream() {
return Stream.of(Arguments.of(10, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}));
}
@Test
public void testFindMaxThrowsExceptionForEmptyInput() {
assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(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/maths/NevilleTest.java | src/test/java/com/thealgorithms/maths/NevilleTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class NevilleTest {
@Test
public void testInterpolateLinear() {
// Test with a simple linear function y = 2x + 1
// Points (0, 1) and (2, 5)
double[] x = {0, 2};
double[] y = {1, 5};
// We want to find y when x = 1, which should be 3
double target = 1;
double expected = 3.0;
assertEquals(expected, Neville.interpolate(x, y, target), 1e-9);
}
@Test
public void testInterpolateQuadratic() {
// Test with a quadratic function y = x^2
// Points (0, 0), (1, 1), (3, 9)
double[] x = {0, 1, 3};
double[] y = {0, 1, 9};
// We want to find y when x = 2, which should be 4
double target = 2;
double expected = 4.0;
assertEquals(expected, Neville.interpolate(x, y, target), 1e-9);
}
@Test
public void testInterpolateWithNegativeNumbers() {
// Test with y = x^2 - 2x + 1
// Points (-1, 4), (0, 1), (2, 1)
double[] x = {-1, 0, 2};
double[] y = {4, 1, 1};
// We want to find y when x = 1, which should be 0
double target = 1;
double expected = 0.0;
assertEquals(expected, Neville.interpolate(x, y, target), 1e-9);
}
@Test
public void testMismatchedArrayLengths() {
double[] x = {1, 2};
double[] y = {1};
double target = 1.5;
assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target));
}
@Test
public void testEmptyArrays() {
double[] x = {};
double[] y = {};
double target = 1;
assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target));
}
@Test
public void testDuplicateXCoordinates() {
double[] x = {1, 2, 1};
double[] y = {5, 8, 3};
double target = 1.5;
assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java | src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.thealgorithms.maths.Prime.SquareFreeInteger;
import java.util.List;
import org.junit.jupiter.api.Test;
class SquareFreeIntegerTest {
@Test
void testIsSquareFreeInteger() {
// given
List<Integer> listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101,
102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194,
195, 197, 199, 201, 202, 203, 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286,
287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, 377, 379, 381, 382, 383, 385,
386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471,
473, 474, 478, 479, 481, 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, 569,
570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, 653, 654, 655, 658, 659, 661, 662,
663, 665, 667, 669, 670, 671, 673, 674, 677, 678, 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757,
758, 759, 761, 762, 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, 851, 853,
854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, 934, 935, 937, 938, 939, 941, 942, 943,
946, 947, 949, 951, 953, 955, 957, 958, 959, 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033,
1034, 1037, 1038, 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, 1110, 1111, 1113,
1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190,
1191, 1193, 1194, 1195, 1198, 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, 1266,
1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, 1335, 1337, 1338, 1339, 1342, 1343, 1345,
1346, 1347, 1349, 1351, 1353, 1354, 1355, 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419,
1423, 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, 1495, 1497, 1498, 1499, 1501,
1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579,
1581, 1582, 1583, 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, 1654, 1655, 1657,
1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742,
1743, 1745, 1747, 1749, 1751, 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, 1822,
1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, 1894, 1895, 1897, 1898, 1901, 1902, 1903,
1905, 1906, 1907, 1909, 1910, 1913, 1914, 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982,
1983, 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, 2053, 2054, 2055, 2059, 2062,
2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138,
2139, 2141, 2143, 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, 2215, 2217, 2218,
2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294,
2297, 2298, 2301, 2302, 2305, 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, 2374,
2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, 2442, 2443, 2445, 2446, 2447, 2449, 2451,
2453, 2454, 2455, 2458, 2459, 2461, 2462, 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498);
for (int i = 1; i <= 2500; i++) {
// when
boolean isNumberSquareFree = SquareFreeInteger.isSquareFreeInteger(i);
boolean isNumberPresentInList = listOfSquareFreeIntegers.contains(i);
// then
assertEquals(isNumberSquareFree, isNumberPresentInList);
}
}
@Test
void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() {
// given
int number = 0;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
@Test
void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() {
// given
int number = -1;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java | src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class CollatzConjectureTest {
static CollatzConjecture cConjecture;
@BeforeAll
static void setUp() {
cConjecture = new CollatzConjecture();
}
@Test
void nextNumberFromEvenNumber() {
assertEquals(25, cConjecture.nextNumber(50));
}
@Test
void nextNumberFromOddNumber() {
assertEquals(154, cConjecture.nextNumber(51));
}
@Test
void collatzConjecture() {
final List<Integer> expected = List.of(35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1);
assertIterableEquals(expected, cConjecture.collatzConjecture(35));
}
@Test
void sequenceOfNotNaturalFirstNumber() {
assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(0));
assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(-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/maths/PiApproximationTest.java | src/test/java/com/thealgorithms/maths/PiApproximationTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class PiApproximationTest {
private static final double DELTA = 0.5; // Tolerance for Pi approximation
private static final double TIGHT_DELTA = 0.1; // Tighter tolerance for large samples
/**
* Test with known points that are all inside the quarter circle.
*/
@Test
public void testAllPointsInside() {
List<PiApproximation.Point> points = new ArrayList<>();
points.add(new PiApproximation.Point(0.0, 0.0)); // Origin
points.add(new PiApproximation.Point(0.5, 0.5)); // Inside
points.add(new PiApproximation.Point(0.3, 0.3)); // Inside
double result = PiApproximation.approximatePi(points);
// All points inside, so result should be 4.0
assertEquals(4.0, result, 0.001);
}
/**
* Test with known points that are all outside the quarter circle.
*/
@Test
public void testAllPointsOutside() {
List<PiApproximation.Point> points = new ArrayList<>();
points.add(new PiApproximation.Point(1.0, 1.0)); // Corner - outside
points.add(new PiApproximation.Point(0.9, 0.9)); // Outside
double result = PiApproximation.approximatePi(points);
// No points inside, so result should be 0.0
assertEquals(0.0, result, 0.001);
}
/**
* Test with mixed points (some inside, some outside).
*/
@Test
public void testMixedPoints() {
List<PiApproximation.Point> points = new ArrayList<>();
// Inside points
points.add(new PiApproximation.Point(0.0, 0.0));
points.add(new PiApproximation.Point(0.5, 0.5));
// Outside points
points.add(new PiApproximation.Point(1.0, 1.0));
points.add(new PiApproximation.Point(0.9, 0.9));
double result = PiApproximation.approximatePi(points);
// 2 out of 4 points inside: 4 * 2/4 = 2.0
assertEquals(2.0, result, 0.001);
}
/**
* Test with boundary point (on the circle).
*/
@Test
public void testBoundaryPoint() {
List<PiApproximation.Point> points = new ArrayList<>();
points.add(new PiApproximation.Point(1.0, 0.0)); // On circle: x² + y² = 1
points.add(new PiApproximation.Point(0.0, 1.0)); // On circle
double result = PiApproximation.approximatePi(points);
// Boundary points should be counted as inside (≤ 1)
assertEquals(4.0, result, 0.001);
}
/**
* Test with small random sample (moderate accuracy expected).
*/
@Test
public void testSmallRandomSample() {
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(1000);
double result = PiApproximation.approximatePi(points);
// With 1000 points, result should be reasonably close to π
assertEquals(Math.PI, result, DELTA);
}
/**
* Test with large random sample (better accuracy expected).
*/
@Test
public void testLargeRandomSample() {
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(100000);
double result = PiApproximation.approximatePi(points);
// With 100000 points, result should be very close to π
assertEquals(Math.PI, result, TIGHT_DELTA);
}
/**
* Test that result is always positive.
*/
@Test
public void testResultIsPositive() {
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(1000);
double result = PiApproximation.approximatePi(points);
assertTrue(result >= 0, "Pi approximation should be positive");
}
/**
* Test that result is bounded (0 ≤ result ≤ 4).
*/
@Test
public void testResultIsBounded() {
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(1000);
double result = PiApproximation.approximatePi(points);
assertTrue(result >= 0 && result <= 4, "Pi approximation should be between 0 and 4");
}
/**
* Test with single point inside.
*/
@Test
public void testSinglePointInside() {
List<PiApproximation.Point> points = new ArrayList<>();
points.add(new PiApproximation.Point(0.0, 0.0));
double result = PiApproximation.approximatePi(points);
assertEquals(4.0, result, 0.001);
}
/**
* Test with single point outside.
*/
@Test
public void testSinglePointOutside() {
List<PiApproximation.Point> points = new ArrayList<>();
points.add(new PiApproximation.Point(1.0, 1.0));
double result = PiApproximation.approximatePi(points);
assertEquals(0.0, result, 0.001);
}
/**
* Test that generated points are within valid range [0, 1].
*/
@Test
public void testGeneratedPointsInRange() {
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(100);
for (PiApproximation.Point p : points) {
assertTrue(p.x >= 0 && p.x <= 1, "X coordinate should be between 0 and 1");
assertTrue(p.y >= 0 && p.y <= 1, "Y coordinate should be between 0 and 1");
}
}
/**
* Test that the correct number of points are generated.
*/
@Test
public void testCorrectNumberOfPointsGenerated() {
int expectedSize = 500;
List<PiApproximation.Point> points = PiApproximation.generateRandomPoints(expectedSize);
assertEquals(expectedSize, points.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/maths/JugglerSequenceTest.java | src/test/java/com/thealgorithms/maths/JugglerSequenceTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
class JugglerSequenceTest {
@Test
void testJugglerSequenceWithThree() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
JugglerSequence.jugglerSequence(3);
assertEquals("3,5,11,36,6,2,1\n", outContent.toString());
}
@Test
void testJugglerSequenceWithTwo() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
JugglerSequence.jugglerSequence(2);
assertEquals("2,1\n", outContent.toString());
}
@Test
void testJugglerSequenceWithNine() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
JugglerSequence.jugglerSequence(9);
assertEquals("9,27,140,11,36,6,2,1\n", outContent.toString());
}
@Test
void testJugglerSequenceWithOne() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
JugglerSequence.jugglerSequence(1);
assertEquals("1\n", outContent.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/maths/SumWithoutArithmeticOperatorsTest.java | src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SumWithoutArithmeticOperatorsTest {
SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators();
@Test
void addZerotoZero() {
assertEquals(0, obj.getSum(0, 0));
}
@Test
void addZerotoNumber() {
assertEquals(5, obj.getSum(0, 5));
assertEquals(28, obj.getSum(28, 0));
}
@Test
void addOddtoEven() {
assertEquals(13, obj.getSum(3, 10));
assertEquals(55, obj.getSum(49, 6));
}
@Test
void addEventoOdd() {
assertEquals(13, obj.getSum(10, 3));
assertEquals(41, obj.getSum(40, 1));
}
@Test
void addRandoms() {
assertEquals(88, obj.getSum(44, 44));
assertEquals(370, obj.getSum(100, 270));
assertEquals(3, obj.getSum(1, 2));
assertEquals(5, obj.getSum(2, 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/maths/ReverseNumberTest.java | src/test/java/com/thealgorithms/maths/ReverseNumberTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
public class ReverseNumberTest {
@ParameterizedTest
@CsvSource({"0, 0", "1, 1", "10, 1", "123, 321", "7890, 987"})
public void testReverseNumber(int input, int expected) {
assertEquals(expected, ReverseNumber.reverseNumber(input));
}
@ParameterizedTest
@ValueSource(ints = {-1, -123, -7890})
public void testReverseNumberThrowsExceptionForNegativeInput(int input) {
assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(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/maths/GCDRecursionTest.java | src/test/java/com/thealgorithms/maths/GCDRecursionTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
public class GCDRecursionTest {
@ParameterizedTest
@CsvSource({"7, 5, 1", "9, 12, 3", "18, 24, 6", "36, 60, 12"})
void testGcdPositiveNumbers(int a, int b, int expectedGcd) {
assertEquals(expectedGcd, GCDRecursion.gcd(a, b));
}
@ParameterizedTest
@CsvSource({"0, 5, 5", "8, 0, 8"})
void testGcdOneZero(int a, int b, int expectedGcd) {
assertEquals(expectedGcd, GCDRecursion.gcd(a, b));
}
@Test
void testGcdBothZero() {
assertEquals(0, GCDRecursion.gcd(0, 0));
}
@ParameterizedTest
@ValueSource(ints = {-5, -15})
void testGcdNegativeNumbers(int negativeValue) {
assertThrows(ArithmeticException.class, () -> GCDRecursion.gcd(negativeValue, 15));
assertThrows(ArithmeticException.class, () -> GCDRecursion.gcd(15, negativeValue));
}
@ParameterizedTest
@CsvSource({"5, 5, 5", "8, 8, 8"})
void testGcdWithSameNumbers(int a, int b, int expectedGcd) {
assertEquals(expectedGcd, GCDRecursion.gcd(a, b));
}
@ParameterizedTest
@CsvSource({"7, 13, 1", "11, 17, 1"})
void testGcdWithPrimeNumbers(int a, int b, int expectedGcd) {
assertEquals(expectedGcd, GCDRecursion.gcd(a, 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/maths/CeilTest.java | src/test/java/com/thealgorithms/maths/CeilTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
public class CeilTest {
@ParameterizedTest
@CsvSource({"7.057, 8", "7.004, 8", "-13.004, -13", "0.98, 1", "-11.357, -11"})
void testCeil(double input, int expected) {
assertEquals(expected, Ceil.ceil(input));
}
@ParameterizedTest
@MethodSource("edgeCaseProvider")
void testEdgeCases(TestData data) {
assertEquals(Ceil.ceil(data.input), data.expected);
}
record TestData(double input, double expected) {
}
static Stream<TestData> edgeCaseProvider() {
return Stream.of(new TestData(Double.MAX_VALUE, Double.MAX_VALUE), new TestData(Double.MIN_VALUE, Math.ceil(Double.MIN_VALUE)), new TestData(0.0, Math.ceil(0.0)), new TestData(-0.0, Math.ceil(-0.0)), new TestData(Double.NaN, Math.ceil(Double.NaN)),
new TestData(Double.NEGATIVE_INFINITY, Math.ceil(Double.NEGATIVE_INFINITY)), new TestData(Double.POSITIVE_INFINITY, Math.ceil(Double.POSITIVE_INFINITY)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/AutoCorrelationTest.java | src/test/java/com/thealgorithms/maths/AutoCorrelationTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* Test class for AutoCorrelation class
*
* @author Athina-Frederiki Swinkels
* @version 2.0
*/
public class AutoCorrelationTest {
@ParameterizedTest
@CsvSource({"1;2;1;1, 1;3;5;7;5;3;1", "1;2;3, 3;8;14;8;3", "1.5;2.3;3.1;4.2, 6.3;14.31;23.6;34.79;23.6;14.31;6.3"})
public void testAutoCorrelationParameterized(String input, String expected) {
double[] array = convertStringToArray(input);
double[] expectedResult = convertStringToArray(expected);
double[] result = AutoCorrelation.autoCorrelation(array);
assertArrayEquals(expectedResult, result, 0.0001);
}
private double[] convertStringToArray(String input) {
String[] elements = input.split(";");
double[] result = new double[elements.length];
for (int i = 0; i < elements.length; i++) {
result[i] = Double.parseDouble(elements[i]);
}
return 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/maths/FindMaxRecursionTest.java | src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class FindMaxRecursionTest {
@ParameterizedTest
@MethodSource("inputStream")
void numberTests(int expected, int[] input) {
Assertions.assertEquals(expected, FindMaxRecursion.max(input));
}
private static Stream<Arguments> inputStream() {
return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3}));
}
@Test
public void testFindMaxThrowsExceptionForEmptyInput() {
assertThrows(IllegalArgumentException.class, () -> FindMaxRecursion.max(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/maths/GCDTest.java | src/test/java/com/thealgorithms/maths/GCDTest.java | package com.thealgorithms.maths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class GCDTest {
@Test
void testNegativeAndZeroThrowsException() {
Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1, 0));
}
@Test
void testPositiveAndNegativeThrowsException() {
Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2));
}
@Test
void testBothNegativeThrowsException() {
Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3));
}
@Test
void testZeroAndPositiveReturnsPositive() {
Assertions.assertEquals(2, GCD.gcd(0, 2));
}
@Test
void testPositiveAndZeroReturnsPositive() {
Assertions.assertEquals(10, GCD.gcd(10, 0));
}
@Test
void testOneAndZeroReturnsOne() {
Assertions.assertEquals(1, GCD.gcd(1, 0));
}
@Test
void testTwoPositiveNumbers() {
Assertions.assertEquals(3, GCD.gcd(9, 6));
}
@Test
void testMultipleArgumentsGcd() {
Assertions.assertEquals(6, GCD.gcd(48, 18, 30, 12));
}
@Test
void testArrayInputGcd() {
Assertions.assertEquals(3, GCD.gcd(new int[] {9, 6}));
}
@Test
void testArrayWithCommonFactor() {
Assertions.assertEquals(5, GCD.gcd(new int[] {2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}));
}
@Test
void testEmptyArrayReturnsZero() {
Assertions.assertEquals(0, GCD.gcd(new int[] {}));
}
@Test
void testSameNumbers() {
Assertions.assertEquals(7, GCD.gcd(7, 7));
}
@Test
void testPrimeNumbersHaveGcdOne() {
Assertions.assertEquals(1, GCD.gcd(13, 17));
}
@Test
void testSingleElementArrayReturnsElement() {
Assertions.assertEquals(42, GCD.gcd(new int[] {42}));
}
@Test
void testLargeNumbers() {
Assertions.assertEquals(12, GCD.gcd(123456, 789012));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java | src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class AbsoluteValueTest {
@Test
void testGetAbsValue() {
Stream.generate(() -> ThreadLocalRandom.current().nextInt()).limit(1000).forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number)));
}
@Test
void testZero() {
assertEquals(0, AbsoluteValue.getAbsValue(0));
}
@Test
void testPositiveNumbers() {
assertEquals(5, AbsoluteValue.getAbsValue(5));
assertEquals(123456, AbsoluteValue.getAbsValue(123456));
assertEquals(Integer.MAX_VALUE, AbsoluteValue.getAbsValue(Integer.MAX_VALUE));
}
@Test
void testNegativeNumbers() {
assertEquals(5, AbsoluteValue.getAbsValue(-5));
assertEquals(123456, AbsoluteValue.getAbsValue(-123456));
assertEquals(Integer.MAX_VALUE, AbsoluteValue.getAbsValue(-Integer.MAX_VALUE));
}
@Test
void testMinIntEdgeCase() {
assertEquals(Integer.MIN_VALUE, AbsoluteValue.getAbsValue(Integer.MIN_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/maths/NumberOfDigitsTest.java | src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.function.IntFunction;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings({"rawtypes", "unchecked"})
public class NumberOfDigitsTest {
@ParameterizedTest
@MethodSource("testCases")
void testNumberOfDigits(final int expected, final int number, final IntFunction<Integer> methodUnderTest) {
assertEquals(expected, methodUnderTest.apply(number));
assertEquals(expected, methodUnderTest.apply(-number));
}
private static Stream<Arguments> testCases() {
final Integer[][] inputs = new Integer[][] {
{3, 100},
{1, 0},
{2, 12},
{3, 123},
{4, 1234},
{5, 12345},
{6, 123456},
{7, 1234567},
{8, 12345678},
{9, 123456789},
{9, 987654321},
};
final IntFunction<Integer>[] methods = new IntFunction[] {NumberOfDigits::numberOfDigits, NumberOfDigits::numberOfDigitsFast, NumberOfDigits::numberOfDigitsFaster, NumberOfDigits::numberOfDigitsRecursion};
return Stream.of(inputs).flatMap(input -> Stream.of(methods).map(method -> Arguments.of(input[0], input[1], method)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java | src/test/java/com/thealgorithms/maths/TwinPrimeTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TwinPrimeTest {
@Test
void shouldReturn7() {
// given
int number = 5;
int expectedResult = 7;
// when
int actualResult = TwinPrime.getTwinPrime(number);
// then
assertEquals(expectedResult, actualResult);
}
@Test
void shouldReturn5() {
// given
int number = 3;
int expectedResult = 5;
// when
int actualResult = TwinPrime.getTwinPrime(number);
// then
assertEquals(expectedResult, actualResult);
}
@Test
void shouldReturnNegative1() {
// given
int number = 4;
int expectedResult = -1;
// when
int actualResult = TwinPrime.getTwinPrime(number);
// then
assertEquals(expectedResult, actualResult);
}
@Test
void shouldReturn19() {
// given
int number = 17;
int expectedResult = 19;
// when
int actualResult = TwinPrime.getTwinPrime(number);
// then
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/maths/GoldbachConjectureTest.java | src/test/java/com/thealgorithms/maths/GoldbachConjectureTest.java | package com.thealgorithms.maths;
import static com.thealgorithms.maths.GoldbachConjecture.getPrimeSum;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class GoldbachConjectureTest {
@Test
void testValidEvenNumbers() {
assertEquals(new GoldbachConjecture.Result(3, 7), getPrimeSum(10)); // 10 = 3 + 7
assertEquals(new GoldbachConjecture.Result(5, 7), getPrimeSum(12)); // 12 = 5 + 7
assertEquals(new GoldbachConjecture.Result(3, 11), getPrimeSum(14)); // 14 = 3 + 11
assertEquals(new GoldbachConjecture.Result(5, 13), getPrimeSum(18)); // 18 = 5 + 13
}
@Test
void testInvalidOddNumbers() {
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(7));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(15));
}
@Test
void testLesserThanTwo() {
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(1));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(2));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-5));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-26));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java | src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java | package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class AbsoluteMinTest {
@Test
void testGetMinValue() {
assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16));
assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2));
}
@Test
void testGetMinValueWithNoArguments() {
Exception exception = assertThrows(IllegalArgumentException.class, AbsoluteMin::getMinValue);
assertEquals("Numbers array cannot be empty", exception.getMessage());
}
@Test
void testGetMinValueWithSameAbsoluteValues() {
assertEquals(-5, AbsoluteMin.getMinValue(-5, 5));
assertEquals(-5, AbsoluteMin.getMinValue(5, -5));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/prime/PrimeCheckTest.java | src/test/java/com/thealgorithms/maths/prime/PrimeCheckTest.java | package com.thealgorithms.maths.prime;
import com.thealgorithms.maths.Prime.PrimeCheck;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PrimeCheckTest {
@Test
void test1() {
Assertions.assertTrue(PrimeCheck.isPrime(2));
}
@Test
void test2() {
Assertions.assertFalse(PrimeCheck.isPrime(-1));
}
@Test
void test3() {
Assertions.assertFalse(PrimeCheck.isPrime(4));
}
@Test
void test4() {
Assertions.assertTrue(PrimeCheck.isPrime(5));
}
@Test
void test5() {
Assertions.assertFalse(PrimeCheck.isPrime(15));
}
@Test
void test6() {
Assertions.assertTrue(PrimeCheck.isPrime(11));
}
@Test
void test7() {
Assertions.assertFalse(PrimeCheck.isPrime(49));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/prime/LiouvilleLambdaFunctionTest.java | src/test/java/com/thealgorithms/maths/prime/LiouvilleLambdaFunctionTest.java | package com.thealgorithms.maths.prime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.thealgorithms.maths.Prime.LiouvilleLambdaFunction;
import org.junit.jupiter.api.Test;
class LiouvilleLambdaFunctionTest {
@Test
void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() {
// given
int number = 0;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
@Test
void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() {
// given
int number = -1;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
@Test
void testLiouvilleLambdaMustReturnNegativeOne() {
// given
int number = 11;
int expectedOutput = -1;
// when
int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number);
// then
assertEquals(expectedOutput, actualOutput);
}
@Test
void testLiouvilleLambdaMustReturnPositiveOne() {
// given
int number = 10;
int expectedOutput = 1;
// when
int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number);
// then
assertEquals(expectedOutput, actualOutput);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/prime/MillerRabinPrimalityCheckTest.java | src/test/java/com/thealgorithms/maths/prime/MillerRabinPrimalityCheckTest.java | package com.thealgorithms.maths.prime;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.maths.Prime.MillerRabinPrimalityCheck;
import org.junit.jupiter.api.Test;
class MillerRabinPrimalityCheckTest {
@Test
void testDeterministicMillerRabinForPrimes() {
assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(2));
assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(37));
assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(123457));
assertTrue(MillerRabinPrimalityCheck.deterministicMillerRabin(6472601713L));
}
@Test
void testDeterministicMillerRabinForNotPrimes() {
assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(1));
assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(35));
assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(123453));
assertFalse(MillerRabinPrimalityCheck.deterministicMillerRabin(647260175));
}
@Test
void testMillerRabinForPrimes() {
assertTrue(MillerRabinPrimalityCheck.millerRabin(11, 5));
assertTrue(MillerRabinPrimalityCheck.millerRabin(97, 5));
assertTrue(MillerRabinPrimalityCheck.millerRabin(6720589, 5));
assertTrue(MillerRabinPrimalityCheck.millerRabin(9549401549L, 5));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/prime/MobiusFunctionTest.java | src/test/java/com/thealgorithms/maths/prime/MobiusFunctionTest.java | package com.thealgorithms.maths.prime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.thealgorithms.maths.Prime.MobiusFunction;
import org.junit.jupiter.api.Test;
class MobiusFunctionTest {
@Test
void testMobiusForZero() {
// given
int number = 0;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
@Test
void testMobiusForNegativeNumber() {
// given
int number = -1;
String expectedMessage = "Number must be greater than zero.";
// when
Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); });
String actualMessage = exception.getMessage();
// then
assertEquals(expectedMessage, actualMessage);
}
@Test
void testMobiusFunction() {
int[] expectedResultArray = {
1,
-1,
-1,
0,
-1,
1,
-1,
0,
0,
1,
-1,
0,
-1,
1,
1,
0,
-1,
0,
-1,
0,
1,
1,
-1,
0,
0,
1,
0,
0,
-1,
-1,
-1,
0,
1,
1,
1,
0,
-1,
1,
1,
0,
-1,
-1,
-1,
0,
0,
1,
-1,
0,
0,
0,
1,
0,
-1,
0,
1,
0,
1,
1,
-1,
0,
-1,
1,
0,
0,
1,
-1,
-1,
0,
1,
-1,
-1,
0,
-1,
1,
0,
0,
1,
-1,
-1,
0,
0,
1,
-1,
0,
1,
1,
1,
0,
-1,
0,
1,
0,
1,
1,
1,
0,
-1,
0,
0,
0,
};
for (int i = 1; i <= 100; i++) {
// given
int expectedValue = expectedResultArray[i - 1];
// when
int actualValue = MobiusFunction.mobius(i);
// then
assertEquals(expectedValue, actualValue);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/maths/prime/PrimeFactorizationTest.java | src/test/java/com/thealgorithms/maths/prime/PrimeFactorizationTest.java | package com.thealgorithms.maths.prime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.thealgorithms.maths.Prime.PrimeFactorization;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PrimeFactorizationTest {
@ParameterizedTest
@MethodSource("provideNumbersAndFactors")
void testPrimeFactorization(int number, List<Integer> expectedFactors) {
assertEquals(expectedFactors, PrimeFactorization.pfactors(number), "Prime factors for number: " + number);
}
@ParameterizedTest
@MethodSource("provideNumbersAndSizes")
void testPrimeFactorsSize(int number, int expectedSize) {
assertEquals(expectedSize, PrimeFactorization.pfactors(number).size(), "Size of prime factors list for number: " + number);
}
private static Stream<Arguments> provideNumbersAndFactors() {
return Stream.of(Arguments.of(0, List.of()), Arguments.of(1, List.of()), Arguments.of(2, List.of(2)), Arguments.of(3, List.of(3)), Arguments.of(4, List.of(2, 2)), Arguments.of(18, List.of(2, 3, 3)), Arguments.of(100, List.of(2, 2, 5, 5)), Arguments.of(198, List.of(2, 3, 3, 11)));
}
private static Stream<Arguments> provideNumbersAndSizes() {
return Stream.of(Arguments.of(2, 1), Arguments.of(3, 1), Arguments.of(4, 2), Arguments.of(18, 3), Arguments.of(100, 4), Arguments.of(198, 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/randomized/ReservoirSamplingTest.java | src/test/java/com/thealgorithms/randomized/ReservoirSamplingTest.java | package com.thealgorithms.randomized;
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.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class ReservoirSamplingTest {
@Test
public void testSampleSizeEqualsStreamLength() {
int[] stream = {1, 2, 3, 4, 5};
int sampleSize = 5;
List<Integer> result = ReservoirSampling.sample(stream, sampleSize);
assertEquals(sampleSize, result.size());
assertTrue(Arrays.stream(stream).allMatch(result::contains));
}
@Test
public void testSampleSizeLessThanStreamLength() {
int[] stream = {10, 20, 30, 40, 50, 60};
int sampleSize = 3;
List<Integer> result = ReservoirSampling.sample(stream, sampleSize);
assertEquals(sampleSize, result.size());
for (int value : result) {
assertTrue(Arrays.stream(stream).anyMatch(x -> x == value));
}
}
@Test
public void testSampleSizeGreaterThanStreamLengthThrowsException() {
int[] stream = {1, 2, 3};
Exception exception = assertThrows(IllegalArgumentException.class, () -> ReservoirSampling.sample(stream, 5));
assertEquals("Sample size cannot exceed stream size.", 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/randomized/MonteCarloIntegrationTest.java | src/test/java/com/thealgorithms/randomized/MonteCarloIntegrationTest.java | package com.thealgorithms.randomized;
import static com.thealgorithms.randomized.MonteCarloIntegration.approximate;
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 java.util.function.Function;
import org.junit.jupiter.api.Test;
class MonteCarloIntegrationTest {
private static final double EPSILON = 0.03; // Allow 3% error margin
@Test
void testConstantFunction() {
// Integral of f(x) = 2 from 0 to 1 is 2
Function<Double, Double> constant = x -> 2.0;
double result = approximate(constant, 0, 1, 10000);
assertEquals(2.0, result, EPSILON);
}
@Test
void testLinearFunction() {
// Integral of f(x) = x from 0 to 1 is 0.5
Function<Double, Double> linear = Function.identity();
double result = approximate(linear, 0, 1, 10000);
assertEquals(0.5, result, EPSILON);
}
@Test
void testQuadraticFunction() {
// Integral of f(x) = x^2 from 0 to 1 is 1/3
Function<Double, Double> quadratic = x -> x * x;
double result = approximate(quadratic, 0, 1, 10000);
assertEquals(1.0 / 3.0, result, EPSILON);
}
@Test
void testLargeSampleSize() {
// Integral of f(x) = x^2 from 0 to 1 is 1/3
Function<Double, Double> quadratic = x -> x * x;
double result = approximate(quadratic, 0, 1, 50000000);
assertEquals(1.0 / 3.0, result, EPSILON / 2); // Larger sample size, smaller error margin
}
@Test
void testReproducibility() {
Function<Double, Double> linear = Function.identity();
double result1 = approximate(linear, 0, 1, 10000, 42L);
double result2 = approximate(linear, 0, 1, 10000, 42L);
assertEquals(result1, result2, 0.0); // Exactly equal
}
@Test
void testNegativeInterval() {
// Integral of f(x) = x from -1 to 1 is 0
Function<Double, Double> linear = Function.identity();
double result = approximate(linear, -1, 1, 10000);
assertEquals(0.0, result, EPSILON);
}
@Test
void testNullFunction() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> approximate(null, 0, 1, 1000));
assertNotNull(exception);
}
@Test
void testInvalidInterval() {
Function<Double, Double> linear = Function.identity();
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
approximate(linear, 2, 1, 1000); // b <= a
});
assertNotNull(exception);
}
@Test
void testZeroSampleSize() {
Function<Double, Double> linear = Function.identity();
Exception exception = assertThrows(IllegalArgumentException.class, () -> approximate(linear, 0, 1, 0));
assertNotNull(exception);
}
@Test
void testNegativeSampleSize() {
Function<Double, Double> linear = Function.identity();
Exception exception = assertThrows(IllegalArgumentException.class, () -> approximate(linear, 0, 1, -100));
assertNotNull(exception);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/randomized/KargerMinCutTest.java | src/test/java/com/thealgorithms/randomized/KargerMinCutTest.java | package com.thealgorithms.randomized;
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.List;
import org.junit.jupiter.api.Test;
public class KargerMinCutTest {
@Test
public void testSimpleGraph() {
// Graph: 0 -- 1
Collection<Integer> nodes = Arrays.asList(0, 1);
List<int[]> edges = List.of(new int[] {0, 1});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(1, result.minCut());
assertTrue(result.first().contains(0) || result.first().contains(1));
assertTrue(result.second().contains(0) || result.second().contains(1));
}
@Test
public void testTriangleGraph() {
// Graph: 0 -- 1 -- 2 -- 0
Collection<Integer> nodes = Arrays.asList(0, 1, 2);
List<int[]> edges = List.of(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 0});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(2, result.minCut());
}
@Test
public void testSquareGraph() {
// Graph: 0 -- 1
// | |
// 3 -- 2
Collection<Integer> nodes = Arrays.asList(0, 1, 2, 3);
List<int[]> edges = List.of(new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 0});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(2, result.minCut());
}
@Test
public void testDisconnectedGraph() {
// Graph: 0 -- 1 2 -- 3
Collection<Integer> nodes = Arrays.asList(0, 1, 2, 3);
List<int[]> edges = List.of(new int[] {0, 1}, new int[] {2, 3});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(0, result.minCut());
}
@Test
public void testCompleteGraph() {
// Complete Graph: 0 -- 1 -- 2 -- 3 (all nodes connected to each other)
Collection<Integer> nodes = Arrays.asList(0, 1, 2, 3);
List<int[]> edges = List.of(new int[] {0, 1}, new int[] {0, 2}, new int[] {0, 3}, new int[] {1, 2}, new int[] {1, 3}, new int[] {2, 3});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(3, result.minCut());
}
@Test
public void testSingleNodeGraph() {
// Graph: Single node with no edges
Collection<Integer> nodes = List.of(0);
List<int[]> edges = List.of();
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(0, result.minCut());
assertTrue(result.first().contains(0));
assertTrue(result.second().isEmpty());
}
@Test
public void testTwoNodesNoEdge() {
// Graph: 0 1 (no edges)
Collection<Integer> nodes = Arrays.asList(0, 1);
List<int[]> edges = List.of();
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
assertEquals(0, result.minCut());
assertTrue(result.first().contains(0) || result.first().contains(1));
assertTrue(result.second().contains(0) || result.second().contains(1));
}
@Test
public void testComplexGraph() {
// Nodes: 0, 1, 2, 3, 4, 5, 6, 7, 8
// Edges: Fully connected graph with additional edges for complexity
Collection<Integer> nodes = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8);
List<int[]> edges = List.of(new int[] {0, 1}, new int[] {0, 2}, new int[] {0, 3}, new int[] {0, 4}, new int[] {0, 5}, new int[] {1, 2}, new int[] {1, 3}, new int[] {1, 4}, new int[] {1, 5}, new int[] {1, 6}, new int[] {2, 3}, new int[] {2, 4}, new int[] {2, 5}, new int[] {2, 6},
new int[] {2, 7}, new int[] {3, 4}, new int[] {3, 5}, new int[] {3, 6}, new int[] {3, 7}, new int[] {3, 8}, new int[] {4, 5}, new int[] {4, 6}, new int[] {4, 7}, new int[] {4, 8}, new int[] {5, 6}, new int[] {5, 7}, new int[] {5, 8}, new int[] {6, 7}, new int[] {6, 8}, new int[] {7, 8},
new int[] {0, 6}, new int[] {1, 7}, new int[] {2, 8});
KargerMinCut.KargerOutput result = KargerMinCut.findMinCut(nodes, edges);
// The exact minimum cut value depends on the randomization, but it should be consistent
// for this graph structure. For a fully connected graph, the minimum cut is typically
// determined by the smallest number of edges connecting two partitions.
assertTrue(result.minCut() > 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/randomized/RandomizedQuickSortTest.java | src/test/java/com/thealgorithms/randomized/RandomizedQuickSortTest.java | package com.thealgorithms.randomized;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the RandomizedQuickSort class.
*/
public class RandomizedQuickSortTest {
/**
* Tests sorting of an array with multiple elements, including duplicates.
*/
@Test
public void testRandomizedQuickSortMultipleElements() {
int[] arr = {3, 6, 8, 10, 1, 2, 1};
int[] expected = {1, 1, 2, 3, 6, 8, 10};
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
/**
* Tests sorting of an empty array.
*/
@Test
public void testRandomizedQuickSortEmptyArray() {
int[] arr = {};
int[] expected = {};
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
/**
* Tests sorting of an array with a single element.
*/
@Test
public void testRandomizedQuickSortSingleElement() {
int[] arr = {5};
int[] expected = {5};
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/randomized/RandomizedClosestPairTest.java | src/test/java/com/thealgorithms/randomized/RandomizedClosestPairTest.java | package com.thealgorithms.randomized;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.thealgorithms.randomized.RandomizedClosestPair.Point;
import org.junit.jupiter.api.Test;
public class RandomizedClosestPairTest {
@Test
public void testFindClosestPairDistance() {
Point[] points = {new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(8, 8), new Point(13, 13)};
double result = RandomizedClosestPair.findClosestPairDistance(points);
assertEquals(Math.sqrt(2), result, 0.00001);
}
@Test
public void testWithIdenticalPoints() {
Point[] points = {new Point(0, 0), new Point(0, 0), new Point(1, 1)};
double result = RandomizedClosestPair.findClosestPairDistance(points);
assertEquals(0.0, result, 0.00001);
}
@Test
public void testWithDistantPoints() {
Point[] points = {new Point(0, 0), new Point(5, 0), new Point(10, 0)};
double result = RandomizedClosestPair.findClosestPairDistance(points);
assertEquals(5.0, result, 0.00001);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerificationTest.java | src/test/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerificationTest.java | package com.thealgorithms.randomized;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RandomizedMatrixMultiplicationVerificationTest {
@Test
void testCorrectMultiplication() {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = {{19, 22}, {43, 50}};
assertTrue(RandomizedMatrixMultiplicationVerification.verify(a, b, c, 10));
}
@Test
void testIncorrectMultiplication() {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] wrongC = {{20, 22}, {43, 51}};
assertFalse(RandomizedMatrixMultiplicationVerification.verify(a, b, wrongC, 10));
}
@Test
void testLargeMatrix() {
int size = 100;
int[][] a = new int[size][size];
int[][] b = new int[size][size];
int[][] c = new int[size][size];
for (int i = 0; i < size; i++) {
a[i][i] = 1;
b[i][i] = 1;
c[i][i] = 1;
}
assertTrue(RandomizedMatrixMultiplicationVerification.verify(a, b, c, 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/recursion/GenerateSubsetsTest.java | src/test/java/com/thealgorithms/recursion/GenerateSubsetsTest.java | package com.thealgorithms.recursion;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public final class GenerateSubsetsTest {
@Test
@DisplayName("Subsets of 'abc'")
void testSubsetsOfABC() {
assertSubsets("abc", Arrays.asList("abc", "ab", "ac", "a", "bc", "b", "c", ""));
}
@Test
@DisplayName("Subsets of 'cbf'")
void testSubsetsOfCBF() {
assertSubsets("cbf", Arrays.asList("cbf", "cb", "cf", "c", "bf", "b", "f", ""));
}
@Test
@DisplayName("Subsets of 'aba' with duplicates")
void testSubsetsWithDuplicateChars() {
assertSubsets("aba", Arrays.asList("aba", "ab", "aa", "a", "ba", "b", "a", ""));
}
@Test
@DisplayName("Subsets of empty string")
void testEmptyInput() {
assertSubsets("", List.of(""));
}
private void assertSubsets(String input, Iterable<String> expected) {
List<String> actual = GenerateSubsets.subsetRecursion(input);
assertIterableEquals(expected, actual, "Subsets do not match for input: " + 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/recursion/FibonacciSeriesTest.java | src/test/java/com/thealgorithms/recursion/FibonacciSeriesTest.java | package com.thealgorithms.recursion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class FibonacciSeriesTest {
@Test
public void testFibonacci() {
assertEquals(0, FibonacciSeries.fibonacci(0));
assertEquals(1, FibonacciSeries.fibonacci(1));
assertEquals(1, FibonacciSeries.fibonacci(2));
assertEquals(2, FibonacciSeries.fibonacci(3));
assertEquals(3, FibonacciSeries.fibonacci(4));
assertEquals(5, FibonacciSeries.fibonacci(5));
assertEquals(8, FibonacciSeries.fibonacci(6));
assertEquals(13, FibonacciSeries.fibonacci(7));
assertEquals(21, FibonacciSeries.fibonacci(8));
assertEquals(34, FibonacciSeries.fibonacci(9));
assertEquals(55, FibonacciSeries.fibonacci(10));
assertEquals(89, FibonacciSeries.fibonacci(11));
assertEquals(144, FibonacciSeries.fibonacci(12));
assertEquals(233, FibonacciSeries.fibonacci(13));
assertEquals(377, FibonacciSeries.fibonacci(14));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java | src/test/java/com/thealgorithms/recursion/DiceThrowerTest.java | package com.thealgorithms.recursion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Test class for DiceThrower
*
* @author BEASTSHRIRAM
*/
class DiceThrowerTest {
@Test
void testTargetZero() {
List<String> result = DiceThrower.getDiceCombinations(0);
assertEquals(1, result.size());
assertEquals("", result.get(0));
}
@Test
void testTargetOne() {
List<String> result = DiceThrower.getDiceCombinations(1);
assertEquals(1, result.size());
assertEquals("1", result.get(0));
}
@Test
void testTargetTwo() {
List<String> result = DiceThrower.getDiceCombinations(2);
assertEquals(2, result.size());
assertTrue(result.contains("11"));
assertTrue(result.contains("2"));
}
@Test
void testTargetThree() {
List<String> result = DiceThrower.getDiceCombinations(3);
assertEquals(4, result.size());
assertTrue(result.contains("111"));
assertTrue(result.contains("12"));
assertTrue(result.contains("21"));
assertTrue(result.contains("3"));
}
@Test
void testTargetFour() {
List<String> result = DiceThrower.getDiceCombinations(4);
assertEquals(8, result.size());
assertTrue(result.contains("1111"));
assertTrue(result.contains("112"));
assertTrue(result.contains("121"));
assertTrue(result.contains("13"));
assertTrue(result.contains("211"));
assertTrue(result.contains("22"));
assertTrue(result.contains("31"));
assertTrue(result.contains("4"));
}
@Test
void testTargetSix() {
List<String> result = DiceThrower.getDiceCombinations(6);
assertEquals(32, result.size());
assertTrue(result.contains("6"));
assertTrue(result.contains("33"));
assertTrue(result.contains("222"));
assertTrue(result.contains("111111"));
}
@Test
void testTargetSeven() {
List<String> result = DiceThrower.getDiceCombinations(7);
// Should include combinations like 61, 52, 43, 331, 322, 2221, etc.
assertTrue(result.size() > 0);
assertTrue(result.contains("61"));
assertTrue(result.contains("16"));
assertTrue(result.contains("52"));
assertTrue(result.contains("43"));
}
@Test
void testLargerTarget() {
List<String> result = DiceThrower.getDiceCombinations(10);
assertTrue(result.size() > 0);
// All results should sum to 10
for (String combination : result) {
int sum = 0;
for (char c : combination.toCharArray()) {
sum += Character.getNumericValue(c);
}
assertEquals(10, sum);
}
}
@Test
void testNegativeTarget() {
assertThrows(IllegalArgumentException.class, () -> { DiceThrower.getDiceCombinations(-1); });
}
@Test
void testNegativeTargetPrint() {
assertThrows(IllegalArgumentException.class, () -> { DiceThrower.printDiceCombinations(-1); });
}
@Test
void testAllCombinationsValid() {
List<String> result = DiceThrower.getDiceCombinations(5);
for (String combination : result) {
// Check that each character is a valid dice face (1-6)
for (char c : combination.toCharArray()) {
int face = Character.getNumericValue(c);
assertTrue(face >= 1 && face <= 6, "Invalid dice face: " + face);
}
// Check that the sum equals the target
int sum = 0;
for (char c : combination.toCharArray()) {
sum += Character.getNumericValue(c);
}
assertEquals(5, sum, "Combination " + combination + " does not sum to 5");
}
}
@Test
void testPrintDiceCombinations() {
// Capture System.out
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outputStream));
try {
// Test printing combinations for target 3
DiceThrower.printDiceCombinations(3);
String output = outputStream.toString();
// Verify all expected combinations are printed
assertTrue(output.contains("111"));
assertTrue(output.contains("12"));
assertTrue(output.contains("21"));
assertTrue(output.contains("3"));
// Count number of lines (combinations)
String[] lines = output.trim().split("\n");
assertEquals(4, lines.length);
} finally {
// Restore System.out
System.setOut(originalOut);
}
}
@Test
void testPrintDiceCombinationsZero() {
// Capture System.out
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outputStream));
try {
DiceThrower.printDiceCombinations(0);
String output = outputStream.toString();
// Should print empty string (one line)
assertEquals("", output.trim());
} finally {
System.setOut(originalOut);
}
}
@Test
void testMainMethod() {
// Capture System.out
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outputStream));
try {
// Test main method
DiceThrower.main(new String[] {});
String output = outputStream.toString();
// Verify expected output contains header and combinations
assertTrue(output.contains("All dice combinations that sum to 4:"));
assertTrue(output.contains("Total combinations: 8"));
assertTrue(output.contains("1111"));
assertTrue(output.contains("22"));
assertTrue(output.contains("4"));
} finally {
System.setOut(originalOut);
}
}
@Test
void testEdgeCaseTargetFive() {
List<String> result = DiceThrower.getDiceCombinations(5);
assertEquals(16, result.size());
// Test specific combinations exist
assertTrue(result.contains("11111"));
assertTrue(result.contains("1112"));
assertTrue(result.contains("122"));
assertTrue(result.contains("14"));
assertTrue(result.contains("23"));
assertTrue(result.contains("5"));
}
@Test
void testTargetGreaterThanSix() {
List<String> result = DiceThrower.getDiceCombinations(8);
assertTrue(result.size() > 0);
// Verify some expected combinations
assertTrue(result.contains("62"));
assertTrue(result.contains("53"));
assertTrue(result.contains("44"));
assertTrue(result.contains("2222"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/recursion/SylvesterSequenceTest.java | src/test/java/com/thealgorithms/recursion/SylvesterSequenceTest.java | package com.thealgorithms.recursion;
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.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
class SylvesterSequenceTest {
/**
* Provides test cases for valid Sylvester sequence numbers.
* Format: { n, expectedValue }
*/
static Stream<Object[]> validSylvesterNumbers() {
return Stream.of(new Object[] {1, BigInteger.valueOf(2)}, new Object[] {2, BigInteger.valueOf(3)}, new Object[] {3, BigInteger.valueOf(7)}, new Object[] {4, BigInteger.valueOf(43)}, new Object[] {5, BigInteger.valueOf(1807)}, new Object[] {6, new BigInteger("3263443")},
new Object[] {7, new BigInteger("10650056950807")}, new Object[] {8, new BigInteger("113423713055421844361000443")});
}
@ParameterizedTest
@MethodSource("validSylvesterNumbers")
void testSylvesterValidNumbers(int n, BigInteger expected) {
assertEquals(expected, SylvesterSequence.sylvester(n), "Sylvester sequence value mismatch for n=" + n);
}
/**
* Test edge case for n <= 0 which should throw IllegalArgumentException
*/
@ParameterizedTest
@ValueSource(ints = {0, -1, -10, -100})
void testSylvesterInvalidZero(int n) {
assertThrows(IllegalArgumentException.class, () -> SylvesterSequence.sylvester(n));
}
/**
* Test a larger number to ensure no overflow occurs.
*/
@Test
void testSylvesterLargeNumber() {
int n = 10;
BigInteger result = SylvesterSequence.sylvester(n);
assertNotNull(result);
assertTrue(result.compareTo(BigInteger.ZERO) > 0, "Result should be positive");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/recursion/FactorialRecursionTest.java | src/test/java/com/thealgorithms/recursion/FactorialRecursionTest.java | package com.thealgorithms.recursion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class FactorialRecursionTest {
@ParameterizedTest
@MethodSource("inputStream")
void testFactorialRecursion(long expected, int number) {
assertEquals(expected, FactorialRecursion.factorial(number));
}
private static Stream<Arguments> inputStream() {
return Stream.of(Arguments.of(1, 0), Arguments.of(1, 1), Arguments.of(2, 2), Arguments.of(6, 3), Arguments.of(120, 5));
}
@Test
void testThrowsForNegativeInput() {
assertThrows(IllegalArgumentException.class, () -> FactorialRecursion.factorial(-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/io/BufferedReaderTest.java | src/test/java/com/thealgorithms/io/BufferedReaderTest.java | package com.thealgorithms.io;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class BufferedReaderTest {
@Test
public void testPeeks() throws IOException {
String text = "Hello!\nWorld!";
int len = text.length();
byte[] bytes = text.getBytes();
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
BufferedReader reader = new BufferedReader(input);
// read the first letter
assertEquals(reader.read(), 'H');
len--;
assertEquals(reader.available(), len);
// position: H[e]llo!\nWorld!
// reader.read() will be == 'e'
assertEquals(reader.peek(1), 'l');
assertEquals(reader.peek(2), 'l'); // second l
assertEquals(reader.peek(3), 'o');
}
@Test
public void testMixes() throws IOException {
String text = "Hello!\nWorld!";
int len = text.length();
byte[] bytes = text.getBytes();
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
BufferedReader reader = new BufferedReader(input);
// read the first letter
assertEquals(reader.read(), 'H'); // first letter
len--;
assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H')
assertEquals(reader.read(), 'e'); // second letter
len--;
assertEquals(reader.available(), len);
// position: H[e]llo!\nWorld!
assertEquals(reader.peek(2), 'o'); // second l
assertEquals(reader.peek(3), '!');
assertEquals(reader.peek(4), '\n');
assertEquals(reader.read(), 'l'); // third letter
assertEquals(reader.peek(1), 'o'); // fourth letter
for (int i = 0; i < 6; i++) {
reader.read();
}
try {
System.out.println((char) reader.peek(4));
} catch (Exception ignored) {
System.out.println("[cached intentional error]");
// intentional, for testing purpose
}
}
@Test
public void testBlockPractical() throws IOException {
String text = "!Hello\nWorld!";
byte[] bytes = text.getBytes();
int len = bytes.length;
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
BufferedReader reader = new BufferedReader(input);
assertEquals(reader.peek(), 'H');
assertEquals(reader.read(), '!'); // read the first letter
len--;
// this only reads the next 5 bytes (Hello) because
// the default buffer size = 5
assertEquals(new String(reader.readBlock()), "Hello");
len -= 5;
assertEquals(reader.available(), len);
// maybe kind of a practical demonstration / use case
if (reader.read() == '\n') {
assertEquals(reader.read(), 'W');
assertEquals(reader.read(), 'o');
// the rest of the blocks
assertEquals(new String(reader.readBlock()), "rld!");
} else {
// should not reach
throw new IOException("Something not right");
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/tree/HeavyLightDecompositionTest.java | src/test/java/com/thealgorithms/tree/HeavyLightDecompositionTest.java | package com.thealgorithms.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class HeavyLightDecompositionTest {
private HeavyLightDecomposition hld;
private final int[] values = {0, 10, 20, 30, 40, 50};
/**
* Initializes the test environment with a predefined tree structure and values.
*/
@BeforeEach
void setUp() {
hld = new HeavyLightDecomposition(5);
hld.addEdge(1, 2);
hld.addEdge(1, 3);
hld.addEdge(2, 4);
hld.addEdge(2, 5);
hld.initialize(1, values);
}
/**
* Verifies that the tree initializes successfully without errors.
*/
@Test
void testBasicTreeInitialization() {
assertTrue(true, "Basic tree structure initialized successfully");
}
/**
* Tests the maximum value query in the path between nodes.
*/
@Test
void testQueryMaxInPath() {
assertEquals(50, hld.queryMaxInPath(4, 5), "Max value in path (4,5) should be 50");
assertEquals(30, hld.queryMaxInPath(3, 2), "Max value in path (3,2) should be 30");
}
/**
* Tests updating a node's value and ensuring it is reflected in queries.
*/
@Test
void testUpdateNodeValue() {
hld.updateSegmentTree(1, 0, hld.getPositionIndex() - 1, hld.getPosition(4), 100);
assertEquals(100, hld.queryMaxInPath(4, 5), "Updated value should be reflected in query");
}
/**
* Tests the maximum value query in a skewed tree structure.
*/
@Test
void testSkewedTreeMaxQuery() {
assertEquals(40, hld.queryMaxInPath(1, 4), "Max value in skewed tree (1,4) should be 40");
}
/**
* Ensures query handles cases where u is a deeper node correctly.
*/
@Test
void testDepthSwapInPathQuery() {
assertEquals(50, hld.queryMaxInPath(5, 2), "Query should handle depth swap correctly");
assertEquals(40, hld.queryMaxInPath(4, 1), "Query should handle swapped nodes correctly and return max 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/searches/MonteCarloTreeSearchTest.java | src/test/java/com/thealgorithms/searches/MonteCarloTreeSearchTest.java | package com.thealgorithms.searches;
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 MonteCarloTreeSearchTest {
/**
* Test the creation of a node and its initial state.
*/
@Test
void testNodeCreation() {
MonteCarloTreeSearch.Node node = new MonteCarloTreeSearch().new Node(null, true);
assertNotNull(node, "Node should be created");
assertTrue(node.childNodes.isEmpty(), "Child nodes should be empty upon creation");
assertTrue(node.isPlayersTurn, "Initial turn should be player's turn");
assertEquals(0, node.score, "Initial score should be zero");
assertEquals(0, node.visitCount, "Initial visit count should be zero");
}
/**
* Test adding child nodes to a parent node.
*/
@Test
void testAddChildNodes() {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch();
MonteCarloTreeSearch.Node parentNode = mcts.new Node(null, true);
mcts.addChildNodes(parentNode, 5);
assertEquals(5, parentNode.childNodes.size(), "Parent should have 5 child nodes");
for (MonteCarloTreeSearch.Node child : parentNode.childNodes) {
assertFalse(child.isPlayersTurn, "Child node should not be player's turn");
assertEquals(0, child.visitCount, "Child node visit count should be zero");
}
}
/**
* Test the UCT selection of a promising node.
*/
@Test
void testGetPromisingNode() {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch();
MonteCarloTreeSearch.Node parentNode = mcts.new Node(null, true);
// Create child nodes with different visit counts and scores
for (int i = 0; i < 3; i++) {
MonteCarloTreeSearch.Node child = mcts.new Node(parentNode, false);
child.visitCount = i + 1;
child.score = i * 2;
parentNode.childNodes.add(child);
}
// Get promising node
MonteCarloTreeSearch.Node promisingNode = mcts.getPromisingNode(parentNode);
// The child with the highest UCT value should be chosen.
assertNotNull(promisingNode, "Promising node should not be null");
assertEquals(0, parentNode.childNodes.indexOf(promisingNode), "The first child should be the most promising");
}
/**
* Test simulation of random play and backpropagation.
*/
@Test
void testSimulateRandomPlay() {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch();
MonteCarloTreeSearch.Node node = mcts.new Node(null, true);
node.visitCount = 10; // Simulating existing visits
// Simulate random play
mcts.simulateRandomPlay(node);
// Check visit count after simulation
assertEquals(11, node.visitCount, "Visit count should increase after simulation");
// Check if score is updated correctly
assertTrue(node.score >= 0 && node.score <= MonteCarloTreeSearch.WIN_SCORE, "Score should be between 0 and WIN_SCORE");
}
/**
* Test retrieving the winning node based on scores.
*/
@Test
void testGetWinnerNode() {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch();
MonteCarloTreeSearch.Node parentNode = mcts.new Node(null, true);
// Create child nodes with varying scores
MonteCarloTreeSearch.Node winningNode = mcts.new Node(parentNode, false);
winningNode.score = 10; // Highest score
parentNode.childNodes.add(winningNode);
MonteCarloTreeSearch.Node losingNode = mcts.new Node(parentNode, false);
losingNode.score = 5;
parentNode.childNodes.add(losingNode);
MonteCarloTreeSearch.Node anotherLosingNode = mcts.new Node(parentNode, false);
anotherLosingNode.score = 3;
parentNode.childNodes.add(anotherLosingNode);
// Get the winning node
MonteCarloTreeSearch.Node winnerNode = mcts.getWinnerNode(parentNode);
assertEquals(winningNode, winnerNode, "Winning node should have the highest score");
}
/**
* Test the full Monte Carlo Tree Search process.
*/
@Test
void testMonteCarloTreeSearch() {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch();
MonteCarloTreeSearch.Node rootNode = mcts.new Node(null, true);
// Execute MCTS and check the resulting node
MonteCarloTreeSearch.Node optimalNode = mcts.monteCarloTreeSearch(rootNode);
assertNotNull(optimalNode, "MCTS should return a non-null optimal node");
assertTrue(rootNode.childNodes.contains(optimalNode), "Optimal node should be a child of the root");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/RecursiveBinarySearchTest.java | src/test/java/com/thealgorithms/searches/RecursiveBinarySearchTest.java | // Created by Pronay Debnath
// Date:- 1/10/2023
// Test file updated with JUnit tests
package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; // Import the JUnit 5 Test annotation
public class RecursiveBinarySearchTest {
@Test
public void testBinarySearch() {
// Create an instance of GenericBinarySearch
RecursiveBinarySearch<Integer> searcher = new RecursiveBinarySearch<>();
// Test case 1: Element found in the array
Integer[] arr1 = {1, 2, 3, 4, 5};
int target1 = 3;
int result1 = searcher.binsear(arr1, 0, arr1.length - 1, target1);
assertEquals(2, result1);
// Test case 2: Element not found in the array
Integer[] arr2 = {1, 2, 3, 4, 5};
int target2 = 6;
int result2 = searcher.binsear(arr2, 0, arr2.length - 1, target2);
assertEquals(-1, result2);
// Test case 3: Element found at the beginning of the array
Integer[] arr3 = {10, 20, 30, 40, 50};
int target3 = 10;
int result3 = searcher.binsear(arr3, 0, arr3.length - 1, target3);
assertEquals(0, result3);
// Test case 4: Element found at the end of the array
Integer[] arr4 = {10, 20, 30, 40, 50};
int target4 = 50;
int result4 = searcher.binsear(arr4, 0, arr4.length - 1, target4);
assertEquals(4, result4);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java | src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class RowColumnWiseSorted2dArrayBinarySearchTest {
@Test
public void rowColumnSorted2dArrayBinarySearchTestMiddle() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 35;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {1, 2};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestSide() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 48;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {2, 3};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestUpper() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 20;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {0, 1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestUpperSide() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 40;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {0, 3};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestLower() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 31;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {3, 1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestLowerSide() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 51;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {3, 3};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestNotFound() {
Integer[][] arr = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
{21, 31, 41, 51},
};
Integer target = 101;
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target);
int[] expected = {-1, -1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
/**
* Tests for a WIDE rectangular matrix (3 rows, 4 columns)
*/
private static final Integer[][] WIDE_RECTANGULAR_MATRIX = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{18, 28, 38, 48},
};
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixMiddle() {
Integer target = 25; // A value in the middle
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {1, 1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixTopRightCorner() {
Integer target = 40; // The top-right corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {0, 3};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixBottomLeftCorner() {
Integer target = 18; // The bottom-left corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {2, 0};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixTopLeftCorner() {
Integer target = 10; // The top-left corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {0, 0};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixBottomRightCorner() {
Integer target = 48; // The bottom-right corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {2, 3};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestWideMatrixNotFound() {
Integer target = 99; // A value that does not exist
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, target);
int[] expected = {-1, -1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
/**
* Tests for a TALL rectangular matrix (4 rows, 3 columns)
*/
private static final Integer[][] TALL_RECTANGULAR_MATRIX = {
{10, 20, 30},
{15, 25, 35},
{18, 28, 38},
{21, 31, 41},
};
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixMiddle() {
Integer target = 28; // A value in the middle
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {2, 1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixTopRightCorner() {
Integer target = 30; // The top-right corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {0, 2};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixBottomLeftCorner() {
Integer target = 21; // The bottom-left corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {3, 0};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixTopLeftCorner() {
Integer target = 10; // The top-left corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {0, 0};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixBottomRightCorner() {
Integer target = 41; // The bottom-right corner element
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {3, 2};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[1]);
}
@Test
public void rowColumnSorted2dArrayBinarySearchTestTallMatrixNotFound() {
Integer target = 5; // A value that does not exist
int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(TALL_RECTANGULAR_MATRIX, target);
int[] expected = {-1, -1};
assertEquals(expected[0], ans[0]);
assertEquals(expected[1], ans[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/searches/SearchInARowAndColWiseSortedMatrixTest.java | src/test/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrixTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class SearchInARowAndColWiseSortedMatrixTest {
private final SearchInARowAndColWiseSortedMatrix searcher = new SearchInARowAndColWiseSortedMatrix();
@Test
void testSearchValueExistsInMatrix() {
int[][] matrix = {{10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}};
int value = 29;
int[] expected = {2, 1}; // Row 2, Column 1
assertArrayEquals(expected, searcher.search(matrix, value), "Value should be found in the matrix");
}
@Test
void testSearchValueNotExistsInMatrix() {
int[][] matrix = {{10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}};
int value = 100;
int[] expected = {-1, -1}; // Not found
assertArrayEquals(expected, searcher.search(matrix, value), "Value should not be found in the matrix");
}
@Test
void testSearchInEmptyMatrix() {
int[][] matrix = {};
int value = 5;
int[] expected = {-1, -1}; // Not found
assertArrayEquals(expected, searcher.search(matrix, value), "Should return {-1, -1} for empty matrix");
}
@Test
void testSearchInSingleElementMatrixFound() {
int[][] matrix = {{5}};
int value = 5;
int[] expected = {0, 0}; // Found at (0,0)
assertArrayEquals(expected, searcher.search(matrix, value), "Value should be found in single element matrix");
}
@Test
void testSearchInSingleElementMatrixNotFound() {
int[][] matrix = {{10}};
int value = 5;
int[] expected = {-1, -1}; // Not found
assertArrayEquals(expected, searcher.search(matrix, value), "Should return {-1, -1} for value not found in single element matrix");
}
@Test
void testSearchInRowWiseSortedMatrix() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int value = 6;
int[] expected = {1, 2}; // Found at (1, 2)
assertArrayEquals(expected, searcher.search(matrix, value), "Value should be found in the row-wise sorted matrix");
}
@Test
void testSearchInColWiseSortedMatrix() {
int[][] matrix = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
int value = 5;
int[] expected = {1, 1}; // Found at (1, 1)
assertArrayEquals(expected, searcher.search(matrix, value), "Value should be found in the column-wise sorted matrix");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/QuickSelectTest.java | src/test/java/com/thealgorithms/searches/QuickSelectTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
class QuickSelectTest {
@Test
void quickSelectMinimumOfOneElement() {
List<Integer> elements = Collections.singletonList(42);
int minimum = QuickSelect.select(elements, 0);
assertEquals(42, minimum);
}
@Test
void quickSelectMinimumOfTwoElements() {
List<Integer> elements1 = Arrays.asList(42, 90);
List<Integer> elements2 = Arrays.asList(90, 42);
int minimum1 = QuickSelect.select(elements1, 0);
int minimum2 = QuickSelect.select(elements2, 0);
assertEquals(42, minimum1);
assertEquals(42, minimum2);
}
@Test
void quickSelectMinimumOfThreeElements() {
List<Integer> elements1 = Arrays.asList(1, 2, 3);
List<Integer> elements2 = Arrays.asList(2, 1, 3);
List<Integer> elements3 = Arrays.asList(2, 3, 1);
int minimum1 = QuickSelect.select(elements1, 0);
int minimum2 = QuickSelect.select(elements2, 0);
int minimum3 = QuickSelect.select(elements3, 0);
assertEquals(1, minimum1);
assertEquals(1, minimum2);
assertEquals(1, minimum3);
}
@Test
void quickSelectMinimumOfManyElements() {
List<Integer> elements = generateRandomIntegers(NUM_RND_ELEMENTS);
int actual = QuickSelect.select(elements, 0);
int expected = elements.stream().min(Comparator.naturalOrder()).get();
assertEquals(expected, actual);
}
@Test
void quickSelectMaximumOfOneElement() {
List<Integer> elements = Collections.singletonList(42);
int maximum = QuickSelect.select(elements, 0);
assertEquals(42, maximum);
}
@Test
void quickSelectMaximumOfTwoElements() {
List<Integer> elements1 = Arrays.asList(42, 90);
List<Integer> elements2 = Arrays.asList(90, 42);
int maximum1 = QuickSelect.select(elements1, 1);
int maximum2 = QuickSelect.select(elements2, 1);
assertEquals(90, maximum1);
assertEquals(90, maximum2);
}
@Test
void quickSelectMaximumOfThreeElements() {
List<Integer> elements1 = Arrays.asList(1, 2, 3);
List<Integer> elements2 = Arrays.asList(2, 1, 3);
List<Integer> elements3 = Arrays.asList(2, 3, 1);
int maximum1 = QuickSelect.select(elements1, 2);
int maximum2 = QuickSelect.select(elements2, 2);
int maximum3 = QuickSelect.select(elements3, 2);
assertEquals(3, maximum1);
assertEquals(3, maximum2);
assertEquals(3, maximum3);
}
@Test
void quickSelectMaximumOfManyElements() {
List<Integer> elements = generateRandomIntegers(NUM_RND_ELEMENTS);
int actual = QuickSelect.select(elements, NUM_RND_ELEMENTS - 1);
int expected = elements.stream().max(Comparator.naturalOrder()).get();
assertEquals(expected, actual);
}
@Test
void quickSelectMedianOfOneElement() {
List<Integer> elements = Collections.singletonList(42);
int median = QuickSelect.select(elements, 0);
assertEquals(42, median);
}
@Test
void quickSelectMedianOfThreeElements() {
List<Integer> elements1 = Arrays.asList(1, 2, 3);
List<Integer> elements2 = Arrays.asList(2, 1, 3);
List<Integer> elements3 = Arrays.asList(2, 3, 1);
int median1 = QuickSelect.select(elements1, 1);
int median2 = QuickSelect.select(elements2, 1);
int median3 = QuickSelect.select(elements3, 1);
assertEquals(2, median1);
assertEquals(2, median2);
assertEquals(2, median3);
}
@Test
void quickSelectMedianOfManyElements() {
int medianIndex = NUM_RND_ELEMENTS / 2;
List<Integer> elements = generateRandomIntegers(NUM_RND_ELEMENTS);
int actual = QuickSelect.select(elements, medianIndex);
List<Integer> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(medianIndex), actual);
}
@Test
void quickSelect30thPercentileOf10Elements() {
List<Integer> elements = generateRandomIntegers(10);
int actual = QuickSelect.select(elements, 2);
List<Integer> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(2), actual);
}
@Test
void quickSelect30thPercentileOfManyElements() {
int percentile30th = NUM_RND_ELEMENTS / 10 * 3;
List<Integer> elements = generateRandomIntegers(NUM_RND_ELEMENTS);
int actual = QuickSelect.select(elements, percentile30th);
List<Integer> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(percentile30th), actual);
}
@Test
void quickSelect70thPercentileOf10Elements() {
List<Integer> elements = generateRandomIntegers(10);
int actual = QuickSelect.select(elements, 6);
List<Integer> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(6), actual);
}
@Test
void quickSelect70thPercentileOfManyElements() {
int percentile70th = NUM_RND_ELEMENTS / 10 * 7;
List<Integer> elements = generateRandomIntegers(NUM_RND_ELEMENTS);
int actual = QuickSelect.select(elements, percentile70th);
List<Integer> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(percentile70th), actual);
}
@Test
void quickSelectMedianOfThreeCharacters() {
List<Character> elements = Arrays.asList('X', 'Z', 'Y');
char actual = QuickSelect.select(elements, 1);
assertEquals(actual, 'Y');
}
@Test
void quickSelectMedianOfManyCharacters() {
List<Character> elements = generateRandomCharacters(NUM_RND_ELEMENTS);
char actual = QuickSelect.select(elements, NUM_RND_ELEMENTS / 30);
List<Character> elementsSorted = getSortedCopyOfList(elements);
assertEquals(elementsSorted.get(NUM_RND_ELEMENTS / 30), actual);
}
@Test
void quickSelectNullList() {
NullPointerException exception = assertThrows(NullPointerException.class, () -> QuickSelect.select(null, 0));
String expectedMsg = "The list of elements must not be null.";
assertEquals(expectedMsg, exception.getMessage());
}
@Test
void quickSelectEmptyList() {
List<String> objects = Collections.emptyList();
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> QuickSelect.select(objects, 0));
String expectedMsg = "The list of elements must not be empty.";
assertEquals(expectedMsg, exception.getMessage());
}
@Test
void quickSelectIndexOutOfLeftBound() {
IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> QuickSelect.select(Collections.singletonList(1), -1));
String expectedMsg = "The index must not be negative.";
assertEquals(expectedMsg, exception.getMessage());
}
@Test
void quickSelectIndexOutOfRightBound() {
IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> QuickSelect.select(Collections.singletonList(1), 1));
String expectedMsg = "The index must be less than the number of elements.";
assertEquals(expectedMsg, exception.getMessage());
}
private static final int NUM_RND_ELEMENTS = 99;
private static final Random RANDOM = new Random(42);
private static final int ASCII_A = 0x41;
private static final int ASCII_Z = 0x5A;
private static List<Integer> generateRandomIntegers(int n) {
return RANDOM.ints(n).boxed().collect(Collectors.toList());
}
private static List<Character> generateRandomCharacters(int n) {
return RANDOM.ints(n, ASCII_A, ASCII_Z).mapToObj(i -> (char) i).collect(Collectors.toList());
}
private static <T extends Comparable<T>> List<T> getSortedCopyOfList(Collection<T> list) {
return list.stream().sorted().collect(Collectors.toList());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/UpperBoundTest.java | src/test/java/com/thealgorithms/searches/UpperBoundTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UpperBoundTest {
private UpperBound upperBound;
private Integer[] sortedArray;
@BeforeEach
void setUp() {
upperBound = new UpperBound();
// Generate a sorted array of random integers for testing
Random random = new Random();
int size = 100;
int maxElement = 100;
sortedArray = random.ints(size, 1, maxElement)
.distinct() // Ensure all elements are unique
.sorted()
.boxed()
.toArray(Integer[] ::new);
}
@Test
void testUpperBoundFound() {
int key = sortedArray[sortedArray.length - 1] + 1; // Test with a key larger than max element
int index = upperBound.find(sortedArray, key);
// The upper bound should be equal to the length of the array
assertEquals(sortedArray.length - 1, index, "Upper bound for a larger key should be the size of the array.");
}
@Test
void testUpperBoundExactMatch() {
int key = sortedArray[sortedArray.length / 2]; // Choose a key from the middle of the array
int index = upperBound.find(sortedArray, key);
// The index should point to the first element greater than the key
assertTrue(index < sortedArray.length, "Upper bound should not exceed array length.");
assertTrue(sortedArray[index] > key, "The element at the index should be greater than the key.");
}
@Test
void testUpperBoundMultipleValues() {
Integer[] arrayWithDuplicates = new Integer[] {1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9}; // Test array with duplicates
int key = 4;
int index = upperBound.find(arrayWithDuplicates, key);
assertTrue(index < arrayWithDuplicates.length, "Upper bound index should be valid.");
assertEquals(6, index, "The upper bound for 4 should be the index of the first 5.");
assertTrue(arrayWithDuplicates[index] > key, "Element at the upper bound index should be greater than the key.");
}
@Test
void testUpperBoundLowerThanMin() {
int key = 0; // Test with a key lower than the minimum element
int index = upperBound.find(sortedArray, key);
assertEquals(0, index, "Upper bound for a key lower than minimum should be 0.");
assertTrue(sortedArray[index] > key, "The element at index 0 should be greater than the key.");
}
@Test
void testUpperBoundHigherThanMax() {
int key = sortedArray[sortedArray.length - 1] + 1; // Test with a key higher than maximum element
int index = upperBound.find(sortedArray, key);
assertEquals(sortedArray.length - 1, index, "Upper bound for a key higher than maximum should be the size of the array.");
}
@Test
void testUpperBoundEdgeCase() {
// Edge case: empty array
Integer[] emptyArray = {};
int index = upperBound.find(emptyArray, 5);
assertEquals(0, index, "Upper bound for an empty array should be 0.");
}
@Test
void testUpperBoundSingleElementArray() {
Integer[] singleElementArray = {10};
int index = upperBound.find(singleElementArray, 5);
assertEquals(0, index, "Upper bound for 5 in a single element array should be 0.");
index = upperBound.find(singleElementArray, 10);
assertEquals(0, index, "Upper bound for 10 in a single element array should be 0.");
index = upperBound.find(singleElementArray, 15);
assertEquals(0, index, "Upper bound for 15 in a single element array should be 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/searches/IterativeTernarySearchTest.java | src/test/java/com/thealgorithms/searches/IterativeTernarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the IterativeTernarySearch class.
*/
class IterativeTernarySearchTest {
/**
* Test for basic ternary search functionality when the element is found.
*/
@Test
void testTernarySearchFound() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
Integer key = 128;
int expectedIndex = 7; // Index of the key in the array
assertEquals(expectedIndex, ternarySearch.find(array, key), "The index of the found element should be 7.");
}
/**
* Test for ternary search when the element is not present in the array.
*/
@Test
void testTernarySearchNotFound() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 6; // Element not present in the array
assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for ternary search with the first element as the key.
*/
@Test
void testTernarySearchFirstElement() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 1; // First element
assertEquals(0, ternarySearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for ternary search with the last element as the key.
*/
@Test
void testTernarySearchLastElement() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 16; // Last element
assertEquals(4, ternarySearch.find(array, key), "The index of the last element should be 4.");
}
/**
* Test for ternary search with a single element present.
*/
@Test
void testTernarySearchSingleElementFound() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1};
Integer key = 1; // Only element present
assertEquals(0, ternarySearch.find(array, key), "The index of the single element should be 0.");
}
/**
* Test for ternary search with a single element not present.
*/
@Test
void testTernarySearchSingleElementNotFound() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {1};
Integer key = 2; // Key not present
assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for ternary search with an empty array.
*/
@Test
void testTernarySearchEmptyArray() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = {}; // Empty array
Integer key = 1; // Key not present
assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for ternary search on a large array.
*/
@Test
void testTernarySearchLargeArray() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = new Integer[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
} // Array from 0 to 19998, step 2
Integer key = 9998; // Present in the array
assertEquals(4999, ternarySearch.find(array, key), "The index of the found element should be 4999.");
}
/**
* Test for ternary search on large array with a non-existent key.
*/
@Test
void testTernarySearchLargeArrayNotFound() {
IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
Integer[] array = new Integer[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
} // Array from 0 to 19998, step 2
Integer key = 9999; // Key not present
assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/BoyerMooreTest.java | src/test/java/com/thealgorithms/searches/BoyerMooreTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BoyerMooreTest {
@Test
public void testPatternFound() {
BoyerMoore bm = new BoyerMoore("ABCDABD");
String text = "ABC ABCDAB ABCDABCDABDE";
int index = bm.search(text);
assertEquals(15, index);
}
@Test
public void testPatternNotFound() {
BoyerMoore bm = new BoyerMoore("XYZ");
String text = "ABC ABCDAB ABCDABCDABDE";
int index = bm.search(text);
assertEquals(-1, index);
}
@Test
public void testPatternAtBeginning() {
BoyerMoore bm = new BoyerMoore("ABC");
String text = "ABCDEF";
int index = bm.search(text);
assertEquals(0, index);
}
@Test
public void testPatternAtEnd() {
BoyerMoore bm = new BoyerMoore("CDE");
String text = "ABCDEFGCDE";
int index = bm.search(text);
assertEquals(2, index); // Primera ocurrencia de "CDE"
}
@Test
public void testEmptyPattern() {
BoyerMoore bm = new BoyerMoore("");
String text = "Hello world";
int index = bm.search(text);
assertEquals(0, index);
}
@Test
public void testStaticSearchMethod() {
String text = "ABCDEFGCDE";
int index = BoyerMoore.staticSearch(text, "CDE");
assertEquals(2, index); // Primera ocurrencia de "CDE"
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/BinarySearchTest.java | src/test/java/com/thealgorithms/searches/BinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the BinarySearch class.
*/
class BinarySearchTest {
/**
* Test for basic binary search functionality.
*/
@Test
void testBinarySearchFound() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int key = 7;
int expectedIndex = 6; // Index of the key in the array
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the found element should be 6.");
}
/**
* Test for binary search when the element is not present.
*/
@Test
void testBinarySearchNotFound() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1, 2, 3, 4, 5};
int key = 6; // Element not present in the array
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for binary search with first element as the key.
*/
@Test
void testBinarySearchFirstElement() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1, 2, 3, 4, 5};
int key = 1; // First element
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for binary search with last element as the key.
*/
@Test
void testBinarySearchLastElement() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1, 2, 3, 4, 5};
int key = 5; // Last element
int expectedIndex = 4; // Index of the key in the array
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 4.");
}
/**
* Test for binary search with a single element present.
*/
@Test
void testBinarySearchSingleElementFound() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1};
int key = 1; // Only element present
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the single element should be 0.");
}
/**
* Test for binary search with a single element not present.
*/
@Test
void testBinarySearchSingleElementNotFound() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {1};
int key = 2; // Key not present
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for binary search with an empty array.
*/
@Test
void testBinarySearchEmptyArray() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = {}; // Empty array
int key = 1; // Key not present
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, binarySearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for binary search on large array.
*/
@Test
void testBinarySearchLargeArray() {
BinarySearch binarySearch = new BinarySearch();
Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999
int key = 9999; // Last element
int expectedIndex = 9999; // Index of the last element
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the last element should be 9999.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/IterativeBinarySearchTest.java | src/test/java/com/thealgorithms/searches/IterativeBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the IterativeBinarySearch class.
*/
class IterativeBinarySearchTest {
/**
* Test for basic binary search functionality when the element is found.
*/
@Test
void testBinarySearchFound() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
Integer key = 128;
int expectedIndex = 7; // Index of the key in the array
assertEquals(expectedIndex, binarySearch.find(array, key), "The index of the found element should be 7.");
}
/**
* Test for binary search when the element is not present in the array.
*/
@Test
void testBinarySearchNotFound() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 6; // Element not present in the array
assertEquals(-1, binarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for binary search with the first element as the key.
*/
@Test
void testBinarySearchFirstElement() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 1; // First element
assertEquals(0, binarySearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for binary search with the last element as the key.
*/
@Test
void testBinarySearchLastElement() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = 16; // Last element
assertEquals(4, binarySearch.find(array, key), "The index of the last element should be 4.");
}
/**
* Test for binary search with a single element present.
*/
@Test
void testBinarySearchSingleElementFound() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1};
Integer key = 1; // Only element present
assertEquals(0, binarySearch.find(array, key), "The index of the single element should be 0.");
}
/**
* Test for binary search with a single element not present.
*/
@Test
void testBinarySearchSingleElementNotFound() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {1};
Integer key = 2; // Key not present
assertEquals(-1, binarySearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for binary search with an empty array.
*/
@Test
void testBinarySearchEmptyArray() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = {}; // Empty array
Integer key = 1; // Key not present
assertEquals(-1, binarySearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for binary search on a large array.
*/
@Test
void testBinarySearchLargeArray() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = new Integer[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
} // Array from 0 to 19998, step 2
Integer key = 9998; // Present in the array
assertEquals(4999, binarySearch.find(array, key), "The index of the found element should be 4999.");
}
/**
* Test for binary search on large array with a non-existent key.
*/
@Test
void testBinarySearchLargeArrayNotFound() {
IterativeBinarySearch binarySearch = new IterativeBinarySearch();
Integer[] array = new Integer[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
} // Array from 0 to 19998, step 2
Integer key = 9999; // Key not present
assertEquals(-1, binarySearch.find(array, key), "The element should not be found in the array.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java | src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class SaddlebackSearchTest {
/**
* Test searching for an element that exists in the array.
*/
@Test
void testFindElementExists() {
int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}};
int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 4);
assertArrayEquals(new int[] {0, 3}, result, "Element 4 should be found at (0, 3)");
}
/**
* Test searching for an element that does not exist in the array.
*/
@Test
void testFindElementNotExists() {
int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}};
int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 1000);
assertArrayEquals(new int[] {-1, -1}, result, "Element 1000 should not be found");
}
/**
* Test searching for the smallest element in the array.
*/
@Test
void testFindSmallestElement() {
int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}};
int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, -10);
assertArrayEquals(new int[] {0, 0}, result, "Element -10 should be found at (0, 0)");
}
/**
* Test searching for the largest element in the array.
*/
@Test
void testFindLargestElement() {
int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}};
int[] result = SaddlebackSearch.find(arr, arr.length - 1, 0, 150);
assertArrayEquals(new int[] {4, 4}, result, "Element 150 should be found at (4, 4)");
}
/**
* Test searching in an empty array.
*/
@Test
void testFindInEmptyArray() {
int[][] arr = {};
assertThrows(IllegalArgumentException.class, () -> { SaddlebackSearch.find(arr, 0, 0, 4); });
}
/**
* Test searching in a single element array that matches the search key.
*/
@Test
void testFindSingleElementExists() {
int[][] arr = {{5}};
int[] result = SaddlebackSearch.find(arr, 0, 0, 5);
assertArrayEquals(new int[] {0, 0}, result, "Element 5 should be found at (0, 0)");
}
/**
* Test searching in a single element array that does not match the search key.
*/
@Test
void testFindSingleElementNotExists() {
int[][] arr = {{5}};
int[] result = SaddlebackSearch.find(arr, 0, 0, 10);
assertArrayEquals(new int[] {-1, -1}, result, "Element 10 should not be found in single element array");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/UnionFindTest.java | src/test/java/com/thealgorithms/searches/UnionFindTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UnionFindTest {
private UnionFind uf;
@BeforeEach
void setUp() {
uf = new UnionFind(10); // Initialize with 10 elements
}
@Test
void testInitialState() {
// Verify that each element is its own parent and rank is 0
assertEquals("p [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] r [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n", uf.toString());
assertEquals(10, uf.count(), "Initial count of disjoint sets should be 10.");
}
@Test
void testUnionOperation() {
uf.union(0, 1);
uf.union(1, 2);
assertEquals(8, uf.count(), "Count should decrease after unions.");
assertEquals(0, uf.find(2), "Element 2 should point to root 0 after unions.");
}
@Test
void testUnionWithRank() {
uf.union(0, 1);
uf.union(1, 2); // Make 0 the root of 2
uf.union(3, 4);
uf.union(4, 5); // Make 3 the root of 5
uf.union(0, 3); // Union two trees
assertEquals(5, uf.count(), "Count should decrease after unions.");
assertEquals(0, uf.find(5), "Element 5 should point to root 0 after unions.");
}
@Test
void testFindOperation() {
uf.union(2, 3);
uf.union(4, 5);
uf.union(3, 5); // Connect 2-3 and 4-5
assertEquals(2, uf.find(3), "Find operation should return the root of the set.");
assertEquals(2, uf.find(5), "Find operation should return the root of the set.");
}
@Test
void testCountAfterMultipleUnions() {
uf.union(0, 1);
uf.union(2, 3);
uf.union(4, 5);
uf.union(1, 3); // Connect 0-1-2-3
uf.union(5, 6);
assertEquals(5, uf.count(), "Count should reflect the number of disjoint sets after multiple unions.");
}
@Test
void testNoUnion() {
assertEquals(10, uf.count(), "Count should remain 10 if no unions are made.");
}
@Test
void testUnionSameSet() {
uf.union(1, 2);
uf.union(1, 2); // Union same elements again
assertEquals(9, uf.count(), "Count should not decrease if union is called on the same set.");
}
@Test
void testFindOnSingleElement() {
assertEquals(7, uf.find(7), "Find on a single element should return itself.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/KMPSearchTest.java | src/test/java/com/thealgorithms/searches/KMPSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class KMPSearchTest {
@Test
// valid test case
public void kmpSearchTestLast() {
String txt = "ABABDABACDABABCABAB";
String pat = "ABABCABAB";
KMPSearch kmpSearch = new KMPSearch();
int value = kmpSearch.kmpSearch(pat, txt);
System.out.println(value);
assertEquals(value, 10);
}
@Test
// valid test case
public void kmpSearchTestFront() {
String txt = "AAAAABAAABA";
String pat = "AAAA";
KMPSearch kmpSearch = new KMPSearch();
int value = kmpSearch.kmpSearch(pat, txt);
System.out.println(value);
assertEquals(value, 0);
}
@Test
// valid test case
public void kmpSearchTestMiddle() {
String txt = "AAACAAAAAC";
String pat = "AAAA";
KMPSearch kmpSearch = new KMPSearch();
int value = kmpSearch.kmpSearch(pat, txt);
System.out.println(value);
assertEquals(value, 4);
}
@Test
// valid test case
public void kmpSearchTestNotFound() {
String txt = "AAABAAAA";
String pat = "AAAA";
KMPSearch kmpSearch = new KMPSearch();
int value = kmpSearch.kmpSearch(pat, txt);
System.out.println(value);
assertEquals(value, 4);
}
@Test
// not valid test case
public void kmpSearchTest4() {
String txt = "AABAAA";
String pat = "AAAA";
KMPSearch kmpSearch = new KMPSearch();
int value = kmpSearch.kmpSearch(pat, txt);
System.out.println(value);
assertEquals(value, -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/searches/SquareRootBinarySearchTest.java | src/test/java/com/thealgorithms/searches/SquareRootBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SquareRootBinarySearchTest {
@Test
void testPerfectSquare() {
long input = 16;
long expected = 4;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 16 should be 4");
}
@Test
void testNonPerfectSquare() {
long input = 15;
long expected = 3;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 15 should be 3");
}
@Test
void testZero() {
long input = 0;
long expected = 0;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 0 should be 0");
}
@Test
void testOne() {
long input = 1;
long expected = 1;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 1 should be 1");
}
@Test
void testLargeNumberPerfectSquare() {
long input = 1000000;
long expected = 1000;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 1000000 should be 1000");
}
@Test
void testLargeNumberNonPerfectSquare() {
long input = 999999;
long expected = 999;
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of 999999 should be 999");
}
@Test
void testNegativeInput() {
long input = -4;
long expected = 0; // Assuming the implementation should return 0 for negative input
assertEquals(expected, SquareRootBinarySearch.squareRoot(input), "Square root of negative number should return 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/searches/JumpSearchTest.java | src/test/java/com/thealgorithms/searches/JumpSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the JumpSearch class.
*/
class JumpSearchTest {
/**
* Test for finding an element present in the array.
*/
@Test
void testJumpSearchFound() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 5; // Element to find
assertEquals(5, jumpSearch.find(array, key), "The index of the found element should be 5.");
}
/**
* Test for finding the first element in the array.
*/
@Test
void testJumpSearchFirstElement() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 0; // First element
assertEquals(0, jumpSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for finding the last element in the array.
*/
@Test
void testJumpSearchLastElement() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 10; // Last element
assertEquals(10, jumpSearch.find(array, key), "The index of the last element should be 10.");
}
/**
* Test for finding an element not present in the array.
*/
@Test
void testJumpSearchNotFound() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = -1; // Element not in the array
assertEquals(-1, jumpSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for finding an element in an empty array.
*/
@Test
void testJumpSearchEmptyArray() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {}; // Empty array
Integer key = 1; // Key not present
assertEquals(-1, jumpSearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for finding an element in a large array.
*/
@Test
void testJumpSearchLargeArray() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2; // Fill the array with even numbers
}
Integer key = 256; // Present in the array
assertEquals(128, jumpSearch.find(array, key), "The index of the found element should be 128.");
}
/**
* Test for finding an element in a large array when it is not present.
*/
@Test
void testJumpSearchLargeArrayNotFound() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i * 2; // Fill the array with even numbers
}
Integer key = 999; // Key not present
assertEquals(-1, jumpSearch.find(array, key), "The element should not be found in the array.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java | src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SortOrderAgnosticBinarySearchTest {
@Test
public void testAscending() {
int[] arr = {1, 2, 3, 4, 5}; // for ascending order.
int target = 2;
int ans = SortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 1;
assertEquals(excepted, ans);
}
@Test
public void testDescending() {
int[] arr = {5, 4, 3, 2, 1}; // for descending order.
int target = 2;
int ans = SortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 3;
assertEquals(excepted, ans);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java | src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.datastructures.Node;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BreadthFirstSearchTest {
private Node<String> root;
private BreadthFirstSearch<String> bfs;
// Tree structure:
//
// A
// / | \
// B C D
// / \
// E F
@BeforeEach
public void setUp() {
// nodes declaration
root = new Node<>("A");
var nodeB = new Node<>("B");
var nodeC = new Node<>("C");
var nodeD = new Node<>("D");
var nodeE = new Node<>("E");
var nodeF = new Node<>("F");
// tree initialization
root.addChild(nodeB);
root.addChild(nodeC);
root.addChild(nodeD);
nodeB.addChild(nodeE);
nodeB.addChild(nodeF);
// create an instance to monitor the visited nodes
bfs = new BreadthFirstSearch<>();
}
@Test
public void testSearchRoot() {
String expectedValue = "A";
List<String> expectedPath = List.of("A");
// check value
Optional<Node<String>> value = bfs.search(root, expectedValue);
assertEquals(expectedValue, value.orElseGet(() -> new Node<>("")).getValue());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
public void testSearchF() {
String expectedValue = "F";
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
// check value
Optional<Node<String>> value = Optional.of(bfs.search(root, expectedValue).orElseGet(() -> new Node<>(null)));
assertEquals(expectedValue, value.get().getValue());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
void testSearchNull() {
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
Optional<Node<String>> node = bfs.search(root, null);
// check value
assertTrue(node.isEmpty());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
void testNullRoot() {
var value = bfs.search(null, "B");
assertTrue(value.isEmpty());
}
@Test
void testSearchValueThatNotExists() {
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
var value = bfs.search(root, "Z");
// check that the value is empty because it's not exists in the tree
assertTrue(value.isEmpty());
// check path is the whole list
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java | src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the ExponentialSearch class.
*/
class ExponentialSearchTest {
/**
* Test for basic exponential search functionality.
*/
@Test
void testExponentialSearchFound() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int key = 7;
int expectedIndex = 6; // Index of the key in the array
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the found element should be 6.");
}
/**
* Test for exponential search with the first element as the key.
*/
@Test
void testExponentialSearchFirstElement() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = {1, 2, 3, 4, 5};
int key = 1; // First element
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for exponential search with the last element as the key.
*/
@Test
void testExponentialSearchLastElement() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = {1, 2, 3, 4, 5};
int key = 5; // Last element
int expectedIndex = 4; // Index of the key in the array
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the last element should be 4.");
}
/**
* Test for exponential search with a single element present.
*/
@Test
void testExponentialSearchSingleElementFound() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = {1};
int key = 1; // Only element present
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the single element should be 0.");
}
/**
* Test for exponential search with an empty array.
*/
@Test
void testExponentialSearchEmptyArray() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = {}; // Empty array
int key = 1; // Key not present
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for exponential search on large array.
*/
@Test
void testExponentialSearchLargeArray() {
ExponentialSearch exponentialSearch = new ExponentialSearch();
Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999
int key = 9999;
int expectedIndex = 9999;
assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the last element should be 9999.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java | src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the FibonacciSearch class.
*/
class FibonacciSearchTest {
/**
* Test for basic Fibonacci search functionality.
*/
@Test
void testFibonacciSearchFound() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
int key = 128;
int expectedIndex = 7; // Index of the key in the array
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the found element should be 7.");
}
/**
* Test for Fibonacci search when the element is not present.
*/
@Test
void testFibonacciSearchNotFound() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1, 2, 4, 8, 16};
int key = 6; // Element not present in the array
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for Fibonacci search with the first element as the key.
*/
@Test
void testFibonacciSearchFirstElement() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1, 2, 4, 8, 16};
int key = 1; // First element
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for Fibonacci search with the last element as the key.
*/
@Test
void testFibonacciSearchLastElement() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1, 2, 4, 8, 16};
int key = 16; // Last element
int expectedIndex = 4; // Index of the key in the array
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the last element should be 4.");
}
/**
* Test for Fibonacci search with a single element present.
*/
@Test
void testFibonacciSearchSingleElementFound() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1};
int key = 1; // Only element present
int expectedIndex = 0; // Index of the key in the array
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the single element should be 0.");
}
/**
* Test for Fibonacci search with a single element not present.
*/
@Test
void testFibonacciSearchSingleElementNotFound() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1};
int key = 2; // Key not present
int expectedIndex = -1; // Key not found
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for Fibonacci search with an empty array.
*/
@Test
void testFibonacciSearchEmptyArray() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {}; // Empty array
int key = 1; // Key not present
assertThrows(IllegalArgumentException.class, () -> fibonacciSearch.find(array, key), "An empty array should throw an IllegalArgumentException.");
}
@Test
void testFibonacciSearchUnsortedArray() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {2, 1, 4, 3, 6, 5};
int key = 3; // Key not present
assertThrows(IllegalArgumentException.class, () -> fibonacciSearch.find(array, key), "An unsorted array should throw an IllegalArgumentException.");
}
@Test
void testFibonacciSearchNullKey() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {1, 2, 4, 8, 16};
Integer key = null; // Null key
assertThrows(IllegalArgumentException.class, () -> fibonacciSearch.find(array, key), "A null key should throw an IllegalArgumentException.");
}
/**
* Test for Fibonacci search on large array.
*/
@Test
void testFibonacciSearchLargeArray() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999
int key = 9999;
int expectedIndex = 9999;
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the last element should be 9999.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java | src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class HowManyTimesRotatedTest {
@Test
public void testHowManyTimesRotated() {
int[] arr1 = {5, 1, 2, 3, 4};
assertEquals(1, HowManyTimesRotated.rotated(arr1));
int[] arr2 = {15, 17, 2, 3, 5};
assertEquals(2, HowManyTimesRotated.rotated(arr2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java | src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class TestSearchInARowAndColWiseSortedMatrix {
@Test
public void searchItem() {
int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}};
var test = new SearchInARowAndColWiseSortedMatrix();
int[] res = test.search(matrix, 16);
int[] expectedResult = {2, 2};
assertArrayEquals(expectedResult, res);
}
@Test
public void notFound() {
int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}};
var test = new SearchInARowAndColWiseSortedMatrix();
int[] res = test.search(matrix, 96);
int[] expectedResult = {-1, -1};
assertArrayEquals(expectedResult, res);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/PerfectBinarySearchTest.java | src/test/java/com/thealgorithms/searches/PerfectBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* @author D Sunil (https://github.com/sunilnitdgp)
* @see PerfectBinarySearch
*/
public class PerfectBinarySearchTest {
@Test
public void testIntegerBinarySearch() {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
PerfectBinarySearch<Integer> binarySearch = new PerfectBinarySearch<>();
// Test cases for elements present in the array
assertEquals(0, binarySearch.find(array, 1)); // First element
assertEquals(4, binarySearch.find(array, 5)); // Middle element
assertEquals(9, binarySearch.find(array, 10)); // Last element
assertEquals(6, binarySearch.find(array, 7)); // Element in the middle
// Test cases for elements not in the array
assertEquals(-1, binarySearch.find(array, 0)); // Element before the array
assertEquals(-1, binarySearch.find(array, 11)); // Element after the array
assertEquals(-1, binarySearch.find(array, 100)); // Element not in the array
}
@Test
public void testStringBinarySearch() {
String[] array = {"apple", "banana", "cherry", "date", "fig"};
PerfectBinarySearch<String> binarySearch = new PerfectBinarySearch<>();
// Test cases for elements not in the array
assertEquals(-1, binarySearch.find(array, "apricot")); // Element not in the array
assertEquals(-1, binarySearch.find(array, "bananaa")); // Element not in the array
// Test cases for elements present in the array
assertEquals(0, binarySearch.find(array, "apple")); // First element
assertEquals(2, binarySearch.find(array, "cherry")); // Middle element
assertEquals(4, binarySearch.find(array, "fig")); // Last element
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java | src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the InterpolationSearch class.
*/
class InterpolationSearchTest {
/**
* Test for basic interpolation search functionality when the element is found.
*/
@Test
void testInterpolationSearchFound() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
int key = 128;
int expectedIndex = 7; // Index of the key in the array
assertEquals(expectedIndex, interpolationSearch.find(array, key), "The index of the found element should be 7.");
}
/**
* Test for interpolation search when the element is not present in the array.
*/
@Test
void testInterpolationSearchNotFound() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {1, 2, 4, 8, 16};
int key = 6; // Element not present in the array
assertEquals(-1, interpolationSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for interpolation search with the first element as the key.
*/
@Test
void testInterpolationSearchFirstElement() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {1, 2, 4, 8, 16};
int key = 1; // First element
assertEquals(0, interpolationSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for interpolation search with a single element not present.
*/
@Test
void testInterpolationSearchSingleElementNotFound() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {1};
int key = 2; // Key not present
assertEquals(-1, interpolationSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for interpolation search with an empty array.
*/
@Test
void testInterpolationSearchEmptyArray() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {}; // Empty array
int key = 1; // Key not present
assertEquals(-1, interpolationSearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for interpolation search on large uniformly distributed array.
*/
@Test
void testInterpolationSearchLargeUniformArray() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = IntStream.range(0, 10000).map(i -> i * 2).toArray(); // Array from 0 to 19998, step 2
int key = 9998; // Last even number in the array
assertEquals(4999, interpolationSearch.find(array, key), "The index of the last element should be 4999.");
}
/**
* Test for interpolation search on large non-uniformly distributed array.
*/
@Test
void testInterpolationSearchLargeNonUniformArray() {
InterpolationSearch interpolationSearch = new InterpolationSearch();
int[] array = {1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}; // Fibonacci numbers
int key = 21; // Present in the array
assertEquals(6, interpolationSearch.find(array, key), "The index of the found element should be 6.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java | src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class OrderAgnosticBinarySearchTest {
@Test
// valid Test Case
public void elementInMiddle() {
int[] arr = {10, 20, 30, 40, 50};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 30);
System.out.println(answer);
int expected = 2;
assertEquals(expected, answer);
}
@Test
// valid Test Case
public void rightHalfDescOrder() {
int[] arr = {50, 40, 30, 20, 10};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 10);
System.out.println(answer);
int expected = 4;
assertEquals(expected, answer);
}
@Test
// valid test case
public void leftHalfDescOrder() {
int[] arr = {50, 40, 30, 20, 10};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 50);
System.out.println(answer);
int expected = 0;
assertEquals(expected, answer);
}
@Test
// valid test case
public void rightHalfAscOrder() {
int[] arr = {10, 20, 30, 40, 50};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 50);
System.out.println(answer);
int expected = 4;
assertEquals(expected, answer);
}
@Test
// valid test case
public void leftHalfAscOrder() {
int[] arr = {10, 20, 30, 40, 50};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 10);
System.out.println(answer);
int expected = 0;
assertEquals(expected, answer);
}
@Test
// valid test case
public void elementNotFound() {
int[] arr = {10, 20, 30, 40, 50};
int answer = OrderAgnosticBinarySearch.binSearchAlgo(arr, 0, arr.length - 1, 100);
System.out.println(answer);
int expected = -1;
assertEquals(expected, answer);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/RandomSearchTest.java | src/test/java/com/thealgorithms/searches/RandomSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class RandomSearchTest {
private RandomSearch randomSearch;
@BeforeEach
void setUp() {
randomSearch = new RandomSearch();
}
@Test
void testElementFound() {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 5;
int index = randomSearch.find(array, key);
assertNotEquals(-1, index, "Element should be found in the array.");
assertEquals(key, array[index], "Element found should match the key.");
}
@Test
void testElementNotFound() {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 11;
int index = randomSearch.find(array, key);
assertEquals(-1, index, "Element not present in the array should return -1.");
}
@Test
void testEmptyArray() {
Integer[] emptyArray = {};
Integer key = 5;
int index = randomSearch.find(emptyArray, key);
assertEquals(-1, index, "Searching in an empty array should return -1.");
}
@Test
void testSingleElementArrayFound() {
Integer[] array = {5};
Integer key = 5;
int index = randomSearch.find(array, key);
assertEquals(0, index, "The key should be found at index 0 in a single-element array.");
}
@Test
void testSingleElementArrayNotFound() {
Integer[] array = {1};
Integer key = 5;
int index = randomSearch.find(array, key);
assertEquals(-1, index, "The key should not be found in a single-element array if it does not match.");
}
@Test
void testDuplicateElementsFound() {
Integer[] array = {1, 2, 3, 4, 5, 5, 5, 7, 8, 9, 10};
Integer key = 5;
int index = randomSearch.find(array, key);
assertNotEquals(-1, index, "The key should be found in the array with duplicates.");
assertEquals(key, array[index], "The key found should be 5.");
}
@Test
void testLargeArray() {
Integer[] largeArray = new Integer[1000];
for (int i = 0; i < largeArray.length; i++) {
largeArray[i] = i + 1; // Fill with values 1 to 1000
}
Integer key = 500;
int index = randomSearch.find(largeArray, key);
assertNotEquals(-1, index, "The key should be found in the large array.");
assertEquals(key, largeArray[index], "The key found should match 500.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/LinearSearchThreadTest.java | src/test/java/com/thealgorithms/searches/LinearSearchThreadTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class LinearSearchThreadTest {
/**
* Test for finding an element that is present in the array.
*/
@Test
void testSearcherFound() throws InterruptedException {
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Searcher searcher = new Searcher(array, 0, array.length, 5);
searcher.start();
searcher.join();
assertTrue(searcher.getResult(), "The element 5 should be found in the array.");
}
/**
* Test for finding an element that is not present in the array.
*/
@Test
void testSearcherNotFound() throws InterruptedException {
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Searcher searcher = new Searcher(array, 0, array.length, 11);
searcher.start();
searcher.join();
assertFalse(searcher.getResult(), "The element 11 should not be found in the array.");
}
/**
* Test for searching a segment of the array.
*/
@Test
void testSearcherSegmentFound() throws InterruptedException {
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Searcher searcher = new Searcher(array, 0, 5, 3);
searcher.start();
searcher.join();
assertTrue(searcher.getResult(), "The element 3 should be found in the segment.");
}
/**
* Test for searching an empty array segment.
*/
@Test
void testSearcherEmptySegment() throws InterruptedException {
int[] array = {};
Searcher searcher = new Searcher(array, 0, 0, 1); // Empty array
searcher.start();
searcher.join();
assertFalse(searcher.getResult(), "The element should not be found in an empty segment.");
}
/**
* Test for searching with random numbers.
*/
@Test
void testSearcherRandomNumbers() throws InterruptedException {
int size = 200;
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = (int) (Math.random() * 100);
}
int target = array[(int) (Math.random() * size)]; // Randomly select a target that is present
Searcher searcher = new Searcher(array, 0, size, target);
searcher.start();
searcher.join();
assertTrue(searcher.getResult(), "The randomly selected target should be found in the array.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/TernarySearchTest.java | src/test/java/com/thealgorithms/searches/TernarySearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TernarySearchTest {
@Test
void testFindElementInSortedArray() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TernarySearch search = new TernarySearch();
int index = search.find(arr, 5);
assertEquals(4, index, "Should find the element 5 at index 4");
}
@Test
void testElementNotFound() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TernarySearch search = new TernarySearch();
int index = search.find(arr, 11);
assertEquals(-1, index, "Should return -1 for element 11 which is not present");
}
@Test
void testFindFirstElement() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TernarySearch search = new TernarySearch();
int index = search.find(arr, 1);
assertEquals(0, index, "Should find the first element 1 at index 0");
}
@Test
void testFindLastElement() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TernarySearch search = new TernarySearch();
int index = search.find(arr, 10);
assertEquals(9, index, "Should find the last element 10 at index 9");
}
@Test
void testFindInLargeArray() {
Integer[] arr = new Integer[1000];
for (int i = 0; i < 1000; i++) {
arr[i] = i + 1; // Array from 1 to 1000
}
TernarySearch search = new TernarySearch();
int index = search.find(arr, 500);
assertEquals(499, index, "Should find element 500 at index 499");
}
@Test
void testNegativeNumbers() {
Integer[] arr = {-10, -5, -3, -1, 0, 1, 3, 5, 7, 10};
TernarySearch search = new TernarySearch();
int index = search.find(arr, -3);
assertEquals(2, index, "Should find the element -3 at index 2");
}
@Test
void testEdgeCaseEmptyArray() {
Integer[] arr = {};
TernarySearch search = new TernarySearch();
int index = search.find(arr, 5);
assertEquals(-1, index, "Should return -1 for an empty array");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java | src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.datastructures.Node;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DepthFirstSearchTest {
private Node<Integer> root;
private DepthFirstSearch<Integer> dfs;
//
// Tree structure:
// 1
// / | \
// 2 3 4
// / \
// 5 6
@BeforeEach
public void setUp() {
// nodes declaration
root = new Node<>(1);
var nodeB = new Node<>(2);
var nodeC = new Node<>(3);
var nodeD = new Node<>(4);
var nodeE = new Node<>(5);
var nodeF = new Node<>(6);
// tree initialization
root.addChild(nodeB);
root.addChild(nodeC);
root.addChild(nodeD);
nodeB.addChild(nodeE);
nodeB.addChild(nodeF);
// create an instance to monitor the visited nodes
dfs = new DepthFirstSearch<>();
}
@Test
public void testSearchRoot() {
Integer expectedValue = 1;
List<Integer> expectedPath = List.of(1);
// check value
Optional<Node<Integer>> value = dfs.recursiveSearch(root, expectedValue);
assertEquals(expectedValue, value.orElseGet(() -> new Node<>(null)).getValue());
// check path
assertArrayEquals(expectedPath.toArray(), dfs.getVisited().toArray());
}
@Test
public void testSearch4() {
Integer expectedValue = 4;
List<Integer> expectedPath = List.of(1, 2, 5, 6, 3, 4);
// check value
Optional<Node<Integer>> value = dfs.recursiveSearch(root, expectedValue);
assertEquals(expectedValue, value.orElseGet(() -> new Node<>(null)).getValue());
// check path
assertArrayEquals(expectedPath.toArray(), dfs.getVisited().toArray());
}
@Test
void testNullRoot() {
var value = dfs.recursiveSearch(null, 4);
assertTrue(value.isEmpty());
}
@Test
void testSearchValueThatNotExists() {
List<Integer> expectedPath = List.of(1, 2, 5, 6, 3, 4);
var value = dfs.recursiveSearch(root, 10);
// check that the value is empty because it's not exists in the tree
assertTrue(value.isEmpty());
// check path is the whole list
assertArrayEquals(expectedPath.toArray(), dfs.getVisited().toArray());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java | src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class RabinKarpAlgorithmTest {
@ParameterizedTest
@CsvSource({"This is an example for rabin karp algorithmn, algorithmn, 101", "AAABBDDG, AAA, 137", "AAABBCCBB, BBCC, 101", "AAABBCCBB, BBCC, 131", "AAAABBBBCCC, CCC, 41", "ABCBCBCAAB, AADB, 293", "Algorithm The Algorithm, Algorithm, 101"})
void rabinKarpAlgorithmTestExample(String txt, String pat, int q) {
int indexFromOurAlgorithm = RabinKarpAlgorithm.search(pat, txt, q);
int indexFromLinearSearch = txt.indexOf(pat);
assertEquals(indexFromOurAlgorithm, indexFromLinearSearch);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java | src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java | package com.thealgorithms.searches;
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.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* Test Cases for Inverted Index with BM25
* @author Prayas Kumar (https://github.com/prayas7102)
*/
class BM25InvertedIndexTest {
private static BM25InvertedIndex index;
@BeforeAll
static void setUp() {
index = new BM25InvertedIndex();
index.addMovie(1, "The Shawshank Redemption", 9.3, 1994, "Hope is a good thing. Maybe the best of things. And no good thing ever dies.");
index.addMovie(2, "The Godfather", 9.2, 1972, "I'm gonna make him an offer he can't refuse.");
index.addMovie(3, "The Dark Knight", 9.0, 2008, "You either die a hero or live long enough to see yourself become the villain.");
index.addMovie(4, "Pulp Fiction", 8.9, 1994, "You know what they call a Quarter Pounder with Cheese in Paris? They call it a Royale with Cheese.");
index.addMovie(5, "Good Will Hunting", 8.3, 1997, "Will Hunting is a genius and he has a good heart. The best of his abilities is yet to be explored.");
index.addMovie(6, "It's a Wonderful Life", 8.6, 1946, "Each man's life touches so many other lives. If he wasn't around, it would leave an awfully good hole.");
index.addMovie(7, "The Pursuit of Happyness", 8.0, 2006, "It was the pursuit of a better life, and a good opportunity to change things for the better.");
index.addMovie(8, "A Few Good Men", 7.7, 1992, "You can't handle the truth! This movie has a lot of good moments and intense drama.");
}
@Test
void testAddMovie() {
// Check that the index contains the correct number of movies
int moviesLength = index.getMoviesLength();
assertEquals(8, moviesLength);
}
@Test
void testSearchForTermFound() {
int expected = 1;
List<SearchResult> result = index.search("hope");
int actual = result.getFirst().getDocId();
assertEquals(expected, actual);
}
@Test
void testSearchRanking() {
// Perform search for the term "good"
List<SearchResult> results = index.search("good");
assertFalse(results.isEmpty());
for (SearchResult result : results) {
System.out.println(result);
}
// Validate the ranking based on the provided relevance scores
assertEquals(1, results.get(0).getDocId()); // The Shawshank Redemption should be ranked 1st
assertEquals(8, results.get(1).getDocId()); // A Few Good Men should be ranked 2nd
assertEquals(5, results.get(2).getDocId()); // Good Will Hunting should be ranked 3rd
assertEquals(7, results.get(3).getDocId()); // The Pursuit of Happyness should be ranked 4th
assertEquals(6, results.get(4).getDocId()); // It's a Wonderful Life should be ranked 5th
// Ensure the relevance scores are in descending order
for (int i = 0; i < results.size() - 1; i++) {
assertTrue(results.get(i).getRelevanceScore() > results.get(i + 1).getRelevanceScore());
}
}
@Test
void testSearchForTermNotFound() {
List<SearchResult> results = index.search("nonexistent");
assertTrue(results.isEmpty());
}
@Test
void testSearchForCommonTerm() {
List<SearchResult> results = index.search("the");
assertFalse(results.isEmpty());
assertTrue(results.size() > 1);
}
@Test
void testBM25ScoreCalculation() {
List<SearchResult> results = index.search("cheese");
assertEquals(1, results.size());
assertEquals(4, results.getFirst().docId); // Pulp Fiction should have the highest score
}
@Test
void testCaseInsensitivity() {
List<SearchResult> resultsLowerCase = index.search("hope");
List<SearchResult> resultsUpperCase = index.search("HOPE");
assertEquals(resultsLowerCase, resultsUpperCase);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/LowerBoundTest.java | src/test/java/com/thealgorithms/searches/LowerBoundTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class LowerBoundTest {
/**
* Test finding the lower bound for an element present in the array.
*/
@Test
void testLowerBoundElementPresent() {
Integer[] array = {1, 2, 3, 4, 5};
LowerBound lowerBound = new LowerBound();
// Test for a value that is present
assertEquals(2, lowerBound.find(array, 3), "Lower bound for 3 should be at index 2");
assertEquals(0, lowerBound.find(array, 1), "Lower bound for 1 should be at index 0");
assertEquals(4, lowerBound.find(array, 5), "Lower bound for 5 should be at index 4");
}
/**
* Test finding the lower bound for a value greater than the maximum element in the array.
*/
@Test
void testLowerBoundElementGreaterThanMax() {
Integer[] array = {1, 2, 3, 4, 5};
LowerBound lowerBound = new LowerBound();
// Test for a value greater than the maximum
assertEquals(4, lowerBound.find(array, 6), "Lower bound for 6 should be at index 4");
}
/**
* Test finding the lower bound for a value less than the minimum element in the array.
*/
@Test
void testLowerBoundElementLessThanMin() {
Integer[] array = {1, 2, 3, 4, 5};
LowerBound lowerBound = new LowerBound();
// Test for a value less than the minimum
assertEquals(0, lowerBound.find(array, 0), "Lower bound for 0 should be at index 0");
}
/**
* Test finding the lower bound for a non-existent value that falls between two elements.
*/
@Test
void testLowerBoundNonExistentValue() {
Integer[] array = {1, 2, 3, 4, 5};
LowerBound lowerBound = new LowerBound();
// Test for a value that is not present
assertEquals(4, lowerBound.find(array, 7), "Lower bound for 7 should be at index 4");
assertEquals(0, lowerBound.find(array, 0), "Lower bound for 0 should be at index 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/searches/LinearSearchTest.java | src/test/java/com/thealgorithms/searches/LinearSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Random;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the LinearSearch class.
*/
class LinearSearchTest {
/**
* Test for finding an element present in the array.
*/
@Test
void testLinearSearchFound() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 5; // Element to find
assertEquals(5, linearSearch.find(array, key), "The index of the found element should be 5.");
}
/**
* Test for finding the first element in the array.
*/
@Test
void testLinearSearchFirstElement() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 0; // First element
assertEquals(0, linearSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for finding the last element in the array.
*/
@Test
void testLinearSearchLastElement() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 10; // Last element
assertEquals(10, linearSearch.find(array, key), "The index of the last element should be 10.");
}
/**
* Test for finding an element not present in the array.
*/
@Test
void testLinearSearchNotFound() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = -1; // Element not in the array
assertEquals(-1, linearSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for finding an element in an empty array.
*/
@Test
void testLinearSearchEmptyArray() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {}; // Empty array
Integer key = 1; // Key not present
assertEquals(-1, linearSearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for finding an element in a large array.
*/
@Test
void testLinearSearchLargeArray() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i; // Fill the array with integers 0 to 999
}
Integer key = 256; // Present in the array
assertEquals(256, linearSearch.find(array, key), "The index of the found element should be 256.");
}
/**
* Test for finding an element in a large array when it is not present.
*/
@Test
void testLinearSearchLargeArrayNotFound() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i; // Fill the array with integers 0 to 999
}
Integer key = 1001; // Key not present
assertEquals(-1, linearSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for finding multiple occurrences of the same element in the array.
*/
@Test
void testLinearSearchMultipleOccurrences() {
LinearSearch linearSearch = new LinearSearch();
Integer[] array = {1, 2, 3, 4, 5, 3, 6, 7, 3}; // 3 occurs multiple times
Integer key = 3; // Key to find
assertEquals(2, linearSearch.find(array, key), "The index of the first occurrence of the element should be 2.");
}
/**
* Test for performance with random large array.
*/
@Test
void testLinearSearchRandomArray() {
LinearSearch linearSearch = new LinearSearch();
Random random = new Random();
Integer[] array = random.ints(0, 1000).distinct().limit(1000).boxed().toArray(Integer[] ::new);
Integer key = array[random.nextInt(array.length)]; // Key should be in the array
assertEquals(java.util.Arrays.asList(array).indexOf(key), linearSearch.find(array, key), "The index of the found element should match.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/SentinelLinearSearchTest.java | src/test/java/com/thealgorithms/searches/SentinelLinearSearchTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Random;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the SentinelLinearSearch class.
*/
class SentinelLinearSearchTest {
/**
* Test for finding an element present in the array.
*/
@Test
void testSentinelLinearSearchFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 5; // Element to find
assertEquals(5, sentinelLinearSearch.find(array, key), "The index of the found element should be 5.");
}
/**
* Test for finding the first element in the array.
*/
@Test
void testSentinelLinearSearchFirstElement() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 0; // First element
assertEquals(0, sentinelLinearSearch.find(array, key), "The index of the first element should be 0.");
}
/**
* Test for finding the last element in the array.
*/
@Test
void testSentinelLinearSearchLastElement() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = 10; // Last element
assertEquals(10, sentinelLinearSearch.find(array, key), "The index of the last element should be 10.");
}
/**
* Test for finding an element not present in the array.
*/
@Test
void testSentinelLinearSearchNotFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer key = -1; // Element not in the array
assertEquals(-1, sentinelLinearSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for finding an element in an empty array.
*/
@Test
void testSentinelLinearSearchEmptyArray() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {}; // Empty array
Integer key = 1; // Key not present
assertEquals(-1, sentinelLinearSearch.find(array, key), "The element should not be found in an empty array.");
}
/**
* Test for finding an element in a single-element array when present.
*/
@Test
void testSentinelLinearSearchSingleElementFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {42}; // Single element array
Integer key = 42; // Element present
assertEquals(0, sentinelLinearSearch.find(array, key), "The element should be found at index 0.");
}
/**
* Test for finding an element in a single-element array when not present.
*/
@Test
void testSentinelLinearSearchSingleElementNotFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {42}; // Single element array
Integer key = 24; // Element not present
assertEquals(-1, sentinelLinearSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for finding multiple occurrences of the same element in the array.
*/
@Test
void testSentinelLinearSearchMultipleOccurrences() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {1, 2, 3, 4, 5, 3, 6, 7, 3}; // 3 occurs multiple times
Integer key = 3; // Key to find
assertEquals(2, sentinelLinearSearch.find(array, key), "The index of the first occurrence of the element should be 2.");
}
/**
* Test for finding an element in a large array.
*/
@Test
void testSentinelLinearSearchLargeArray() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i; // Fill the array with integers 0 to 999
}
Integer key = 256; // Present in the array
assertEquals(256, sentinelLinearSearch.find(array, key), "The index of the found element should be 256.");
}
/**
* Test for finding an element in a large array when it is not present.
*/
@Test
void testSentinelLinearSearchLargeArrayNotFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = new Integer[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i; // Fill the array with integers 0 to 999
}
Integer key = 1001; // Key not present
assertEquals(-1, sentinelLinearSearch.find(array, key), "The element should not be found in the array.");
}
/**
* Test for performance with random large array.
*/
@Test
void testSentinelLinearSearchRandomArray() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Random random = new Random();
Integer[] array = random.ints(0, 1000).distinct().limit(1000).boxed().toArray(Integer[] ::new);
Integer key = array[random.nextInt(array.length)]; // Key should be in the array
assertEquals(java.util.Arrays.asList(array).indexOf(key), sentinelLinearSearch.find(array, key), "The index of the found element should match.");
}
/**
* Test for handling null array.
*/
@Test
void testSentinelLinearSearchNullArray() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = null; // Null array
Integer key = 1; // Any key
assertThrows(IllegalArgumentException.class, () -> sentinelLinearSearch.find(array, key), "Should throw IllegalArgumentException for null array.");
}
/**
* Test for handling null key in array with null elements.
*/
@Test
void testSentinelLinearSearchNullKey() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {1, null, 3, 4, null}; // Array with null elements
Integer key = null; // Null key
assertEquals(1, sentinelLinearSearch.find(array, key), "The index of the first null element should be 1.");
}
/**
* Test for handling null key when not present in array.
*/
@Test
void testSentinelLinearSearchNullKeyNotFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {1, 2, 3, 4, 5}; // Array without null elements
Integer key = null; // Null key
assertEquals(-1, sentinelLinearSearch.find(array, key), "Null key should not be found in array without null elements.");
}
/**
* Test with String array to verify generic functionality.
*/
@Test
void testSentinelLinearSearchStringArray() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
String[] array = {"apple", "banana", "cherry", "date", "elderberry"};
String key = "cherry"; // Element to find
assertEquals(2, sentinelLinearSearch.find(array, key), "The index of 'cherry' should be 2.");
}
/**
* Test with String array when element not found.
*/
@Test
void testSentinelLinearSearchStringArrayNotFound() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
String[] array = {"apple", "banana", "cherry", "date", "elderberry"};
String key = "grape"; // Element not in array
assertEquals(-1, sentinelLinearSearch.find(array, key), "The element 'grape' should not be found in the array.");
}
/**
* Test that the original array is not modified after search.
*/
@Test
void testSentinelLinearSearchArrayIntegrity() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {1, 2, 3, 4, 5};
Integer[] originalArray = array.clone(); // Keep a copy of the original
Integer key = 3; // Element to find
sentinelLinearSearch.find(array, key);
// Verify array is unchanged
for (int i = 0; i < array.length; i++) {
assertEquals(originalArray[i], array[i], "Array should remain unchanged after search.");
}
}
/**
* Test edge case where the key is the same as the last element.
*/
@Test
void testSentinelLinearSearchKeyEqualsLastElement() {
SentinelLinearSearch sentinelLinearSearch = new SentinelLinearSearch();
Integer[] array = {1, 2, 3, 4, 5, 3}; // Last element is 3, and 3 also appears earlier
Integer key = 3; // Key equals last element
assertEquals(2, sentinelLinearSearch.find(array, key), "Should find the first occurrence at index 2, not the last.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java | src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java | package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class BinarySearch2dArrayTest {
@Test
// valid test case
public void binarySearch2dArrayTestMiddle() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 6;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(1, ans[0]);
assertEquals(1, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestMiddleSide() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 8;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(1, ans[0]);
assertEquals(3, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestUpper() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 2;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(0, ans[0]);
assertEquals(1, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestUpperSide() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 1;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(0, ans[0]);
assertEquals(0, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestLower() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 10;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(2, ans[0]);
assertEquals(1, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestLowerSide() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 11;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(2, ans[0]);
assertEquals(2, ans[1]);
}
@Test
// valid test case
public void binarySearch2dArrayTestNotFound() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 101;
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(-1, ans[0]);
assertEquals(-1, ans[1]);
}
/**
* Test if the method works with input arrays consisting only of one row.
*/
@Test
public void binarySearch2dArrayTestOneRow() {
int[][] arr = {{1, 2, 3, 4}};
int target = 2;
// Assert that the requirement, that the array only has one row, is fulfilled.
assertEquals(arr.length, 1);
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(0, ans[0]);
assertEquals(1, ans[1]);
}
/**
* Test if the method works with the target in the middle of the input.
*/
@Test
public void binarySearch2dArrayTestTargetInMiddle() {
int[][] arr = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}};
int target = 8;
// Assert that the requirement, that the target is in the middle row and middle column, is
// fulfilled.
assertEquals(arr[arr.length / 2][arr[0].length / 2], target);
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(1, ans[0]);
assertEquals(2, ans[1]);
}
/**
* Test if the method works with the target in the middle column,
* in the row above the middle row.
*/
@Test
public void binarySearch2dArrayTestTargetAboveMiddleRowInMiddleColumn() {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 3;
// Assert that the requirement, that he target is in the middle column,
// in an array with an even number of columns, and on the row "above" the middle row.
assertEquals(arr[0].length % 2, 0);
assertEquals(arr[arr.length / 2 - 1][arr[0].length / 2], target);
int[] ans = BinarySearch2dArray.binarySearch(arr, target);
System.out.println(Arrays.toString(ans));
assertEquals(0, ans[0]);
assertEquals(2, ans[1]);
}
/**
* Test if the method works with an empty array.
*/
@Test
public void binarySearch2dArrayTestEmptyArray() {
int[][] arr = {};
int target = 5;
// Assert that an empty array is not valid input for the method.
assertThrows(ArrayIndexOutOfBoundsException.class, () -> BinarySearch2dArray.binarySearch(arr, target));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/FloydTriangleTest.java | src/test/java/com/thealgorithms/others/FloydTriangleTest.java | package com.thealgorithms.others;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class FloydTriangleTest {
@Test
public void testGenerateFloydTriangleWithValidInput() {
List<List<Integer>> expectedOutput = Arrays.asList(singletonList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6));
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(3));
}
@Test
public void testGenerateFloydTriangleWithOneRow() {
List<List<Integer>> expectedOutput = singletonList(singletonList(1));
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(1));
}
@Test
public void testGenerateFloydTriangleWithZeroRows() {
List<List<Integer>> expectedOutput = emptyList();
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(0));
}
@Test
public void testGenerateFloydTriangleWithNegativeRows() {
List<List<Integer>> expectedOutput = emptyList();
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(-3));
}
@Test
public void testGenerateFloydTriangleWithMultipleRows() {
List<List<Integer>> expectedOutput = Arrays.asList(singletonList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9, 10), Arrays.asList(11, 12, 13, 14, 15));
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(5));
}
@Test
public void testGenerateFloydTriangleWithMoreMultipleRows() {
List<List<Integer>> expectedOutput = Arrays.asList(singletonList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9, 10), Arrays.asList(11, 12, 13, 14, 15), Arrays.asList(16, 17, 18, 19, 20, 21), Arrays.asList(22, 23, 24, 25, 26, 27, 28));
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(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/others/BFPRTTest.java | src/test/java/com/thealgorithms/others/BFPRTTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class BFPRTTest {
@ParameterizedTest
@MethodSource("minKNumsTestData")
void testGetMinKNumsByBFPRT(int[] arr, int k, int[] expected) {
int[] result = BFPRT.getMinKNumsByBFPRT(arr, k);
assertArrayEquals(expected, result);
}
private static Stream<Arguments> minKNumsTestData() {
return Stream.of(Arguments.of(new int[] {11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9}, 5, new int[] {1, 1, 2, 2, 2}), Arguments.of(new int[] {3, 2, 1}, 2, new int[] {1, 2}), Arguments.of(new int[] {7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, new int[] {1, 2, 3}));
}
@ParameterizedTest
@MethodSource("minKthTestData")
void testGetMinKthByBFPRT(int[] arr, int k, int expected) {
int result = BFPRT.getMinKthByBFPRT(arr, k);
assertEquals(expected, result);
}
private static Stream<Arguments> minKthTestData() {
return Stream.of(Arguments.of(new int[] {3, 2, 1}, 2, 2), Arguments.of(new int[] {7, 5, 9, 1, 3, 8, 2, 4, 6}, 3, 3), Arguments.of(new int[] {5, 8, 6, 3, 2, 7, 1, 4}, 4, 4));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java | src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.dynamicprogramming.CountFriendsPairing;
import org.junit.jupiter.api.Test;
public class CountFriendsPairingTest {
@Test
void testForOneElement() {
int[] a = {1, 2, 2};
assertTrue(CountFriendsPairing.countFriendsPairing(3, a));
}
@Test
void testForTwoElements() {
int[] a = {1, 2, 2, 3};
assertTrue(CountFriendsPairing.countFriendsPairing(4, a));
}
@Test
void testForThreeElements() {
int[] a = {1, 2, 2, 3, 3};
assertTrue(CountFriendsPairing.countFriendsPairing(5, a));
}
@Test
void testForFourElements() {
int[] a = {1, 2, 2, 3, 3, 4};
assertTrue(CountFriendsPairing.countFriendsPairing(6, a));
}
@Test
void testForFiveElements() {
int[] a = {1, 2, 2, 3, 3, 4, 4};
assertTrue(CountFriendsPairing.countFriendsPairing(7, a));
}
@Test
void testForSixElements() {
int[] a = {1, 2, 2, 3, 3, 4, 4, 4};
assertTrue(CountFriendsPairing.countFriendsPairing(8, a));
}
@Test
void testForSevenElements() {
int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5};
assertTrue(CountFriendsPairing.countFriendsPairing(9, a));
}
@Test
void testForEightElements() {
int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5, 5};
assertTrue(CountFriendsPairing.countFriendsPairing(10, 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/others/PasswordGenTest.java | src/test/java/com/thealgorithms/others/PasswordGenTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class PasswordGenTest {
@Test
public void failGenerationWithSameMinMaxLengthTest() {
int length = 10;
assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(length, length));
}
@Test
public void generateOneCharacterPassword() {
String tempPassword = PasswordGen.generatePassword(1, 2);
assertTrue(tempPassword.length() == 1);
}
@Test
public void failGenerationWithMinLengthSmallerThanMaxLengthTest() {
int minLength = 10;
int maxLength = 5;
assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(minLength, maxLength));
}
@Test
public void generatePasswordNonEmptyTest() {
String tempPassword = PasswordGen.generatePassword(8, 16);
assertTrue(tempPassword.length() != 0);
}
@Test
public void testGeneratePasswordWithMinGreaterThanMax() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(12, 8));
assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", exception.getMessage());
}
@Test
public void testGeneratePasswordWithNegativeLength() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(-5, 10));
assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", exception.getMessage());
}
@Test
public void testGeneratePasswordWithZeroLength() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(0, 0));
assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", 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/others/BoyerMooreTest.java | src/test/java/com/thealgorithms/others/BoyerMooreTest.java | package com.thealgorithms.others;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class BoyerMooreTest {
@ParameterizedTest
@MethodSource("inputStreamWithExistingMajority")
void checkWhenMajorityExists(int expected, int[] input) {
Assertions.assertEquals(expected, BoyerMoore.findMajorityElement(input).get());
}
private static Stream<Arguments> inputStreamWithExistingMajority() {
return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 2}), Arguments.of(10, new int[] {10, 10, 20}), Arguments.of(10, new int[] {10, 20, 10}), Arguments.of(10, new int[] {20, 10, 10}), Arguments.of(4, new int[] {1, 4, 2, 4, 4, 5, 4}), Arguments.of(-1, new int[] {-1}));
}
@ParameterizedTest
@MethodSource("inputStreamWithoutMajority")
void checkWhenMajorityExists(int[] input) {
Assertions.assertFalse(BoyerMoore.findMajorityElement(input).isPresent());
}
private static Stream<Arguments> inputStreamWithoutMajority() {
return Stream.of(Arguments.of(new int[] {10, 10, 20, 20, 30, 30}), Arguments.of(new int[] {10, 20, 30, 40, 50}), Arguments.of(new int[] {1, 2}), Arguments.of(new int[] {}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/NextFitTest.java | src/test/java/com/thealgorithms/others/NextFitTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* author Alexandros Lemonaris
*/
class NextFitCPUTest {
int[] sizeOfBlocks;
int[] sizeOfProcesses;
ArrayList<Integer> memAllocation = new ArrayList<>();
ArrayList<Integer> testMemAllocation;
MemoryManagementAlgorithms nextFit = new NextFit();
@Test
void testFitForUseOfOneBlock() {
// test1 - third process does not fit because of algorithms procedure
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 5, 15, 2};
memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, -255, 2));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForEqualProcecesses() {
// test2
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 10, 10, 10};
memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForNoEmptyBlockCell() {
// test3 for more processes than blocks - no empty space left to none of the blocks
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 12, 10, 7};
memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForSameInputDifferentQuery() {
// test4 for more processes than blocks - one element does not fit due to input series
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 7, 10, 12};
memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForMoreBlocksNoFit() {
// test5 for more blocks than processes
sizeOfBlocks = new int[] {5, 4, -1, 3, 6};
sizeOfProcesses = new int[] {10, 11};
memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255));
assertEquals(testMemAllocation, memAllocation);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java | src/test/java/com/thealgorithms/others/WorstFitCPUTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* author Alexandros Lemonaris
*/
class WorstFitCPUTest {
int[] sizeOfBlocks;
int[] sizeOfProcesses;
ArrayList<Integer> memAllocation = new ArrayList<>();
ArrayList<Integer> testMemAllocation;
MemoryManagementAlgorithms worstFit = new WorstFitCPU();
@Test
void testFitForUseOfOneBlock() {
// test1
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 5, 15, 2};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, -255, 3));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForEqualProcecesses() {
// test2
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 10, 10, 10};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 3, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForNoEmptyBlockCell() {
// test3 - could suits best, bad use of memory allocation due to worstFit algorithm
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 12, 10, 7};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForSameInputDifferentQuery() {
// test4 same example different series - same results
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 7, 10, 12};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForMoreBlocksNoFit() {
// test5 for more blocks than processes
sizeOfBlocks = new int[] {5, 4, -1, 3, 6};
sizeOfProcesses = new int[] {10, 11};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitBadCase() {
// test6 for only two process fit
sizeOfBlocks = new int[] {7, 17, 7, 5, 6};
sizeOfProcesses = new int[] {8, 10, 10, 8, 8, 8};
memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255));
assertEquals(testMemAllocation, memAllocation);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/InsertDeleteInArrayTest.java | src/test/java/com/thealgorithms/others/InsertDeleteInArrayTest.java | package com.thealgorithms.others;
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;
/**
* Test cases for {@link InsertDeleteInArray} class.
* <p>
* Tests cover:
* <ul>
* <li>Insert operations at various positions</li>
* <li>Delete operations at various positions</li>
* <li>Edge cases (empty arrays, single element, boundary positions)</li>
* <li>Error conditions (null arrays, invalid positions)</li>
* </ul>
* </p>
*/
class InsertDeleteInArrayTest {
// ========== Insert Element Tests ==========
@Test
void testInsertAtBeginning() {
int[] array = {2, 3, 4, 5};
int[] result = InsertDeleteInArray.insertElement(array, 1, 0);
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, result);
}
@Test
void testInsertAtEnd() {
int[] array = {1, 2, 3, 4};
int[] result = InsertDeleteInArray.insertElement(array, 5, 4);
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, result);
}
@Test
void testInsertInMiddle() {
int[] array = {1, 2, 4, 5};
int[] result = InsertDeleteInArray.insertElement(array, 3, 2);
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, result);
}
@Test
void testInsertIntoEmptyArray() {
int[] array = {};
int[] result = InsertDeleteInArray.insertElement(array, 42, 0);
assertArrayEquals(new int[] {42}, result);
}
@Test
void testInsertIntoSingleElementArray() {
int[] array = {5};
int[] result = InsertDeleteInArray.insertElement(array, 3, 0);
assertArrayEquals(new int[] {3, 5}, result);
}
@Test
void testInsertNegativeNumber() {
int[] array = {1, 2, 3};
int[] result = InsertDeleteInArray.insertElement(array, -10, 1);
assertArrayEquals(new int[] {1, -10, 2, 3}, result);
}
@Test
void testInsertZero() {
int[] array = {1, 2, 3};
int[] result = InsertDeleteInArray.insertElement(array, 0, 1);
assertArrayEquals(new int[] {1, 0, 2, 3}, result);
}
@Test
void testInsertWithNullArray() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.insertElement(null, 5, 0));
assertEquals("Array cannot be null", exception.getMessage());
}
@Test
void testInsertWithNegativePosition() {
int[] array = {1, 2, 3};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.insertElement(array, 5, -1));
assertEquals("Position must be between 0 and 3", exception.getMessage());
}
@Test
void testInsertWithPositionTooLarge() {
int[] array = {1, 2, 3};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.insertElement(array, 5, 4));
assertEquals("Position must be between 0 and 3", exception.getMessage());
}
// ========== Delete Element Tests ==========
@Test
void testDeleteFromBeginning() {
int[] array = {1, 2, 3, 4, 5};
int[] result = InsertDeleteInArray.deleteElement(array, 0);
assertArrayEquals(new int[] {2, 3, 4, 5}, result);
}
@Test
void testDeleteFromEnd() {
int[] array = {1, 2, 3, 4, 5};
int[] result = InsertDeleteInArray.deleteElement(array, 4);
assertArrayEquals(new int[] {1, 2, 3, 4}, result);
}
@Test
void testDeleteFromMiddle() {
int[] array = {1, 2, 3, 4, 5};
int[] result = InsertDeleteInArray.deleteElement(array, 2);
assertArrayEquals(new int[] {1, 2, 4, 5}, result);
}
@Test
void testDeleteFromSingleElementArray() {
int[] array = {42};
int[] result = InsertDeleteInArray.deleteElement(array, 0);
assertArrayEquals(new int[] {}, result);
}
@Test
void testDeleteFromTwoElementArray() {
int[] array = {10, 20};
int[] result = InsertDeleteInArray.deleteElement(array, 1);
assertArrayEquals(new int[] {10}, result);
}
@Test
void testDeleteWithNullArray() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.deleteElement(null, 0));
assertEquals("Array cannot be null", exception.getMessage());
}
@Test
void testDeleteFromEmptyArray() {
int[] array = {};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.deleteElement(array, 0));
assertEquals("Array is empty", exception.getMessage());
}
@Test
void testDeleteWithNegativePosition() {
int[] array = {1, 2, 3};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.deleteElement(array, -1));
assertEquals("Position must be between 0 and 2", exception.getMessage());
}
@Test
void testDeleteWithPositionTooLarge() {
int[] array = {1, 2, 3};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.deleteElement(array, 3));
assertEquals("Position must be between 0 and 2", exception.getMessage());
}
@Test
void testDeleteWithPositionEqualToLength() {
int[] array = {1, 2, 3, 4, 5};
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> InsertDeleteInArray.deleteElement(array, 5));
assertEquals("Position must be between 0 and 4", exception.getMessage());
}
// ========== Combined Operations Tests ==========
@Test
void testInsertThenDelete() {
int[] array = {1, 2, 3};
int[] afterInsert = InsertDeleteInArray.insertElement(array, 99, 1);
assertArrayEquals(new int[] {1, 99, 2, 3}, afterInsert);
int[] afterDelete = InsertDeleteInArray.deleteElement(afterInsert, 1);
assertArrayEquals(new int[] {1, 2, 3}, afterDelete);
}
@Test
void testMultipleInsertions() {
int[] array = {1, 3, 5};
array = InsertDeleteInArray.insertElement(array, 2, 1);
assertArrayEquals(new int[] {1, 2, 3, 5}, array);
array = InsertDeleteInArray.insertElement(array, 4, 3);
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, array);
}
@Test
void testMultipleDeletions() {
int[] array = {1, 2, 3, 4, 5};
array = InsertDeleteInArray.deleteElement(array, 2);
assertArrayEquals(new int[] {1, 2, 4, 5}, array);
array = InsertDeleteInArray.deleteElement(array, 0);
assertArrayEquals(new int[] {2, 4, 5}, array);
}
@Test
void testLargeArray() {
int[] array = new int[100];
for (int i = 0; i < 100; i++) {
array[i] = i;
}
int[] result = InsertDeleteInArray.insertElement(array, 999, 50);
assertEquals(101, result.length);
assertEquals(999, result[50]);
assertEquals(49, result[49]);
assertEquals(50, result[51]);
}
@Test
void testArrayWithDuplicates() {
int[] array = {1, 2, 2, 3, 2};
int[] result = InsertDeleteInArray.deleteElement(array, 1);
assertArrayEquals(new int[] {1, 2, 3, 2}, result);
}
@Test
void testNegativeNumbers() {
int[] array = {-5, -3, -1, 0, 1};
int[] result = InsertDeleteInArray.insertElement(array, -2, 2);
assertArrayEquals(new int[] {-5, -3, -2, -1, 0, 1}, 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/others/MiniMaxAlgorithmTest.java | src/test/java/com/thealgorithms/others/MiniMaxAlgorithmTest.java | package com.thealgorithms.others;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test class for MiniMaxAlgorithm
* Tests the minimax algorithm implementation for game tree evaluation
*/
class MiniMaxAlgorithmTest {
private MiniMaxAlgorithm miniMax;
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@BeforeEach
void setUp() {
miniMax = new MiniMaxAlgorithm();
System.setOut(new PrintStream(outputStream));
}
@AfterEach
void tearDown() {
System.setOut(originalOut);
}
@Test
void testConstructorCreatesValidScores() {
// The default constructor should create scores array of length 8 (2^3)
Assertions.assertEquals(8, miniMax.getScores().length);
Assertions.assertEquals(3, miniMax.getHeight());
// All scores should be positive (between 1 and 99)
for (int score : miniMax.getScores()) {
Assertions.assertTrue(score >= 1 && score <= 99);
}
}
@Test
void testConstructorWithValidScores() {
int[] validScores = {10, 20, 30, 40};
MiniMaxAlgorithm customMiniMax = new MiniMaxAlgorithm(validScores);
Assertions.assertArrayEquals(validScores, customMiniMax.getScores());
Assertions.assertEquals(2, customMiniMax.getHeight()); // log2(4) = 2
}
@Test
void testConstructorWithInvalidScoresThrowsException() {
int[] invalidScores = {10, 20, 30}; // Length 3 is not a power of 2
Assertions.assertThrows(IllegalArgumentException.class, () -> new MiniMaxAlgorithm(invalidScores));
}
@Test
void testConstructorDoesNotModifyOriginalArray() {
int[] originalScores = {10, 20, 30, 40};
int[] copyOfOriginal = {10, 20, 30, 40};
MiniMaxAlgorithm customMiniMax = new MiniMaxAlgorithm(originalScores);
// Modify the original array
originalScores[0] = 999;
// Constructor should have made a copy, so internal state should be unchanged
Assertions.assertArrayEquals(copyOfOriginal, customMiniMax.getScores());
}
@Test
void testSetScoresWithValidPowerOfTwo() {
int[] validScores = {10, 20, 30, 40};
miniMax.setScores(validScores);
Assertions.assertArrayEquals(validScores, miniMax.getScores());
Assertions.assertEquals(2, miniMax.getHeight()); // log2(4) = 2
}
@Test
void testSetScoresWithInvalidLength() {
int[] invalidScores = {10, 20, 30}; // Length 3 is not a power of 2
Assertions.assertThrows(IllegalArgumentException.class, () -> miniMax.setScores(invalidScores));
// Scores should remain unchanged (original length 8)
Assertions.assertEquals(8, miniMax.getScores().length);
}
@Test
void testSetScoresWithZeroLength() {
int[] emptyScores = {}; // Length 0 is not a power of 2
Assertions.assertThrows(IllegalArgumentException.class, () -> miniMax.setScores(emptyScores));
// Scores should remain unchanged (original length 8)
Assertions.assertEquals(8, miniMax.getScores().length);
}
@Test
void testSetScoresWithVariousInvalidLengths() {
// Test multiple invalid lengths to ensure isPowerOfTwo function is fully
// covered
int[][] invalidScoreArrays = {
{1, 2, 3, 4, 5}, // Length 5
{1, 2, 3, 4, 5, 6}, // Length 6
{1, 2, 3, 4, 5, 6, 7}, // Length 7
new int[9], // Length 9
new int[10], // Length 10
new int[15] // Length 15
};
for (int[] invalidScores : invalidScoreArrays) {
Assertions.assertThrows(IllegalArgumentException.class, () -> miniMax.setScores(invalidScores), "Failed for array length: " + invalidScores.length);
}
// Scores should remain unchanged (original length 8)
Assertions.assertEquals(8, miniMax.getScores().length);
}
@Test
void testSetScoresWithSingleElement() {
int[] singleScore = {42};
miniMax.setScores(singleScore);
Assertions.assertArrayEquals(singleScore, miniMax.getScores());
Assertions.assertEquals(0, miniMax.getHeight()); // log2(1) = 0
}
@Test
void testMiniMaxWithKnownScores() {
// Test with a known game tree: [3, 12, 8, 2]
int[] testScores = {3, 12, 8, 2};
miniMax.setScores(testScores);
// Maximizer starts: should choose max(min(3,12), min(8,2)) = max(3, 2) = 3
int result = miniMax.miniMax(0, true, 0, false);
Assertions.assertEquals(3, result);
}
@Test
void testMiniMaxWithMinimizerFirst() {
// Test with minimizer starting first
int[] testScores = {3, 12, 8, 2};
miniMax.setScores(testScores);
// Minimizer starts: should choose min(max(3,12), max(8,2)) = min(12, 8) = 8
int result = miniMax.miniMax(0, false, 0, false);
Assertions.assertEquals(8, result);
}
@Test
void testMiniMaxWithLargerTree() {
// Test with 8 elements: [5, 6, 7, 4, 5, 3, 6, 2]
int[] testScores = {5, 6, 7, 4, 5, 3, 6, 2};
miniMax.setScores(testScores);
// Maximizer starts
int result = miniMax.miniMax(0, true, 0, false);
// Expected: max(min(max(5,6), max(7,4)), min(max(5,3), max(6,2)))
// = max(min(6, 7), min(5, 6)) = max(6, 5) = 6
Assertions.assertEquals(6, result);
}
@Test
void testMiniMaxVerboseOutput() {
int[] testScores = {3, 12, 8, 2};
miniMax.setScores(testScores);
miniMax.miniMax(0, true, 0, true);
String output = outputStream.toString();
Assertions.assertTrue(output.contains("Maximizer"));
Assertions.assertTrue(output.contains("Minimizer"));
Assertions.assertTrue(output.contains("chooses"));
}
@Test
void testGetRandomScoresLength() {
int[] randomScores = MiniMaxAlgorithm.getRandomScores(4, 50);
Assertions.assertEquals(16, randomScores.length); // 2^4 = 16
// All scores should be between 1 and 50
for (int score : randomScores) {
Assertions.assertTrue(score >= 1 && score <= 50);
}
}
@Test
void testGetRandomScoresWithDifferentParameters() {
int[] randomScores = MiniMaxAlgorithm.getRandomScores(2, 10);
Assertions.assertEquals(4, randomScores.length); // 2^2 = 4
// All scores should be between 1 and 10
for (int score : randomScores) {
Assertions.assertTrue(score >= 1 && score <= 10);
}
}
@Test
void testMainMethod() {
// Test that main method runs without errors
Assertions.assertDoesNotThrow(() -> MiniMaxAlgorithm.main(new String[] {}));
String output = outputStream.toString();
Assertions.assertTrue(output.contains("The best score for"));
Assertions.assertTrue(output.contains("Maximizer"));
}
@Test
void testHeightCalculation() {
// Test height calculation for different array sizes
int[] scores2 = {1, 2};
miniMax.setScores(scores2);
Assertions.assertEquals(1, miniMax.getHeight()); // log2(2) = 1
int[] scores16 = new int[16];
miniMax.setScores(scores16);
Assertions.assertEquals(4, miniMax.getHeight()); // log2(16) = 4
}
@Test
void testEdgeCaseWithZeroScores() {
int[] zeroScores = {0, 0, 0, 0};
miniMax.setScores(zeroScores);
int result = miniMax.miniMax(0, true, 0, false);
Assertions.assertEquals(0, result);
}
@Test
void testEdgeCaseWithNegativeScores() {
int[] negativeScores = {-5, -2, -8, -1};
miniMax.setScores(negativeScores);
// Tree evaluation with maximizer first:
// Level 1 (minimizer): min(-5,-2) = -5, min(-8,-1) = -8
// Level 0 (maximizer): max(-5, -8) = -5
int result = miniMax.miniMax(0, true, 0, false);
Assertions.assertEquals(-5, result);
}
@Test
void testSetScoresWithNegativeLength() {
// This test ensures the first condition of isPowerOfTwo (n > 0) is tested
// Although we can't directly create an array with negative length,
// we can test edge cases around zero and ensure proper validation
// Test with array length 0 (edge case for n > 0 condition)
int[] emptyArray = new int[0];
Assertions.assertThrows(IllegalArgumentException.class, () -> miniMax.setScores(emptyArray));
Assertions.assertEquals(8, miniMax.getScores().length); // Should remain unchanged
}
@Test
void testSetScoresWithLargePowerOfTwo() {
// Test with a large power of 2 to ensure the algorithm works correctly
int[] largeValidScores = new int[32]; // 32 = 2^5
for (int i = 0; i < largeValidScores.length; i++) {
largeValidScores[i] = i + 1;
}
miniMax.setScores(largeValidScores);
Assertions.assertArrayEquals(largeValidScores, miniMax.getScores());
Assertions.assertEquals(5, miniMax.getHeight()); // log2(32) = 5
}
@Test
void testSetScoresValidEdgeCases() {
// Test valid powers of 2 to ensure isPowerOfTwo returns true correctly
int[][] validPowersOf2 = {
new int[1], // 1 = 2^0
new int[2], // 2 = 2^1
new int[4], // 4 = 2^2
new int[8], // 8 = 2^3
new int[16], // 16 = 2^4
new int[64] // 64 = 2^6
};
int[] expectedHeights = {0, 1, 2, 3, 4, 6};
for (int i = 0; i < validPowersOf2.length; i++) {
miniMax.setScores(validPowersOf2[i]);
Assertions.assertEquals(validPowersOf2[i].length, miniMax.getScores().length, "Failed for array length: " + validPowersOf2[i].length);
Assertions.assertEquals(expectedHeights[i], miniMax.getHeight(), "Height calculation failed for array length: " + validPowersOf2[i].length);
}
}
@Test
void testGetScoresReturnsDefensiveCopy() {
int[] originalScores = {10, 20, 30, 40};
miniMax.setScores(originalScores);
// Get the scores and modify them
int[] retrievedScores = miniMax.getScores();
retrievedScores[0] = 999;
// Internal state should remain unchanged
Assertions.assertEquals(10, miniMax.getScores()[0]);
}
@Test
void testSetScoresCreatesDefensiveCopy() {
int[] originalScores = {10, 20, 30, 40};
miniMax.setScores(originalScores);
// Modify the original array after setting
originalScores[0] = 999;
// Internal state should remain unchanged
Assertions.assertEquals(10, miniMax.getScores()[0]);
}
@Test
void testMiniMaxWithAllSameScores() {
int[] sameScores = {5, 5, 5, 5};
miniMax.setScores(sameScores);
// When all scores are the same, result should be that score
int result = miniMax.miniMax(0, true, 0, false);
Assertions.assertEquals(5, result);
}
@Test
void testMiniMaxAtDifferentDepths() {
int[] testScores = {3, 12, 8, 2, 14, 5, 2, 9};
miniMax.setScores(testScores);
// Test maximizer first
int result = miniMax.miniMax(0, true, 0, false);
// Expected: max(min(max(3,12), max(8,2)), min(max(14,5), max(2,9)))
// = max(min(12, 8), min(14, 9)) = max(8, 9) = 9
Assertions.assertEquals(9, result);
}
@Test
void testMiniMaxWithMinIntAndMaxInt() {
int[] extremeScores = {Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 1};
miniMax.setScores(extremeScores);
int result = miniMax.miniMax(0, true, 0, false);
// Expected: max(min(MIN, MAX), min(0, 1)) = max(MIN, 0) = 0
Assertions.assertEquals(0, 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/others/LineSweepTest.java | src/test/java/com/thealgorithms/others/LineSweepTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class LineSweepTest {
private record OverlapTestCase(int[][] ranges, boolean expected) {
}
private record MaximumEndPointTestCase(int[][] ranges, int expected) {
}
@ParameterizedTest
@MethodSource("provideOverlapTestData")
void testIsOverlap(OverlapTestCase testCase) {
assertEquals(testCase.expected(), LineSweep.isOverlap(testCase.ranges()));
}
private static Stream<Arguments> provideOverlapTestData() {
return Stream.of(Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {7, 20}, {15, 24}}, true)), Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {11, 20}, {21, 24}}, false)), Arguments.of(new OverlapTestCase(new int[][] {{0, 10}, {10, 20}, {21, 24}}, true)),
Arguments.of(new OverlapTestCase(new int[][] {{5, 10}}, false)), Arguments.of(new OverlapTestCase(new int[][] {{1, 5}, {1, 5}, {1, 5}}, true)), Arguments.of(new OverlapTestCase(new int[][] {{1, 1}, {2, 2}, {3, 3}}, false)), Arguments.of(new OverlapTestCase(new int[][] {}, false)));
}
@ParameterizedTest
@MethodSource("provideMaximumEndPointTestData")
void testFindMaximumEndPoint(MaximumEndPointTestCase testCase) {
assertEquals(testCase.expected(), LineSweep.findMaximumEndPoint(testCase.ranges()));
}
private static Stream<Arguments> provideMaximumEndPointTestData() {
return Stream.of(Arguments.of(new MaximumEndPointTestCase(new int[][] {{10, 20}, {1, 100}, {14, 16}, {1, 8}}, 100)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java | src/test/java/com/thealgorithms/others/FirstFitCPUTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* author Alexandros Lemonaris
*/
class FirstFitCPUTest {
int[] sizeOfBlocks;
int[] sizeOfProcesses;
ArrayList<Integer> memAllocation = new ArrayList<>();
ArrayList<Integer> testMemAllocation;
MemoryManagementAlgorithms firstFit = new FirstFitCPU();
@Test
void testFitForUseOfOneBlock() {
// test1 - no use of one block for two processes
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 5, 15, 2};
memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(1, 0, 2, 1));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForEqualProcecesses() {
// test2
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 10, 10, 10};
memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForNoEmptyBlockCell() {
// test3 for more processes than blocks - no empty space left to none of the blocks
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 12, 10, 7};
memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForSameInputDifferentQuery() {
// test4 for more processes than blocks - one element does not fit due to input series
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 7, 10, 12};
memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForMoreBlocksNoFit() {
// test5 for more blocks than processes
sizeOfBlocks = new int[] {5, 4, -1, 3, 6};
sizeOfProcesses = new int[] {10, 11};
memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255));
assertEquals(testMemAllocation, memAllocation);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/CRC16Test.java | src/test/java/com/thealgorithms/others/CRC16Test.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CRC16Test {
@Test
void testCRC16() {
// given
String textToCRC16 = "hacktoberfest!";
// when
String resultCRC16 = CRC16.crc16(textToCRC16); // Algorithm CRC16-CCITT-FALSE
// then
assertEquals("10FC", resultCRC16);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java | src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class ArrayLeftRotationTest {
@Test
void testForOneElement() {
int[] arr = {3};
int[] result = ArrayLeftRotation.rotateLeft(arr, 3);
assertArrayEquals(arr, result);
}
@Test
void testForZeroStep() {
int[] arr = {3, 1, 5, 8, 6};
int[] result = ArrayLeftRotation.rotateLeft(arr, 0);
assertArrayEquals(arr, result);
}
@Test
void testForEqualSizeStep() {
int[] arr = {3, 1, 5, 8, 6};
int[] result = ArrayLeftRotation.rotateLeft(arr, 5);
assertArrayEquals(arr, result);
}
@Test
void testForLowerSizeStep() {
int[] arr = {3, 1, 5, 8, 6};
int n = 2;
int[] expected = {5, 8, 6, 3, 1};
int[] result = ArrayLeftRotation.rotateLeft(arr, n);
assertArrayEquals(expected, result);
}
@Test
void testForHigherSizeStep() {
int[] arr = {3, 1, 5, 8, 6};
int n = 7;
int[] expected = {5, 8, 6, 3, 1};
int[] result = ArrayLeftRotation.rotateLeft(arr, n);
assertArrayEquals(expected, result);
}
@Test
void testForEmptyArray() {
int[] arr = {};
int[] result = ArrayLeftRotation.rotateLeft(arr, 3);
assertArrayEquals(arr, 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/others/PerlinNoiseTest.java | src/test/java/com/thealgorithms/others/PerlinNoiseTest.java | package com.thealgorithms.others;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class PerlinNoiseTest {
@Test
@DisplayName("generatePerlinNoise returns array with correct dimensions")
void testDimensions() {
int w = 8;
int h = 6;
float[][] noise = PerlinNoise.generatePerlinNoise(w, h, 4, 0.6f, 123L);
assertThat(noise).hasDimensions(w, h);
}
@Test
@DisplayName("All values are within [0,1] after normalization")
void testRange() {
int w = 16;
int h = 16;
float[][] noise = PerlinNoise.generatePerlinNoise(w, h, 5, 0.7f, 42L);
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
assertThat(noise[x][y]).isBetween(0f, 1f);
}
}
}
@Test
@DisplayName("Deterministic for same parameters and seed")
void testDeterminism() {
int w = 10;
int h = 10;
long seed = 98765L;
float[][] a = PerlinNoise.generatePerlinNoise(w, h, 3, 0.5f, seed);
float[][] b = PerlinNoise.generatePerlinNoise(w, h, 3, 0.5f, seed);
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
assertThat(a[x][y]).isEqualTo(b[x][y]);
}
}
}
@Test
@DisplayName("Different seeds produce different outputs (probabilistically)")
void testDifferentSeeds() {
int w = 12;
int h = 12;
float[][] a = PerlinNoise.generatePerlinNoise(w, h, 4, 0.8f, 1L);
float[][] b = PerlinNoise.generatePerlinNoise(w, h, 4, 0.8f, 2L);
// Count exact equalities; expect very few or none.
int equalCount = 0;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
if (Float.compare(a[x][y], b[x][y]) == 0) {
equalCount++;
}
}
}
assertThat(equalCount).isLessThan(w * h / 10); // less than 10% equal exact values
}
@Test
@DisplayName("Interpolation endpoints are respected")
void testInterpolateEndpoints() {
assertThat(PerlinNoise.interpolate(0f, 1f, 0f)).isEqualTo(0f);
assertThat(PerlinNoise.interpolate(0f, 1f, 1f)).isEqualTo(1f);
assertThat(PerlinNoise.interpolate(0.2f, 0.8f, 0.5f)).isEqualTo(0.5f);
}
@Test
@DisplayName("Single octave reduces to bilinear interpolation of base grid")
void testSingleOctaveLayer() {
int w = 8;
int h = 8;
long seed = 7L;
float[][] base = PerlinNoise.createBaseGrid(w, h, seed);
float[][] layer = PerlinNoise.generatePerlinNoiseLayer(base, w, h, 0); // period=1
// With period = 1, x0=x, x1=(x+1)%w etc. Values should be smooth and within
// [0,1]
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
assertThat(layer[x][y]).isBetween(0f, 1f);
}
}
}
@Test
@DisplayName("Invalid inputs are rejected")
void testInvalidInputs() {
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(0, 5, 1, 0.5f, 1L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(5, -1, 1, 0.5f, 1L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(5, 5, 0, 0.5f, 1L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(5, 5, 1, 0f, 1L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(5, 5, 1, Float.NaN, 1L)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> PerlinNoise.generatePerlinNoise(5, 5, 1, 1.1f, 1L)).isInstanceOf(IllegalArgumentException.class);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/ConwayTest.java | src/test/java/com/thealgorithms/others/ConwayTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ConwayTest {
@Test
public void testGenerateWith1() {
assertEquals("31131211131221", Conway.generateList("1", 8).get(7));
}
@Test
public void testGenerateWith123456() {
assertEquals(
"13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116",
Conway.generateList("123456", 20).get(11));
}
@Test
public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C() {
assertEquals(
"311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C",
Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19));
}
@Test
public void testGenerateNextElementWith1() {
assertEquals("11", Conway.generateNextElement("1"));
}
@Test
public void testGenerateNextElementWith123456() {
assertEquals("111213141516", Conway.generateNextElement("123456"));
}
@Test
public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C() {
assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/HuffmanTest.java | src/test/java/com/thealgorithms/others/HuffmanTest.java | package com.thealgorithms.others;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test class for Huffman coding algorithm.
* Tests various scenarios including normal cases, edge cases, and error
* conditions.
*/
class HuffmanTest {
@Test
void testBuildHuffmanTreeWithBasicInput() {
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
int[] charFreq = {5, 9, 12, 13, 16, 45};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Assertions.assertNotNull(root);
Assertions.assertEquals(100, root.data); // Total frequency
}
@Test
void testGenerateCodesWithBasicInput() {
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
int[] charFreq = {5, 9, 12, 13, 16, 45};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(6, codes.size());
// Verify that all characters have codes
for (char c : charArray) {
Assertions.assertTrue(codes.containsKey(c), "Missing code for character: " + c);
Assertions.assertNotNull(codes.get(c), "Null code for character: " + c);
}
// Verify that higher frequency characters have shorter codes
// 'f' has the highest frequency (45), so it should have one of the shortest
// codes
Assertions.assertTrue(codes.get('f').length() <= codes.get('a').length());
}
@Test
void testSingleCharacter() {
char[] charArray = {'a'};
int[] charFreq = {10};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(1, codes.size());
Assertions.assertEquals("0", codes.get('a')); // Single character gets code "0"
}
@Test
void testTwoCharacters() {
char[] charArray = {'a', 'b'};
int[] charFreq = {3, 7};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(2, codes.size());
// Verify both characters have codes
Assertions.assertTrue(codes.containsKey('a'));
Assertions.assertTrue(codes.containsKey('b'));
// Verify codes are different
Assertions.assertNotEquals(codes.get('a'), codes.get('b'));
}
@Test
void testEqualFrequencies() {
char[] charArray = {'a', 'b', 'c'};
int[] charFreq = {5, 5, 5};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(3, codes.size());
// Verify all characters have codes
for (char c : charArray) {
Assertions.assertTrue(codes.containsKey(c));
}
}
@Test
void testLargeFrequencyDifference() {
char[] charArray = {'a', 'b', 'c'};
int[] charFreq = {1, 10, 100};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(3, codes.size());
// Character 'c' with highest frequency should have shortest code
Assertions.assertTrue(codes.get('c').length() <= codes.get('b').length());
Assertions.assertTrue(codes.get('c').length() <= codes.get('a').length());
}
@Test
void testNullCharacterArray() {
int[] charFreq = {5, 9, 12};
Assertions.assertThrows(IllegalArgumentException.class, () -> { Huffman.buildHuffmanTree(null, charFreq); });
}
@Test
void testNullFrequencyArray() {
char[] charArray = {'a', 'b', 'c'};
Assertions.assertThrows(IllegalArgumentException.class, () -> { Huffman.buildHuffmanTree(charArray, null); });
}
@Test
void testEmptyArrays() {
char[] charArray = {};
int[] charFreq = {};
Assertions.assertThrows(IllegalArgumentException.class, () -> { Huffman.buildHuffmanTree(charArray, charFreq); });
}
@Test
void testMismatchedArrayLengths() {
char[] charArray = {'a', 'b', 'c'};
int[] charFreq = {5, 9};
Assertions.assertThrows(IllegalArgumentException.class, () -> { Huffman.buildHuffmanTree(charArray, charFreq); });
}
@Test
void testNegativeFrequency() {
char[] charArray = {'a', 'b', 'c'};
int[] charFreq = {5, -9, 12};
Assertions.assertThrows(IllegalArgumentException.class, () -> { Huffman.buildHuffmanTree(charArray, charFreq); });
}
@Test
void testZeroFrequency() {
char[] charArray = {'a', 'b', 'c'};
int[] charFreq = {0, 5, 10};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(3, codes.size());
Assertions.assertTrue(codes.containsKey('a')); // Even with 0 frequency, character should have a code
}
@Test
void testGenerateCodesWithNullRoot() {
Map<Character, String> codes = Huffman.generateCodes(null);
Assertions.assertNotNull(codes);
Assertions.assertTrue(codes.isEmpty());
}
@Test
void testPrefixProperty() {
// Verify that no code is a prefix of another (Huffman property)
char[] charArray = {'a', 'b', 'c', 'd', 'e'};
int[] charFreq = {5, 9, 12, 13, 16};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
// Check that no code is a prefix of another
for (Map.Entry<Character, String> entry1 : codes.entrySet()) {
for (Map.Entry<Character, String> entry2 : codes.entrySet()) {
if (!entry1.getKey().equals(entry2.getKey())) {
String code1 = entry1.getValue();
String code2 = entry2.getValue();
Assertions.assertTrue(!code1.startsWith(code2) && !code2.startsWith(code1), "Code " + code1 + " is a prefix of " + code2);
}
}
}
}
@Test
void testBinaryCodesOnly() {
// Verify that all codes contain only '0' and '1'
char[] charArray = {'a', 'b', 'c', 'd'};
int[] charFreq = {1, 2, 3, 4};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
for (String code : codes.values()) {
Assertions.assertTrue(code.matches("[01]+"), "Code contains non-binary characters: " + code);
}
}
@Test
void testMultipleCharactersWithLargeAlphabet() {
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
int[] charFreq = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
HuffmanNode root = Huffman.buildHuffmanTree(charArray, charFreq);
Map<Character, String> codes = Huffman.generateCodes(root);
Assertions.assertNotNull(codes);
Assertions.assertEquals(10, codes.size());
// Verify all characters have codes
for (char c : charArray) {
Assertions.assertTrue(codes.containsKey(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/others/BestFitCPUTest.java | src/test/java/com/thealgorithms/others/BestFitCPUTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* author Alexandros Lemonaris
*/
class BestFitCPUTest {
int[] sizeOfBlocks;
int[] sizeOfProcesses;
ArrayList<Integer> memAllocation = new ArrayList<>();
ArrayList<Integer> testMemAllocation;
MemoryManagementAlgorithms bestFit = new BestFitCPU();
@Test
void testFitForUseOfOneBlock() {
// test1 - 2 processes shall fit to one block instead of using a different block each
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 5, 15, 2};
memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(3, 0, 2, 2));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForEqualProcecesses() {
// test2
sizeOfBlocks = new int[] {5, 12, 17, 10};
sizeOfProcesses = new int[] {10, 10, 10, 10};
memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(3, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForNoEmptyBlockCell() {
// test3 for more processes than blocks - no empty space left to none of the blocks
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 12, 10, 7};
memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForSameInputDifferentQuery() {
// test4 for more processes than blocks - one element does not fit due to input series
sizeOfBlocks = new int[] {5, 12, 17};
sizeOfProcesses = new int[] {5, 7, 10, 12};
memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255));
assertEquals(testMemAllocation, memAllocation);
}
@Test
void testFitForMoreBlocksNoFit() {
// test5 for more blocks than processes
sizeOfBlocks = new int[] {5, 4, -1, 3, 6};
sizeOfProcesses = new int[] {10, 11};
memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses);
testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255));
assertEquals(testMemAllocation, memAllocation);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java | src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.dynamicprogramming.KadaneAlgorithm;
import org.junit.jupiter.api.Test;
public class KadaneAlogrithmTest {
@Test
void testForOneElement() {
int[] a = {-1};
assertTrue(KadaneAlgorithm.maxSum(a, -1));
}
@Test
void testForTwoElements() {
int[] a = {-2, 1};
assertTrue(KadaneAlgorithm.maxSum(a, 1));
}
@Test
void testForThreeElements() {
int[] a = {5, 3, 12};
assertTrue(KadaneAlgorithm.maxSum(a, 20));
}
@Test
void testForFourElements() {
int[] a = {-1, -3, -7, -4};
assertTrue(KadaneAlgorithm.maxSum(a, -1));
}
@Test
void testForFiveElements() {
int[] a = {4, 5, 3, 0, 2};
assertTrue(KadaneAlgorithm.maxSum(a, 14));
}
@Test
void testForSixElements() {
int[] a = {-43, -45, 47, 12, 87, -13};
assertTrue(KadaneAlgorithm.maxSum(a, 146));
}
@Test
void testForSevenElements() {
int[] a = {9, 8, 2, 23, 13, 6, 7};
assertTrue(KadaneAlgorithm.maxSum(a, 68));
}
@Test
void testForEightElements() {
int[] a = {9, -5, -5, -2, 4, 5, 0, 1};
assertTrue(KadaneAlgorithm.maxSum(a, 10));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/LinkListSortTest.java | src/test/java/com/thealgorithms/others/LinkListSortTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.sorts.LinkListSort;
import org.junit.jupiter.api.Test;
public class LinkListSortTest {
@Test
void testForOneElement() {
int[] a = {56};
assertTrue(LinkListSort.isSorted(a, 2));
}
@Test
void testForTwoElements() {
int[] a = {6, 4};
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForThreeElements() {
int[] a = {875, 253, 12};
assertTrue(LinkListSort.isSorted(a, 3));
}
@Test
void testForFourElements() {
int[] a = {86, 32, 87, 13};
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForFiveElements() {
int[] a = {6, 5, 3, 0, 9};
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForSixElements() {
int[] a = {9, 65, 432, 32, 47, 327};
assertTrue(LinkListSort.isSorted(a, 3));
}
@Test
void testForSevenElements() {
int[] a = {6, 4, 2, 1, 3, 6, 7};
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForEightElements() {
int[] a = {123, 234, 145, 764, 322, 367, 768, 34};
assertTrue(LinkListSort.isSorted(a, 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/others/CRCAlgorithmTest.java | src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class CRCAlgorithmTest {
@Test
void testNoErrorsWithZeroBER() {
CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 0.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
assertEquals(0, c.getWrongMess(), "BER=0 should produce no wrong messages");
assertEquals(0, c.getWrongMessCaught(), "No errors, so no caught wrong messages");
assertEquals(0, c.getWrongMessNotCaught(), "No errors, so no uncaught wrong messages");
assertTrue(c.getCorrectMess() > 0, "Should have some correct messages");
}
@Test
void testAllErrorsWithBEROne() {
CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 1.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
assertTrue(c.getWrongMess() > 0, "BER=1 should produce wrong messages");
assertEquals(0, c.getCorrectMess(), "BER=1 should produce no correct messages");
}
@Test
void testIntermediateBER() {
CRCAlgorithm c = new CRCAlgorithm("1101", 4, 0.5);
c.generateRandomMess();
for (int i = 0; i < 1000; i++) {
c.refactor();
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
}
assertTrue(c.getWrongMess() > 0, "Some wrong messages expected with BER=0.5");
assertTrue(c.getWrongMessCaught() >= 0, "Wrong messages caught counter >= 0");
assertTrue(c.getWrongMessNotCaught() >= 0, "Wrong messages not caught counter >= 0");
assertTrue(c.getCorrectMess() >= 0, "Correct messages counter >= 0");
assertEquals(c.getWrongMess(), c.getWrongMessCaught() + c.getWrongMessNotCaught(), "Sum of caught and not caught wrong messages should equal total wrong messages");
}
@Test
void testMessageChangedFlag() {
CRCAlgorithm c = new CRCAlgorithm("1010", 4, 1.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
assertTrue(c.getWrongMess() > 0, "Message should be marked as changed with BER=1");
}
@Test
void testSmallMessageSize() {
CRCAlgorithm c = new CRCAlgorithm("11", 2, 0.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
assertEquals(0, c.getWrongMess(), "No errors expected for BER=0 with small message");
}
@Test
void testLargeMessageSize() {
CRCAlgorithm c = new CRCAlgorithm("1101", 1000, 0.01);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
// Just ensure counters are updated, no exceptions
assertTrue(c.getWrongMess() >= 0);
assertTrue(c.getCorrectMess() >= 0);
}
@Test
void testSingleBitMessage() {
CRCAlgorithm c = new CRCAlgorithm("11", 1, 0.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
assertTrue(c.getCorrectMess() >= 0, "Single bit message should be handled");
}
@Test
void testPolynomialLongerThanMessage() {
CRCAlgorithm c = new CRCAlgorithm("11010101", 3, 0.0);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
// Should not crash, counters should be valid
assertTrue(c.getCorrectMess() + c.getWrongMess() >= 0);
}
@Test
void testPolynomialWithOnlyOnes() {
CRCAlgorithm c = new CRCAlgorithm("1111", 5, 0.1);
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
assertTrue(c.getCorrectMess() + c.getWrongMess() >= 0);
}
@Test
void testMultipleRefactorCalls() {
CRCAlgorithm c = new CRCAlgorithm("1101", 5, 0.2);
for (int i = 0; i < 5; i++) {
c.refactor();
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
}
// Counters should accumulate across multiple runs
assertTrue(c.getCorrectMess() + c.getWrongMess() > 0);
}
@Test
void testCounterConsistency() {
CRCAlgorithm c = new CRCAlgorithm("1101", 10, 0.3);
for (int i = 0; i < 100; i++) {
c.refactor();
c.generateRandomMess();
c.divideMessageWithP(false);
c.changeMess();
c.divideMessageWithP(true);
}
// Total messages processed should equal correct + wrong
int totalProcessed = c.getCorrectMess() + c.getWrongMess();
assertEquals(100, totalProcessed, "Total processed messages should equal iterations");
// Wrong messages should equal caught + not caught
assertEquals(c.getWrongMess(), c.getWrongMessCaught() + c.getWrongMessNotCaught(), "Wrong messages should equal sum of caught and not caught");
}
@Test
void testGetterMethodsInitialState() {
CRCAlgorithm c = new CRCAlgorithm("1101", 10, 0.1);
// Check initial state
assertEquals(0, c.getCorrectMess(), "Initial correct messages should be 0");
assertEquals(0, c.getWrongMess(), "Initial wrong messages should be 0");
assertEquals(0, c.getWrongMessCaught(), "Initial caught wrong messages should be 0");
assertEquals(0, c.getWrongMessNotCaught(), "Initial not caught wrong messages should be 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/others/PageRankTest.java | src/test/java/com/thealgorithms/others/PageRankTest.java | package com.thealgorithms.others;
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 org.junit.jupiter.api.Test;
/**
* Test class for PageRank algorithm implementation
*
* @author Hardvan
*/
class PageRankTest {
private static final double EPSILON = 0.0001; // Tolerance for floating point comparisons
/**
* Test basic PageRank calculation with a simple 3-node graph
* Graph: 1 -> 2, 2 -> 3, 3 -> 1
*/
@Test
void testSimpleThreeNodeGraph() {
PageRank pageRank = new PageRank(3);
// Create a simple circular graph: 1 -> 2 -> 3 -> 1
int[][] adjacencyMatrix = new int[10][10];
adjacencyMatrix[1][2] = 1; // Node 1 links to Node 2
adjacencyMatrix[2][3] = 1; // Node 2 links to Node 3
adjacencyMatrix[3][1] = 1; // Node 3 links to Node 1
pageRank.setAdjacencyMatrix(adjacencyMatrix);
double[] result = pageRank.calculatePageRank(3);
// All nodes should have equal PageRank in a circular graph
assertNotNull(result);
assertEquals(result[1], result[2], EPSILON);
assertEquals(result[2], result[3], EPSILON);
}
/**
* Test PageRank with a two-node graph where one node points to another
*/
@Test
void testTwoNodeGraph() {
PageRank pageRank = new PageRank(2);
// Node 1 links to Node 2
pageRank.setEdge(1, 2, 1);
double[] result = pageRank.calculatePageRank(2);
// Node 2 should have higher PageRank than Node 1 (after 2 iterations)
assertNotNull(result);
assertEquals(0.2775, result[2], EPSILON);
assertEquals(0.15, result[1], EPSILON);
}
/**
* Test PageRank with a single node (no links)
*/
@Test
void testSingleNode() {
PageRank pageRank = new PageRank(1);
double[] result = pageRank.calculatePageRank(1);
// Single node should have (1-d) = 0.15 after applying damping
assertNotNull(result);
assertEquals(0.15, result[1], EPSILON);
}
/**
* Test PageRank with a hub-and-spoke configuration
* Node 1 is the hub, pointing to nodes 2, 3, and 4
*/
@Test
void testHubAndSpokeGraph() {
PageRank pageRank = new PageRank(4);
// Hub node (1) links to all other nodes
pageRank.setEdge(1, 2, 1);
pageRank.setEdge(1, 3, 1);
pageRank.setEdge(1, 4, 1);
// All spokes link back to hub
pageRank.setEdge(2, 1, 1);
pageRank.setEdge(3, 1, 1);
pageRank.setEdge(4, 1, 1);
double[] result = pageRank.calculatePageRank(4);
assertNotNull(result);
// Hub should have higher PageRank
assertEquals(result[2], result[3], EPSILON);
assertEquals(result[3], result[4], EPSILON);
}
/**
* Test PageRank with multiple iterations
*/
@Test
void testMultipleIterations() {
PageRank pageRank = new PageRank(3);
pageRank.setEdge(1, 2, 1);
pageRank.setEdge(2, 3, 1);
pageRank.setEdge(3, 1, 1);
double[] result2Iterations = pageRank.calculatePageRank(3, 0.85, 2, false);
double[] result5Iterations = pageRank.calculatePageRank(3, 0.85, 5, false);
assertNotNull(result2Iterations);
assertNotNull(result5Iterations);
}
/**
* Test getPageRank method for individual node
*/
@Test
void testGetPageRank() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
pageRank.calculatePageRank(2);
double node1PageRank = pageRank.getPageRank(1);
double node2PageRank = pageRank.getPageRank(2);
assertEquals(0.15, node1PageRank, EPSILON);
assertEquals(0.2775, node2PageRank, EPSILON);
}
/**
* Test getAllPageRanks method
*/
@Test
void testGetAllPageRanks() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
pageRank.calculatePageRank(2);
double[] allPageRanks = pageRank.getAllPageRanks();
assertNotNull(allPageRanks);
assertEquals(0.15, allPageRanks[1], EPSILON);
assertEquals(0.2775, allPageRanks[2], EPSILON);
}
/**
* Test that self-loops are not allowed
*/
@Test
void testNoSelfLoops() {
PageRank pageRank = new PageRank(2);
// Try to set a self-loop
pageRank.setEdge(1, 1, 1);
pageRank.setEdge(1, 2, 1);
double[] result = pageRank.calculatePageRank(2);
assertNotNull(result);
// Self-loop should be ignored
}
/**
* Test exception when node count is too small
*/
@Test
void testInvalidNodeCountTooSmall() {
assertThrows(IllegalArgumentException.class, () -> new PageRank(0));
}
/**
* Test exception when node count is too large
*/
@Test
void testInvalidNodeCountTooLarge() {
assertThrows(IllegalArgumentException.class, () -> new PageRank(11));
}
/**
* Test exception for invalid damping factor (negative)
*/
@Test
void testInvalidDampingFactorNegative() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
assertThrows(IllegalArgumentException.class, () -> pageRank.calculatePageRank(2, -0.1, 2, false));
}
/**
* Test exception for invalid damping factor (greater than 1)
*/
@Test
void testInvalidDampingFactorTooLarge() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
assertThrows(IllegalArgumentException.class, () -> pageRank.calculatePageRank(2, 1.5, 2, false));
}
/**
* Test exception for invalid iterations (less than 1)
*/
@Test
void testInvalidIterations() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
assertThrows(IllegalArgumentException.class, () -> pageRank.calculatePageRank(2, 0.85, 0, false));
}
/**
* Test exception when getting PageRank for invalid node
*/
@Test
void testGetPageRankInvalidNode() {
PageRank pageRank = new PageRank(2);
pageRank.calculatePageRank(2);
assertThrows(IllegalArgumentException.class, () -> pageRank.getPageRank(3));
}
/**
* Test exception when getting PageRank for node less than 1
*/
@Test
void testGetPageRankNodeLessThanOne() {
PageRank pageRank = new PageRank(2);
pageRank.calculatePageRank(2);
assertThrows(IllegalArgumentException.class, () -> pageRank.getPageRank(0));
}
/**
* Test complex graph with multiple incoming and outgoing links
*/
@Test
void testComplexGraph() {
PageRank pageRank = new PageRank(4);
// Create a more complex graph
pageRank.setEdge(1, 2, 1);
pageRank.setEdge(1, 3, 1);
pageRank.setEdge(2, 3, 1);
pageRank.setEdge(3, 4, 1);
pageRank.setEdge(4, 1, 1);
double[] result = pageRank.calculatePageRank(4);
assertNotNull(result);
// Node 3 should have high PageRank (receives links from nodes 1 and 2)
// After 2 iterations, the sum will not equal total nodes
double sum = result[1] + result[2] + result[3] + result[4];
assertEquals(1.8325, sum, EPSILON);
}
/**
* Test that PageRank values sum after 2 iterations
*/
@Test
void testPageRankSum() {
PageRank pageRank = new PageRank(5);
// Create arbitrary graph
pageRank.setEdge(1, 2, 1);
pageRank.setEdge(2, 3, 1);
pageRank.setEdge(3, 4, 1);
pageRank.setEdge(4, 5, 1);
pageRank.setEdge(5, 1, 1);
double[] result = pageRank.calculatePageRank(5);
double sum = 0;
for (int i = 1; i <= 5; i++) {
sum += result[i];
}
// Sum after 2 iterations with default damping factor
assertEquals(2.11, sum, EPSILON);
}
/**
* Test graph with isolated node (no incoming or outgoing links)
*/
@Test
void testGraphWithIsolatedNode() {
PageRank pageRank = new PageRank(3);
// Node 1 and 2 are connected, Node 3 is isolated
pageRank.setEdge(1, 2, 1);
pageRank.setEdge(2, 1, 1);
double[] result = pageRank.calculatePageRank(3);
assertNotNull(result);
// Isolated node should have some PageRank due to damping factor
assertEquals(0.15, result[3], EPSILON);
}
/**
* Test verbose mode (should not throw exception)
*/
@Test
void testVerboseMode() {
PageRank pageRank = new PageRank(2);
pageRank.setEdge(1, 2, 1);
// This should execute without throwing an exception
double[] result = pageRank.calculatePageRank(2, 0.85, 2, true);
assertNotNull(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/others/MosAlgorithmTest.java | src/test/java/com/thealgorithms/others/MosAlgorithmTest.java | package com.thealgorithms.others;
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.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
/**
* Test class for MosAlgorithm
*
* @author BEASTSHRIRAM
*/
class MosAlgorithmTest {
@Test
void testRangeSumQueriesBasic() {
int[] arr = {1, 3, 5, 2, 7};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 2, 0), // Sum of [1, 3, 5] = 9
new MosAlgorithm.Query(1, 3, 1), // Sum of [3, 5, 2] = 10
new MosAlgorithm.Query(2, 4, 2) // Sum of [5, 2, 7] = 14
};
int[] expected = {9, 10, 14};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testRangeSumQueriesSingleElement() {
int[] arr = {5, 10, 15, 20};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 0, 0), // Sum of [5] = 5
new MosAlgorithm.Query(1, 1, 1), // Sum of [10] = 10
new MosAlgorithm.Query(2, 2, 2), // Sum of [15] = 15
new MosAlgorithm.Query(3, 3, 3) // Sum of [20] = 20
};
int[] expected = {5, 10, 15, 20};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testRangeSumQueriesFullArray() {
int[] arr = {1, 2, 3, 4, 5};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 4, 0) // Sum of entire array = 15
};
int[] expected = {15};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testRangeSumQueriesOverlapping() {
int[] arr = {2, 4, 6, 8, 10};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 2, 0), // Sum of [2, 4, 6] = 12
new MosAlgorithm.Query(1, 3, 1), // Sum of [4, 6, 8] = 18
new MosAlgorithm.Query(2, 4, 2) // Sum of [6, 8, 10] = 24
};
int[] expected = {12, 18, 24};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testRangeFrequencyQueriesBasic() {
int[] arr = {1, 2, 2, 1, 3, 2, 1};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 3, 0), // Count of 2 in [1, 2, 2, 1] = 2
new MosAlgorithm.Query(1, 5, 1), // Count of 2 in [2, 2, 1, 3, 2] = 3
new MosAlgorithm.Query(4, 6, 2) // Count of 2 in [3, 2, 1] = 1
};
int[] expected = {2, 3, 1};
int[] results = MosAlgorithm.solveRangeFrequencyQueries(arr, queries, 2);
assertArrayEquals(expected, results);
}
@Test
void testRangeFrequencyQueriesNoMatch() {
int[] arr = {1, 3, 5, 7, 9};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 2, 0), // Count of 2 in [1, 3, 5] = 0
new MosAlgorithm.Query(1, 4, 1) // Count of 2 in [3, 5, 7, 9] = 0
};
int[] expected = {0, 0};
int[] results = MosAlgorithm.solveRangeFrequencyQueries(arr, queries, 2);
assertArrayEquals(expected, results);
}
@Test
void testRangeFrequencyQueriesAllMatch() {
int[] arr = {5, 5, 5, 5, 5};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 2, 0), // Count of 5 in [5, 5, 5] = 3
new MosAlgorithm.Query(1, 3, 1), // Count of 5 in [5, 5, 5] = 3
new MosAlgorithm.Query(0, 4, 2) // Count of 5 in [5, 5, 5, 5, 5] = 5
};
int[] expected = {3, 3, 5};
int[] results = MosAlgorithm.solveRangeFrequencyQueries(arr, queries, 5);
assertArrayEquals(expected, results);
}
@Test
void testEmptyArray() {
int[] arr = {};
MosAlgorithm.Query[] queries = {};
int[] expected = {};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testNullInputs() {
int[] results1 = MosAlgorithm.solveRangeSumQueries(null, null);
assertArrayEquals(new int[0], results1);
int[] results2 = MosAlgorithm.solveRangeFrequencyQueries(null, null, 1);
assertArrayEquals(new int[0], results2);
}
@Test
void testQueryStructure() {
MosAlgorithm.Query query = new MosAlgorithm.Query(1, 5, 0);
assertEquals(1, query.left);
assertEquals(5, query.right);
assertEquals(0, query.index);
assertEquals(0, query.result); // Default value
}
@Test
void testLargerArray() {
int[] arr = {1, 4, 2, 8, 5, 7, 3, 6, 9, 10};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 4, 0), // Sum of [1, 4, 2, 8, 5] = 20
new MosAlgorithm.Query(2, 7, 1), // Sum of [2, 8, 5, 7, 3, 6] = 31
new MosAlgorithm.Query(5, 9, 2), // Sum of [7, 3, 6, 9, 10] = 35
new MosAlgorithm.Query(1, 8, 3) // Sum of [4, 2, 8, 5, 7, 3, 6, 9] = 44
};
int[] expected = {20, 31, 35, 44};
int[] results = MosAlgorithm.solveRangeSumQueries(arr, queries);
assertArrayEquals(expected, results);
}
@Test
void testRangeFrequencyWithDuplicates() {
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
MosAlgorithm.Query[] queries = {
new MosAlgorithm.Query(0, 5, 0), // Count of 1 in [3, 1, 4, 1, 5, 9] = 2
new MosAlgorithm.Query(3, 9, 1), // Count of 1 in [1, 5, 9, 2, 6, 5, 3] = 1
new MosAlgorithm.Query(0, 9, 2) // Count of 1 in entire array = 2
};
int[] expected = {2, 1, 2};
int[] results = MosAlgorithm.solveRangeFrequencyQueries(arr, queries, 1);
assertArrayEquals(expected, results);
}
@Test
void testMainMethod() {
// Capture System.out
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outputStream));
try {
// Test main method
MosAlgorithm.main(new String[] {});
String output = outputStream.toString();
// Verify expected output contains demonstration
assertTrue(output.contains("Range Sum Queries:"));
assertTrue(output.contains("Range Frequency Queries (count of value 3):"));
assertTrue(output.contains("Array: [1, 3, 5, 2, 7, 6, 3, 1, 4, 8]"));
} finally {
System.setOut(originalOut);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java | src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Test class for {@link MaximumSumOfDistinctSubarraysWithLengthK}.
*
* This class contains comprehensive test cases to verify the correctness of the
* maximum subarray sum algorithm with distinct elements constraint.
*/
class MaximumSumOfDistinctSubarraysWithLengthKTest {
/**
* Parameterized test for various input scenarios.
*
* @param expected the expected maximum sum
* @param k the subarray size
* @param arr the input array
*/
@ParameterizedTest
@MethodSource("inputStream")
void testMaximumSubarraySum(long expected, int k, int[] arr) {
assertEquals(expected, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(k, arr));
}
/**
* Provides test cases for the parameterized test.
*
* Test cases cover:
* - Normal cases with distinct and duplicate elements
* - Edge cases (empty array, k = 0, k > array length)
* - Single element arrays
* - Arrays with all duplicates
* - Negative numbers
* - Large sums
*
* @return stream of test arguments
*/
private static Stream<Arguments> inputStream() {
return Stream.of(
// Normal case: [5, 4, 2] has distinct elements with sum 11, but [4, 2, 9] also
// distinct with sum 15
Arguments.of(15L, 3, new int[] {1, 5, 4, 2, 9, 9, 9}),
// All elements are same, no distinct subarray of size 3
Arguments.of(0L, 3, new int[] {4, 4, 4}),
// First three have duplicates, but [1, 2, 3] are distinct with sum 6, wait
// [9,1,2] has sum 12
Arguments.of(12L, 3, new int[] {9, 9, 9, 1, 2, 3}),
// k = 0, should return 0
Arguments.of(0L, 0, new int[] {9, 9, 9}),
// k > array length, should return 0
Arguments.of(0L, 5, new int[] {9, 9, 9}),
// k = 1, single element (always distinct)
Arguments.of(9L, 1, new int[] {9, 2, 3, 7}),
// All distinct elements, size matches array
Arguments.of(15L, 5, new int[] {1, 2, 3, 4, 5}),
// Array with negative numbers
Arguments.of(6L, 3, new int[] {-1, 2, 3, 1, -2, 4}),
// Single element array
Arguments.of(10L, 1, new int[] {10}),
// All duplicates with k = 2
Arguments.of(0L, 2, new int[] {7, 7, 7, 7}),
// Empty array
Arguments.of(0L, 3, new int[] {}),
// k much larger than array length
Arguments.of(0L, 10, new int[] {1, 2, 3}));
}
/**
* Test with a larger array and larger k value.
*/
@Test
void testLargerArray() {
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(5, arr);
// Maximum sum with 5 distinct elements: [6,7,8,9,10] = 40
assertEquals(40L, result);
}
/**
* Test with negative k value.
*/
@Test
void testNegativeK() {
int[] arr = new int[] {1, 2, 3, 4, 5};
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(-1, arr);
assertEquals(0L, result);
}
/**
* Test with null array.
*/
@Test
void testNullArray() {
int[] nullArray = null;
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, new int[][] {nullArray}[0]);
assertEquals(0L, result);
}
/**
* Test with array containing duplicates at boundaries.
*/
@Test
void testDuplicatesAtBoundaries() {
int[] arr = new int[] {1, 1, 2, 3, 4, 4};
// [2, 3, 4] is the only valid window with sum 9
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, arr);
assertEquals(9L, result);
}
/**
* Test with large numbers to verify long return type.
*/
@Test
void testLargeNumbers() {
int[] arr = new int[] {1000000, 2000000, 3000000, 4000000};
// All elements are distinct, max sum with k=3 is [2000000, 3000000, 4000000] =
// 9000000
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, arr);
assertEquals(9000000L, result);
}
/**
* Test where multiple windows have the same maximum sum.
*/
@Test
void testMultipleMaxWindows() {
int[] arr = new int[] {1, 2, 3, 4, 3, 2, 1};
// Windows [1,2,3], [2,3,4], [4,3,2], [3,2,1] - max is [2,3,4] = 9
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, arr);
assertEquals(9L, result);
}
/**
* Test with only two elements and k=2.
*/
@Test
void testTwoElementsDistinct() {
int[] arr = new int[] {5, 10};
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(2, arr);
assertEquals(15L, result);
}
/**
* Test with only two elements (duplicates) and k=2.
*/
@Test
void testTwoElementsDuplicate() {
int[] arr = new int[] {5, 5};
long result = MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(2, arr);
assertEquals(0L, 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/others/SkylineProblemTest.java | src/test/java/com/thealgorithms/others/SkylineProblemTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
public class SkylineProblemTest {
@Test
public void testSingleBuildingSkyline() {
SkylineProblem skylineProblem = new SkylineProblem();
skylineProblem.building = new SkylineProblem.Building[1];
skylineProblem.add(2, 10, 9);
ArrayList<SkylineProblem.Skyline> result = skylineProblem.findSkyline(0, 0);
assertEquals(2, result.get(0).coordinates);
assertEquals(10, result.get(0).height);
assertEquals(9, result.get(1).coordinates);
assertEquals(0, result.get(1).height);
}
@Test
public void testTwoBuildingsSkyline() {
SkylineProblem skylineProblem = new SkylineProblem();
skylineProblem.building = new SkylineProblem.Building[2];
skylineProblem.add(1, 11, 5);
skylineProblem.add(2, 6, 7);
ArrayList<SkylineProblem.Skyline> result = skylineProblem.findSkyline(0, 1);
// Expected skyline points: (1, 11), (5, 6), (7, 0)
assertEquals(1, result.get(0).coordinates);
assertEquals(11, result.get(0).height);
assertEquals(5, result.get(1).coordinates);
assertEquals(6, result.get(1).height);
assertEquals(7, result.get(2).coordinates);
assertEquals(0, result.get(2).height);
}
@Test
public void testMergeSkyline() {
SkylineProblem skylineProblem = new SkylineProblem();
ArrayList<SkylineProblem.Skyline> sky1 = new ArrayList<>();
ArrayList<SkylineProblem.Skyline> sky2 = new ArrayList<>();
sky1.add(skylineProblem.new Skyline(2, 10));
sky1.add(skylineProblem.new Skyline(9, 0));
sky2.add(skylineProblem.new Skyline(3, 15));
sky2.add(skylineProblem.new Skyline(7, 0));
ArrayList<SkylineProblem.Skyline> result = skylineProblem.mergeSkyline(sky1, sky2);
// Expected merged skyline: (2, 10), (3, 15), (7, 10), (9, 0)
assertEquals(2, result.get(0).coordinates);
assertEquals(10, result.get(0).height);
assertEquals(3, result.get(1).coordinates);
assertEquals(15, result.get(1).height);
assertEquals(7, result.get(2).coordinates);
assertEquals(10, result.get(2).height);
assertEquals(9, result.get(3).coordinates);
assertEquals(0, result.get(3).height);
}
@Test
public void testMultipleBuildingsSkyline() {
SkylineProblem skylineProblem = new SkylineProblem();
skylineProblem.building = new SkylineProblem.Building[3];
skylineProblem.add(1, 10, 5);
skylineProblem.add(2, 15, 7);
skylineProblem.add(3, 12, 9);
ArrayList<SkylineProblem.Skyline> result = skylineProblem.findSkyline(0, 2);
assertEquals(1, result.get(0).coordinates);
assertEquals(10, result.get(0).height);
assertEquals(2, result.get(1).coordinates);
assertEquals(15, result.get(1).height);
assertEquals(7, result.get(2).coordinates);
assertEquals(12, result.get(2).height);
assertEquals(9, result.get(3).coordinates);
assertEquals(0, result.get(3).height);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/ArrayRightRotationTest.java | src/test/java/com/thealgorithms/others/ArrayRightRotationTest.java | package com.thealgorithms.others;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class ArrayRightRotationTest {
@Test
void testArrayRightRotation() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
int[] expected = {5, 6, 7, 1, 2, 3, 4};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
@Test
void testArrayRightRotationWithZeroSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 0;
int[] expected = {1, 2, 3, 4, 5, 6, 7};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
@Test
void testArrayRightRotationWithEqualSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = arr.length;
int[] expected = {1, 2, 3, 4, 5, 6, 7};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
@Test
void testArrayRightRotationWithLowerSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 2;
int[] expected = {6, 7, 1, 2, 3, 4, 5};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
@Test
void testArrayRightRotationWithHigherSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 10;
int[] expected = {5, 6, 7, 1, 2, 3, 4};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
}
| 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.