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/sorts/StalinSortTest.java | src/test/java/com/thealgorithms/sorts/StalinSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class StalinSortTest {
@Test
public void testSortIntegers() {
StalinSort stalinSort = new StalinSort();
Integer[] input = {4, 23, 6, 78, 1, 54, 231, 9, 12};
Integer[] expected = {4, 23, 78, 231};
Integer[] result = stalinSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortStrings() {
StalinSort stalinSort = new StalinSort();
String[] input = {"c", "a", "e", "b", "d"};
String[] expected = {"c", "e"};
String[] result = stalinSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortWithDuplicates() {
StalinSort stalinSort = new StalinSort();
Integer[] input = {1, 3, 2, 2, 5, 4};
Integer[] expected = {1, 3, 5};
Integer[] result = stalinSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortEmptyArray() {
StalinSort stalinSort = new StalinSort();
Integer[] input = {};
Integer[] expected = {};
Integer[] result = stalinSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortSingleElement() {
StalinSort stalinSort = new StalinSort();
Integer[] input = {42};
Integer[] expected = {42};
Integer[] result = stalinSort.sort(input);
assertArrayEquals(expected, result);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/ShellSortTest.java | src/test/java/com/thealgorithms/sorts/ShellSortTest.java | package com.thealgorithms.sorts;
public class ShellSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new ShellSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/PancakeSortTest.java | src/test/java/com/thealgorithms/sorts/PancakeSortTest.java | package com.thealgorithms.sorts;
public class PancakeSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new PancakeSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java | src/test/java/com/thealgorithms/sorts/SortUtilsTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
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;
class SortUtilsTest {
@Test
void isSortedEmptyArray() {
Double[] emptyArray = {};
assertTrue(SortUtils.isSorted(emptyArray));
}
@Test
void isSortedWithSingleElement() {
Double[] singleElementArray = {1.0};
assertTrue(SortUtils.isSorted(singleElementArray));
}
@Test
void isSortedArrayTrue() {
Integer[] array = {1, 1, 2, 3, 5, 8, 11};
assertTrue(SortUtils.isSorted(array));
Integer[] identicalArray = {1, 1, 1, 1, 1};
assertTrue(SortUtils.isSorted(identicalArray));
Double[] doubles = {-15.123, -15.111, 0.0, 0.12, 0.15};
assertTrue(SortUtils.isSorted(doubles));
}
@Test
void isSortedArrayFalse() {
Double[] array = {1.0, 3.0, -0.15};
assertFalse(SortUtils.isSorted(array));
Integer[] array2 = {14, 15, 16, 1};
assertFalse(SortUtils.isSorted(array2));
Integer[] array3 = {5, 4, 3, 2, 1};
assertFalse(SortUtils.isSorted(array3));
}
@Test
void isSortedListTrue() {
List<Integer> list = List.of(1, 1, 2, 3, 5, 8, 11);
assertTrue(SortUtils.isSorted(list));
List<Integer> identicalList = List.of(1, 1, 1, 1, 1);
assertTrue(SortUtils.isSorted(identicalList));
List<Double> doubles = List.of(-15.123, -15.111, 0.0, 0.12, 0.15);
assertTrue(SortUtils.isSorted(doubles));
}
@Test
void isSortedListFalse() {
List<Double> list = List.of(1.0, 3.0, -0.15);
assertFalse(SortUtils.isSorted(list));
List<Integer> array2 = List.of(14, 15, 16, 1);
assertFalse(SortUtils.isSorted(array2));
List<Integer> array3 = List.of(5, 4, 3, 2, 1);
assertFalse(SortUtils.isSorted(array3));
}
@ParameterizedTest
@MethodSource("provideArraysForSwap")
public <T> void testSwap(T[] array, int i, int j, T[] expected) {
SortUtils.swap(array, i, j);
assertArrayEquals(expected, array);
}
@ParameterizedTest
@MethodSource("provideArraysForSwap")
public <T> void testSwapFlippedIndices(T[] array, int i, int j, T[] expected) {
SortUtils.swap(array, j, i);
assertArrayEquals(expected, array);
}
private static Stream<Arguments> provideArraysForSwap() {
return Stream.of(Arguments.of(new Integer[] {1, 2, 3, 4}, 1, 2, new Integer[] {1, 3, 2, 4}), Arguments.of(new Integer[] {1, 2, 3, 4}, 0, 3, new Integer[] {4, 2, 3, 1}), Arguments.of(new Integer[] {1, 2, 3, 4}, 2, 2, new Integer[] {1, 2, 3, 4}),
Arguments.of(new String[] {"a", "b", "c", "d"}, 0, 3, new String[] {"d", "b", "c", "a"}), Arguments.of(new String[] {null, "b", "c", null}, 0, 3, new String[] {null, "b", "c", null}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java | src/test/java/com/thealgorithms/sorts/PatienceSortTest.java | package com.thealgorithms.sorts;
public class PatienceSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new PatienceSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SlowSortTest.java | src/test/java/com/thealgorithms/sorts/SlowSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Objects;
import org.junit.jupiter.api.Test;
/**
* @author Rebecca Velez (https://github.com/rebeccavelez)
* @see SlowSort
*/
public class SlowSortTest {
private SlowSort slowSort = new SlowSort();
@Test
public void slowSortEmptyArray() {
Integer[] inputArray = {};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortSingleIntegerElementArray() {
Integer[] inputArray = {5};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {5};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortSingleStringElementArray() {
String[] inputArray = {"k"};
String[] outputArray = slowSort.sort(inputArray);
String[] expectedOutput = {"k"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortIntegerArray() {
Integer[] inputArray = {8, 84, 53, -683, 953, 64, 2, 202, 98, -10};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {-683, -10, 2, 8, 53, 64, 84, 98, 202, 953};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortDuplicateIntegerArray() {
Integer[] inputArray = {8, 84, 8, -2, 953, 64, 2, 953, 98};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {-2, 2, 8, 8, 64, 84, 98, 953, 953};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortStringArray() {
String[] inputArray = {"g", "d", "a", "b", "f", "c", "e"};
String[] outputArray = slowSort.sort(inputArray);
String[] expectedOutput = {"a", "b", "c", "d", "e", "f", "g"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortDuplicateStringArray() {
String[] inputArray = {"g", "d", "a", "g", "b", "f", "d", "c", "e"};
String[] outputArray = slowSort.sort(inputArray);
String[] expectedOutput = {"a", "b", "c", "d", "d", "e", "f", "g", "g"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void slowSortStringSymbolArray() {
String[] inputArray = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"};
String[] outputArray = slowSort.sort(inputArray);
String[] expectedOutput = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortAlreadySortedArray() {
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortReversedSortedArray() {
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortAllEqualArray() {
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = slowSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortMixedCaseStrings() {
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = slowSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
public void testSortCustomObjects() {
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = slowSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/RadixSortTest.java | src/test/java/com/thealgorithms/sorts/RadixSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 RadixSortTest {
@ParameterizedTest
@MethodSource("provideTestCases")
public void test(int[] inputArray, int[] expectedArray) {
assertArrayEquals(RadixSort.sort(inputArray), expectedArray);
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new int[] {170, 45, 75, 90, 802, 24, 2, 66}, new int[] {2, 24, 45, 66, 75, 90, 170, 802}), Arguments.of(new int[] {3, 3, 3, 3}, new int[] {3, 3, 3, 3}), Arguments.of(new int[] {9, 4, 6, 8, 14, 3}, new int[] {3, 4, 6, 8, 9, 14}),
Arguments.of(new int[] {10, 90, 49, 2, 1, 5, 23}, new int[] {1, 2, 5, 10, 23, 49, 90}), Arguments.of(new int[] {1, 3, 4, 2, 7, 8}, new int[] {1, 2, 3, 4, 7, 8}), Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {1}, new int[] {1}),
Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), Arguments.of(new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}),
Arguments.of(new int[] {1000000000, 999999999, 888888888, 777777777}, new int[] {777777777, 888888888, 999999999, 1000000000}), Arguments.of(new int[] {123, 9, 54321, 123456789, 0}, new int[] {0, 9, 123, 54321, 123456789}));
}
@Test
public void testWithNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> RadixSort.sort(new int[] {3, 1, 4, 1, 5, -9}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java | src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java | package com.thealgorithms.sorts;
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 static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.sorts.TopologicalSort.Graph;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
class TopologicalSortTest {
@Test
void successTest() {
/*
* Professor Bumstead example DAG. Each directed edge means that garment u must be put on
* before garment v.
* */
Graph graph = new Graph();
graph.addEdge("shirt", "tie", "belt");
graph.addEdge("tie", "jacket");
graph.addEdge("belt", "jacket");
graph.addEdge("watch", "");
graph.addEdge("undershorts", "pants", "shoes");
graph.addEdge("shoes", "");
graph.addEdge("socks", "shoes");
graph.addEdge("jacket", "");
graph.addEdge("pants", "belt", "shoes");
LinkedList<String> expected = new LinkedList<>();
expected.add("socks");
expected.add("undershorts");
expected.add("pants");
expected.add("shoes");
expected.add("watch");
expected.add("shirt");
expected.add("belt");
expected.add("tie");
expected.add("jacket");
assertIterableEquals(expected, TopologicalSort.sort(graph));
}
@Test
public void failureTest() {
/*
* Graph example from Geeks For Geeks
* https://www.geeksforgeeks.org/tree-back-edge-and-cross-edges-in-dfs-of-graph/
* */
Graph graph = new Graph();
graph.addEdge("1", "2", "3", "8");
graph.addEdge("2", "4");
graph.addEdge("3", "5");
graph.addEdge("4", "6");
graph.addEdge("5", "4", "7", "8");
graph.addEdge("6", "2");
graph.addEdge("7", "");
graph.addEdge("8", "");
Exception exception = assertThrows(RuntimeException.class, () -> TopologicalSort.sort(graph));
String expected = "This graph contains a cycle. No linear ordering is possible. "
+ "Back edge: 6 -> 2";
assertEquals(exception.getMessage(), expected);
}
@Test
void testEmptyGraph() {
Graph graph = new Graph();
LinkedList<String> sorted = TopologicalSort.sort(graph);
assertTrue(sorted.isEmpty());
}
@Test
void testSingleNode() {
Graph graph = new Graph();
graph.addEdge("A", "");
LinkedList<String> sorted = TopologicalSort.sort(graph);
assertEquals(1, sorted.size());
assertEquals("A", sorted.getFirst());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SwapSortTest.java | src/test/java/com/thealgorithms/sorts/SwapSortTest.java | package com.thealgorithms.sorts;
public class SwapSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SwapSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java | src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class DutchNationalFlagSortTest {
@Test
/*
1 will be used as intended middle.
Partitions on the result array: [ smaller than 1 , equal 1, greater than 1]
*/
void testOddDnfs() {
Integer[] integers = {1, 3, 1, 4, 0};
Integer[] integersResult = {0, 1, 1, 4, 3};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(integers);
assertArrayEquals(integers, integersResult);
}
@Test
/*
3 will be used as intended middle.
Partitions on the result array: [ smaller than 3 , equal 3, greater than 3]
*/
void testEvenDnfs() {
Integer[] integers = {8, 1, 3, 1, 4, 0};
Integer[] integersResult = {0, 1, 1, 3, 4, 8};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(integers);
assertArrayEquals(integers, integersResult);
}
@Test
/*
"b" will be used as intended middle.
Partitions on the result array: [ smaller than b , equal b, greater than b]
*/
void testEvenStringsDnfs() {
String[] strings = {"a", "d", "b", "s", "e", "e"};
String[] stringsResult = {"a", "b", "s", "e", "e", "d"};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(strings);
assertArrayEquals(strings, stringsResult);
}
@Test
/*
"b" will be used as intended middle.
Partitions on the result array: [ smaller than b , equal b, greater than b]
*/
void testOddStringsDnfs() {
String[] strings = {"a", "d", "b", "s", "e"};
String[] stringsResult = {"a", "b", "s", "e", "d"};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(strings);
assertArrayEquals(strings, stringsResult);
}
@Test
/*
0 will be used as intended middle.
Partitions on the result array: [ smaller than 0 , equal 0, greater than 0]
*/
void testOddMidGivenDnfs() {
Integer[] integers = {1, 3, 1, 4, 0};
Integer[] integersResult = {0, 1, 4, 3, 1};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(integers, 0);
assertArrayEquals(integers, integersResult);
}
@Test
/*
4 will be used as intended middle.
Partitions on the result array: [ smaller than 4 , equal 4, greater than 4]
*/
void testEvenMidGivenDnfs() {
Integer[] integers = {8, 1, 3, 1, 4, 0};
Integer[] integersResult = {0, 1, 3, 1, 4, 8};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(integers, 4);
assertArrayEquals(integers, integersResult);
}
@Test
/*
"s" will be used as intended middle.
Partitions on the result array: [ smaller than s , equal s, greater than s]
*/
void testEvenStringsMidGivenDnfs() {
String[] strings = {"a", "d", "b", "s", "e", "e"};
String[] stringsResult = {"a", "d", "b", "e", "e", "s"};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(strings, "s");
assertArrayEquals(strings, stringsResult);
}
@Test
/*
"e" will be used as intended middle.
Partitions on the result array: [ smaller than e , equal e, greater than e]
*/
void testOddStringsMidGivenDnfs() {
String[] strings = {"a", "d", "b", "s", "e"};
String[] stringsResult = {"a", "d", "b", "e", "s"};
DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
dutchNationalFlagSort.sort(strings, "e");
assertArrayEquals(strings, stringsResult);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/TreeSortTest.java | src/test/java/com/thealgorithms/sorts/TreeSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
/**
* @author Tabbygray (https://github.com/Tabbygray)
* @see TreeSort
*/
public class TreeSortTest {
private TreeSort treeSort = new TreeSort();
@Test
public void treeSortEmptyArray() {
Integer[] inputArray = {};
Integer[] outputArray = treeSort.sort(inputArray);
Integer[] expectedOutput = {};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void treeSortSingleStringElement() {
String[] inputArray = {"Test"};
String[] outputArray = treeSort.sort(inputArray);
String[] expectedArray = {"Test"};
assertArrayEquals(outputArray, expectedArray);
}
@Test
public void treeSortStringArray() {
String[] inputArray = {"F6w9", "l1qz", "dIxH", "larj", "kRzy", "vnNH", "3ftM", "hc4n", "C5Qi", "btGF"};
String[] outputArray = treeSort.sort(inputArray);
String[] expectedArray = {"3ftM", "C5Qi", "F6w9", "btGF", "dIxH", "hc4n", "kRzy", "l1qz", "larj", "vnNH"};
assertArrayEquals(outputArray, expectedArray);
}
@Test
public void treeSortIntegerArray() {
Integer[] inputArray = {-97, -44, -4, -85, -92, 74, 79, -26, 76, -5};
Integer[] outputArray = treeSort.sort(inputArray);
Integer[] expectedArray = {-97, -92, -85, -44, -26, -5, -4, 74, 76, 79};
assertArrayEquals(outputArray, expectedArray);
}
@Test
public void treeSortDoubleArray() {
Double[] inputArray = {0.8047485045, 0.4493112337, 0.8298433723, 0.2691406748, 0.2482782839, 0.5976243420, 0.6746235284, 0.0552623569, 0.3515624123, 0.0536747336};
Double[] outputArray = treeSort.sort(inputArray);
Double[] expectedArray = {0.0536747336, 0.0552623569, 0.2482782839, 0.2691406748, 0.3515624123, 0.4493112337, 0.5976243420, 0.6746235284, 0.8047485045, 0.8298433723};
assertArrayEquals(outputArray, expectedArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java | src/test/java/com/thealgorithms/sorts/InsertionSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Objects;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class InsertionSortTest {
private InsertionSort insertionSort;
@BeforeEach
void setUp() {
insertionSort = new InsertionSort();
}
@Test
void insertionSortSortEmptyArrayShouldPass() {
testEmptyArray(insertionSort::sort);
testEmptyArray(insertionSort::sentinelSort);
}
private void testEmptyArray(Function<Integer[], Integer[]> sortAlgorithm) {
Integer[] array = {};
Integer[] sorted = sortAlgorithm.apply(array);
Integer[] expected = {};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalSortSingleValueArrayShouldPass() {
testSingleValue(insertionSort::sort);
testSingleValue(insertionSort::sentinelSort);
}
private void testSingleValue(Function<Integer[], Integer[]> sortAlgorithm) {
Integer[] array = {7};
Integer[] sorted = sortAlgorithm.apply(array);
Integer[] expected = {7};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalWithIntegerArrayShouldPass() {
testIntegerArray(insertionSort::sort);
testIntegerArray(insertionSort::sentinelSort);
}
private void testIntegerArray(Function<Integer[], Integer[]> sortAlgorithm) {
Integer[] array = {49, 4, 36, 9, 144, 1};
Integer[] sorted = sortAlgorithm.apply(array);
Integer[] expected = {1, 4, 9, 36, 49, 144};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalForArrayWithNegativeValuesShouldPass() {
testWithNegativeValues(insertionSort::sort);
testWithNegativeValues(insertionSort::sentinelSort);
}
private void testWithNegativeValues(Function<Integer[], Integer[]> sortAlgorithm) {
Integer[] array = {49, -36, -144, -49, 1, 9};
Integer[] sorted = sortAlgorithm.apply(array);
Integer[] expected = {-144, -49, -36, 1, 9, 49};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalForArrayWithDuplicateValuesShouldPass() {
testWithDuplicates(insertionSort::sort);
testWithDuplicates(insertionSort::sentinelSort);
}
private void testWithDuplicates(Function<Integer[], Integer[]> sortAlgorithm) {
Integer[] array = {36, 1, 49, 1, 4, 9};
Integer[] sorted = sortAlgorithm.apply(array);
Integer[] expected = {1, 1, 4, 9, 36, 49};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalWithStringArrayShouldPass() {
testWithStringArray(insertionSort::sort);
testWithStringArray(insertionSort::sentinelSort);
}
private void testWithStringArray(Function<String[], String[]> sortAlgorithm) {
String[] array = {"c", "a", "e", "b", "d"};
String[] sorted = sortAlgorithm.apply(array);
String[] expected = {"a", "b", "c", "d", "e"};
assertArrayEquals(expected, sorted);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void insertionSortClassicalWithRandomArrayPass() {
testWithRandomArray(insertionSort::sort);
testWithRandomArray(insertionSort::sentinelSort);
}
private void testWithRandomArray(Function<Double[], Double[]> sortAlgorithm) {
int randomSize = SortUtilsRandomGenerator.generateInt(10_000);
Double[] array = SortUtilsRandomGenerator.generateArray(randomSize);
Double[] sorted = sortAlgorithm.apply(array);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
public void testSortAlreadySortedArray() {
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = insertionSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortReversedSortedArray() {
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = insertionSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortAllEqualArray() {
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = insertionSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortMixedCaseStrings() {
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = insertionSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
public void testSortCustomObjects() {
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = insertionSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/DarkSortTest.java | src/test/java/com/thealgorithms/sorts/DarkSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class DarkSortTest {
@Test
void testSortWithIntegers() {
Integer[] unsorted = {5, 3, 8, 6, 2, 7, 4, 1};
Integer[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertArrayEquals(expected, sorted);
}
@Test
void testEmptyArray() {
Integer[] unsorted = {};
Integer[] expected = {};
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertArrayEquals(expected, sorted);
}
@Test
void testSingleElementArray() {
Integer[] unsorted = {42};
Integer[] expected = {42};
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertArrayEquals(expected, sorted);
}
@Test
void testAlreadySortedArray() {
Integer[] unsorted = {1, 2, 3, 4, 5};
Integer[] expected = {1, 2, 3, 4, 5};
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertArrayEquals(expected, sorted);
}
@Test
void testDuplicateElementsArray() {
Integer[] unsorted = {4, 2, 7, 2, 1, 4};
Integer[] expected = {1, 2, 2, 4, 4, 7};
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertArrayEquals(expected, sorted);
}
@Test
void testNullArray() {
Integer[] unsorted = null;
DarkSort darkSort = new DarkSort();
Integer[] sorted = darkSort.sort(unsorted);
assertNull(sorted, "Sorting a null array should return null");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java | src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java | package com.thealgorithms.sorts;
public class SelectionSortRecursiveTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SelectionSortRecursive();
}
protected int getGeneratedArraySize() {
return 5000;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/CountingSortTest.java | src/test/java/com/thealgorithms/sorts/CountingSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CountingSortTest {
record TestCase(int[] inputArray, int[] expectedArray) {
}
static Stream<TestCase> provideTestCases() {
return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {4}, new int[] {4}), new TestCase(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), new TestCase(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}),
new TestCase(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {3, -1, 4, 1, 5, -9}, new int[] {-9, -1, 1, 3, 4, 5}),
new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}), new TestCase(new int[] {3, 3, -1, -1, 2, 2, 0, 0}, new int[] {-1, -1, 0, 0, 2, 2, 3, 3}), new TestCase(new int[] {-3, -2, -1, -5, -4}, new int[] {-5, -4, -3, -2, -1}),
new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {4, -5, 10, 0}, new int[] {-5, 0, 4, 10}));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testCountingSortException(TestCase testCase) {
int[] outputArray = CountingSort.sort(testCase.inputArray);
assertArrayEquals(testCase.expectedArray, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/FlashSortTest.java | src/test/java/com/thealgorithms/sorts/FlashSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class FlashSortTest extends SortingAlgorithmTest {
private final FlashSort flashSort = new FlashSort();
public FlashSort getFlashSort() {
return flashSort;
}
@Override
SortAlgorithm getSortAlgorithm() {
return getFlashSort();
}
@Test
public void testDefaultConstructor() {
double defaultRation = 0.45;
FlashSort sorter = new FlashSort();
assertEquals(defaultRation, sorter.getClassificationRatio());
}
@ParameterizedTest
@ValueSource(doubles = {0.1, 0.2, 0.5, 0.9})
public void testCustomConstructorValidRatio(double ratio) {
FlashSort sorter = new FlashSort(ratio);
assertEquals(ratio, sorter.getClassificationRatio());
}
@ParameterizedTest
@ValueSource(doubles = {0, 1, -0.1, 1.1})
public void testCustomConstructorInvalidRatio(double ratio) {
assertThrows(IllegalArgumentException.class, () -> new FlashSort(ratio));
}
@TestFactory
public List<DynamicTest> dynamicTestsForSorting() {
List<DynamicTest> dynamicTests = new ArrayList<>();
double[] ratios = {0.1, 0.2, 0.5, 0.9};
for (double ratio : ratios) {
FlashSort sorter = (FlashSort) getSortAlgorithm();
sorter.setClassificationRatio(ratio);
dynamicTests.addAll(createDynamicTestsForRatio(ratio));
}
return dynamicTests;
}
private List<DynamicTest> createDynamicTestsForRatio(double ratio) {
List<DynamicTest> dynamicTests = new ArrayList<>();
for (TestMethod testMethod : getTestMethodsFromSuperClass()) {
dynamicTests.add(DynamicTest.dynamicTest("Ratio: " + ratio + " - Test: " + testMethod.name(), testMethod.executable()));
}
return dynamicTests;
}
private List<TestMethod> getTestMethodsFromSuperClass() {
List<TestMethod> testMethods = new ArrayList<>();
Method[] methods = SortingAlgorithmTest.class.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
testMethods.add(new TestMethod(() -> {
try {
method.invoke(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}, method.getName()));
}
}
return testMethods;
}
record TestMethod(Executable executable, String name) {
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/HeapSortTest.java | src/test/java/com/thealgorithms/sorts/HeapSortTest.java | package com.thealgorithms.sorts;
public class HeapSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new HeapSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/BogoSortTest.java | src/test/java/com/thealgorithms/sorts/BogoSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Objects;
import org.junit.jupiter.api.Test;
public class BogoSortTest {
private BogoSort bogoSort = new BogoSort();
@Test
public void bogoSortEmptyArray() {
Integer[] inputArray = {};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortSingleIntegerArray() {
Integer[] inputArray = {4};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {4};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortSingleStringArray() {
String[] inputArray = {"s"};
String[] outputArray = bogoSort.sort(inputArray);
String[] expectedOutput = {"s"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortNonDuplicateIntegerArray() {
Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortDuplicateIntegerArray() {
Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortNonDuplicateStringArray() {
String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"};
String[] outputArray = bogoSort.sort(inputArray);
String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortDuplicateStringArray() {
String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"};
String[] outputArray = bogoSort.sort(inputArray);
String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortAlreadySortedArray() {
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortReversedSortedArray() {
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortAllEqualArray() {
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = bogoSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bogoSortMixedCaseStrings() {
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = bogoSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
public void bogoSortCustomObjects() {
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = bogoSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java | src/test/java/com/thealgorithms/sorts/SelectionSortTest.java | package com.thealgorithms.sorts;
class SelectionSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SelectionSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/PriorityQueueSortTest.java | src/test/java/com/thealgorithms/sorts/PriorityQueueSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class PriorityQueueSortTest {
@Test
void testNullArray() {
int[] input = null;
assertArrayEquals(null, PriorityQueueSort.sort(input));
}
@Test
void testSingleElementArray() {
int[] input = {5};
int[] expected = {5};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
@Test
void testSortNormalArray() {
int[] input = {7, 2, 9, 4, 1};
int[] expected = {1, 2, 4, 7, 9};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
@Test
void testEmptyArray() {
int[] input = {};
int[] expected = {};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
@Test
void testNegativeNumbers() {
int[] input = {3, -1, 2, -5, 0};
int[] expected = {-5, -1, 0, 2, 3};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
@Test
void testAlreadySortedArray() {
int[] input = {1, 2, 3, 4, 5};
int[] expected = {1, 2, 3, 4, 5};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
@Test
void testArrayWithDuplicates() {
int[] input = {5, 1, 3, 3, 2, 5};
int[] expected = {1, 2, 3, 3, 5, 5};
assertArrayEquals(expected, PriorityQueueSort.sort(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/sorts/BeadSortTest.java | src/test/java/com/thealgorithms/sorts/BeadSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 BeadSortTest {
@ParameterizedTest
@MethodSource("provideArraysForBeadSort")
public void testBeadSort(int[] inputArray, int[] expectedArray) {
BeadSort beadSort = new BeadSort();
assertArrayEquals(expectedArray, beadSort.sort(inputArray));
}
private static Stream<Arguments> provideArraysForBeadSort() {
return Stream.of(Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {4}, new int[] {4}), Arguments.of(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}),
Arguments.of(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}));
}
@Test
public void testWithNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> new BeadSort().sort(new int[] {3, 1, 4, 1, 5, -9}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java | src/test/java/com/thealgorithms/sorts/WiggleSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class WiggleSortTest {
@Test
void wiggleTestNumbersEven() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 2, 3, 4};
Integer[] result = {1, 4, 2, 3};
wiggleSort.sort(values);
assertArrayEquals(values, result);
}
@Test
void wiggleTestNumbersOdd() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 2, 3, 4, 5};
Integer[] result = {3, 5, 1, 4, 2};
wiggleSort.sort(values);
assertArrayEquals(values, result);
}
@Test
void wiggleTestNumbersOddDuplicates() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {7, 2, 2, 2, 5};
Integer[] result = {2, 7, 2, 5, 2};
wiggleSort.sort(values);
assertArrayEquals(values, result);
}
@Test
void wiggleTestNumbersOddMultipleDuplicates() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 1, 2, 2, 5};
Integer[] result = {2, 5, 1, 2, 1};
wiggleSort.sort(values);
assertArrayEquals(values, result);
}
@Test
void wiggleTestNumbersEvenMultipleDuplicates() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 1, 2, 2, 2, 5};
Integer[] result = {2, 5, 1, 2, 1, 2};
wiggleSort.sort(values);
System.out.println(Arrays.toString(values));
assertArrayEquals(values, result);
}
@Test
void wiggleTestNumbersEvenDuplicates() {
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 2, 4, 4};
Integer[] result = {1, 4, 2, 4};
wiggleSort.sort(values);
assertArrayEquals(values, result);
}
@Test
void wiggleTestStrings() {
WiggleSort wiggleSort = new WiggleSort();
String[] values = {"a", "b", "d", "c"};
String[] result = {"a", "d", "b", "c"};
wiggleSort.sort(values);
assertArrayEquals(values, 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/sorts/AdaptiveMergeSortTest.java | src/test/java/com/thealgorithms/sorts/AdaptiveMergeSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Objects;
import org.junit.jupiter.api.Test;
public class AdaptiveMergeSortTest {
@Test
public void testSortIntegers() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] input = {4, 23, 6, 78, 1, 54, 231, 9, 12};
Integer[] expected = {1, 4, 6, 9, 12, 23, 54, 78, 231};
Integer[] result = adaptiveMergeSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortStrings() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
String[] input = {"c", "a", "e", "b", "d"};
String[] expected = {"a", "b", "c", "d", "e"};
String[] result = adaptiveMergeSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortWithDuplicates() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] input = {1, 3, 2, 2, 5, 4};
Integer[] expected = {1, 2, 2, 3, 4, 5};
Integer[] result = adaptiveMergeSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortEmptyArray() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] input = {};
Integer[] expected = {};
Integer[] result = adaptiveMergeSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortSingleElement() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] input = {42};
Integer[] expected = {42};
Integer[] result = adaptiveMergeSort.sort(input);
assertArrayEquals(expected, result);
}
@Test
public void testSortAlreadySortedArray() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = adaptiveMergeSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortReversedSortedArray() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = adaptiveMergeSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortAllEqualArray() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = adaptiveMergeSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void testSortMixedCaseStrings() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = adaptiveMergeSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
public void testSortCustomObjects() {
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = adaptiveMergeSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java | src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java | package com.thealgorithms.sorts;
class DualPivotQuickSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new DualPivotQuickSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/TimSortTest.java | src/test/java/com/thealgorithms/sorts/TimSortTest.java | package com.thealgorithms.sorts;
class TimSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new TimSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/BucketSortTest.java | src/test/java/com/thealgorithms/sorts/BucketSortTest.java | package com.thealgorithms.sorts;
public class BucketSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new BucketSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java | src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java | package com.thealgorithms.sorts;
/**
* @author Tabbygray (https://github.com/Tabbygray)
* @see OddEvenSort
*/
public class OddEvenSortTest extends SortingAlgorithmTest {
private final OddEvenSort oddEvenSort = new OddEvenSort();
@Override
SortAlgorithm getSortAlgorithm() {
return oddEvenSort;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/QuickSortTest.java | src/test/java/com/thealgorithms/sorts/QuickSortTest.java | package com.thealgorithms.sorts;
/**
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
* @see QuickSort
*/
class QuickSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new QuickSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/BubbleSortRecursiveTest.java | src/test/java/com/thealgorithms/sorts/BubbleSortRecursiveTest.java | package com.thealgorithms.sorts;
public class BubbleSortRecursiveTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new BubbleSortRecursive();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java | src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java | package com.thealgorithms.sorts;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
class SortUtilsRandomGeneratorTest {
@RepeatedTest(1000)
void generateArray() {
int size = 1_000;
Double[] doubles = SortUtilsRandomGenerator.generateArray(size);
assertThat(doubles).hasSize(size);
assertThat(doubles).doesNotContainNull();
}
@Test
void generateArrayEmpty() {
int size = 0;
Double[] doubles = SortUtilsRandomGenerator.generateArray(size);
assertThat(doubles).hasSize(size);
}
@RepeatedTest(1000)
void generateDouble() {
Double randomDouble = SortUtilsRandomGenerator.generateDouble();
assertThat(randomDouble).isBetween(0.0, 1.0);
assertThat(randomDouble).isNotEqualTo(1.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/sorts/StrandSortTest.java | src/test/java/com/thealgorithms/sorts/StrandSortTest.java | package com.thealgorithms.sorts;
class StrandSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new StrandSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java | src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 PigeonholeSortTest {
@ParameterizedTest
@MethodSource("provideArraysForPigeonholeSort")
public void testPigeonholeSort(int[] inputArray, int[] expectedArray) {
PigeonholeSort.sort(inputArray);
assertArrayEquals(expectedArray, inputArray);
}
private static Stream<Arguments> provideArraysForPigeonholeSort() {
return Stream.of(Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {4}, new int[] {4}), Arguments.of(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}),
Arguments.of(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}));
}
@Test
public void testWithNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {3, 1, 4, 1, 5, -9}));
assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {-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/sorts/BinaryInsertionSortTest.java | src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java | package com.thealgorithms.sorts;
class BinaryInsertionSortTest extends SortingAlgorithmTest {
private final BinaryInsertionSort binaryInsertionSort = new BinaryInsertionSort();
@Override
SortAlgorithm getSortAlgorithm() {
return binaryInsertionSort;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java | src/test/java/com/thealgorithms/sorts/GnomeSortTest.java | package com.thealgorithms.sorts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Objects;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class GnomeSortTest {
private GnomeSort gnomeSort = new GnomeSort();
@Test
@DisplayName("GnomeSort empty Array")
public void gnomeSortEmptyArray() {
Integer[] inputArray = {};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEmpty();
}
@Test
@DisplayName("GnomeSort single Integer Array")
public void singleIntegerArray() {
Integer[] inputArray = {4};
Integer[] expectedOutput = {4};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort non duplicate Integer Array")
public void gnomeSortNonDuplicateIntegerArray() {
Integer[] inputArray = {6, 3, 87, 99, 27, 4};
Integer[] expectedOutput = {3, 4, 6, 27, 87, 99};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort Integer Array with duplicates")
public void gnomeSortDuplicateIntegerArray() {
Integer[] inputArray = {6, 3, 87, 3, 99, 27, 4, 27};
Integer[] expectedOutput = {3, 3, 4, 6, 27, 27, 87, 99};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort negative Integer Array with duplicates")
public void gnomeSortNegativeDuplicateIntegerArray() {
Integer[] inputArray = {6, 3, -87, 3, 99, -27, 4, -27};
Integer[] expectedOutput = {-87, -27, -27, 3, 3, 4, 6, 99};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort single String Array")
public void singleStringArray() {
String[] inputArray = {"b"};
String[] expectedOutput = {"b"};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort non duplicate String Array")
public void gnomeSortNonDuplicateStringArray() {
String[] inputArray = {"He", "A", "bc", "lo", "n", "bcp", "mhp", "d"};
String[] expectedOutput = {"A", "He", "bc", "bcp", "d", "lo", "mhp", "n"};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort String Array with duplicates")
public void gnomeSortDuplicateStringArray() {
String[] inputArray = {"He", "A", "bc", "lo", "n", "bcp", "mhp", "bcp"};
String[] expectedOutput = {"A", "He", "bc", "bcp", "bcp", "lo", "mhp", "n"};
gnomeSort.sort(inputArray);
assertThat(inputArray).isEqualTo(expectedOutput);
}
@Test
@DisplayName("GnomeSort for sorted Array")
public void testSortAlreadySortedArray() {
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = gnomeSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
@DisplayName("GnomeSort for reversed sorted Array")
public void testSortReversedSortedArray() {
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = gnomeSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
@DisplayName("GnomeSort for All equal Array")
public void testSortAllEqualArray() {
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = gnomeSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
@DisplayName("GnomeSort String Array with mixed cases")
public void testSortMixedCaseStrings() {
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = gnomeSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
@DisplayName("GnomeSort Custom Object Array")
public void testSortCustomObjects() {
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = gnomeSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java | src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java | package com.thealgorithms.sorts;
public class CocktailShakerSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new CocktailShakerSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java | src/test/java/com/thealgorithms/sorts/SpreadSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class SpreadSortTest extends SortingAlgorithmTest {
protected int getGeneratedArraySize() {
return 1000;
}
@Override
SortAlgorithm getSortAlgorithm() {
return new SpreadSort();
}
private static Stream<Arguments> wrongConstructorInputs() {
return Stream.of(Arguments.of(0, 16, 2, IllegalArgumentException.class), Arguments.of(16, 0, 2, IllegalArgumentException.class), Arguments.of(16, 16, 0, IllegalArgumentException.class), Arguments.of(1001, 16, 2, IllegalArgumentException.class),
Arguments.of(16, 1001, 2, IllegalArgumentException.class), Arguments.of(16, 16, 101, IllegalArgumentException.class));
}
@ParameterizedTest
@MethodSource("wrongConstructorInputs")
void testConstructor(int insertionSortThreshold, int initialBucketCapacity, int minBuckets, Class<Exception> expectedException) {
Executable executable = () -> new SpreadSort(insertionSortThreshold, initialBucketCapacity, minBuckets);
assertThrows(expectedException, executable);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java | src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java | package com.thealgorithms.sorts;
public class ExchangeSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new ExchangeSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java | src/test/java/com/thealgorithms/sorts/BitonicSortTest.java | package com.thealgorithms.sorts;
public class BitonicSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new BitonicSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/StoogeSortTest.java | src/test/java/com/thealgorithms/sorts/StoogeSortTest.java | package com.thealgorithms.sorts;
public class StoogeSortTest extends SortingAlgorithmTest {
protected int getGeneratedArraySize() {
return 1000;
}
@Override
SortAlgorithm getSortAlgorithm() {
return new StoogeSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java | src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.MethodSource;
public class MergeSortNoExtraSpaceTest {
record TestCase(int[] inputArray, int[] expectedArray) {
}
static Stream<TestCase> provideTestCases() {
return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {1}, new int[] {1}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}),
new TestCase(new int[] {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}, new int[] {1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9}), new TestCase(new int[] {4, 2, 4, 3, 2, 1, 5}, new int[] {1, 2, 2, 3, 4, 4, 5}), new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}),
new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {1, 2, 3, 1, 2, 3, 1, 2, 3}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 3}),
new TestCase(new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), new TestCase(new int[] {2, 1}, new int[] {1, 2}), new TestCase(new int[] {1, 3, 2}, new int[] {1, 2, 3}));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testCountingSort(TestCase testCase) {
int[] outputArray = MergeSortNoExtraSpace.sort(testCase.inputArray);
assertArrayEquals(testCase.expectedArray, outputArray);
}
@Test
public void testNegativeNumbers() {
int[] arrayWithNegatives = {1, -2, 3, -4};
assertThrows(IllegalArgumentException.class, () -> MergeSortNoExtraSpace.sort(arrayWithNegatives));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/MergeSortTest.java | src/test/java/com/thealgorithms/sorts/MergeSortTest.java | package com.thealgorithms.sorts;
public class MergeSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new MergeSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java | src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class MergeSortRecursiveTest {
// private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive();
@Test
void testMergeSortRecursiveCase1() {
MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88));
List<Integer> expected = Arrays.asList(3, 5, 9, 12, 15, 88);
List<Integer> sorted = mergeSortRecursive.mergeSort();
assertEquals(expected, sorted);
}
@Test
void testMergeSortRecursiveCase2() {
MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0));
List<Integer> expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40);
List<Integer> sorted = mergeSortRecursive.mergeSort();
assertEquals(expected, sorted);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/CycleSortTest.java | src/test/java/com/thealgorithms/sorts/CycleSortTest.java | package com.thealgorithms.sorts;
public class CycleSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new CycleSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/WaveSortTest.java | src/test/java/com/thealgorithms/sorts/WaveSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class WaveSortTest {
@ParameterizedTest
@MethodSource("arraysToWaveSort")
public void waveSortTest(Integer[] array) {
WaveSort waveSort = new WaveSort();
final var inputHistogram = getHistogram(array);
final var sortedArray = waveSort.sort(array);
assertTrue(waveSort.isWaveSorted(sortedArray));
final var sortedHistogram = getHistogram(sortedArray);
assertEquals(inputHistogram, sortedHistogram, "Element counts do not match");
}
private Map<Integer, Integer> getHistogram(Integer[] array) {
Map<Integer, Integer> histogram = new HashMap<>();
for (final var element : array) {
histogram.put(element, histogram.getOrDefault(element, 0) + 1);
}
return histogram;
}
private static Stream<Object[]> arraysToWaveSort() {
return Stream.of(new Object[] {new Integer[] {7, 7, 11, 3, 4, 5, 15}}, new Object[] {new Integer[] {1, 2, 3, 4, 5, 6, 7, 8}}, new Object[] {new Integer[] {8, 7, 6, 5, 4, 3, 2, 1}}, new Object[] {new Integer[] {3, 3, 3, 3}}, new Object[] {new Integer[] {-1, -3, -2, -4, -6, -5}},
new Object[] {new Integer[] {5, 3, 1, 2, 9, 7, 6, 8, 4, 0}}, new Object[] {new Integer[] {1}}, new Object[] {new Integer[] {2, 1}}, new Object[] {new Integer[] {1, 2}}, new Object[] {new Integer[] {}}, new Object[] {new Integer[] {0, 5, -3, 2, -1, 4, -2, 1, 3}});
}
@ParameterizedTest
@MethodSource("waveSortedArrays")
public <T extends Comparable<T>> void testIsWaveSorted(T[] array, boolean expected) {
final WaveSort waveSort = new WaveSort();
assertEquals(expected, waveSort.isWaveSorted(array));
}
public static Stream<Object[]> waveSortedArrays() {
return Stream.of(new Object[] {new Integer[] {3, 1, 4, 2, 5}, Boolean.TRUE}, new Object[] {new Integer[] {3, 1, 4, 2}, Boolean.TRUE}, new Object[] {new Integer[] {1, 3, 2, 4, 5}, Boolean.FALSE}, new Object[] {new Integer[] {4, 3, 5, 2, 3, 1, 2}, Boolean.TRUE},
new Object[] {new Integer[] {10, 90, 49, 2, 1, 5, 23}, Boolean.FALSE}, new Object[] {new Integer[] {}, Boolean.TRUE}, new Object[] {new Integer[] {1}, Boolean.TRUE}, new Object[] {new Integer[] {2, 1}, Boolean.TRUE}, new Object[] {new Integer[] {4, 3, 2, 5}, Boolean.FALSE},
new Object[] {new Double[] {4.0, 3.0, 5.1, 2.1, 3.3, 1.1, 2.2}, Boolean.TRUE}, new Object[] {new Double[] {10.1, 2.0, 2.0}, Boolean.TRUE}, new Object[] {new String[] {"a", "b", "c", "d"}, Boolean.FALSE}, new Object[] {new String[] {"b", "a", "b", "a", "b"}, Boolean.TRUE});
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java | src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java | package com.thealgorithms.sorts;
public class IntrospectiveSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new IntrospectiveSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java | src/test/java/com/thealgorithms/sorts/BubbleSortTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Objects;
import org.junit.jupiter.api.Test;
/**
* @author Aitor Fidalgo (https://github.com/aitorfi)
* @see BubbleSort
*/
public class BubbleSortTest {
private BubbleSort bubbleSort = new BubbleSort();
@Test
public void bubbleSortEmptyArray() {
Integer[] inputArray = {};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortSingleIntegerElementArray() {
Integer[] inputArray = {4};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {4};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortSingleStringElementArray() {
String[] inputArray = {"s"};
String[] outputArray = bubbleSort.sort(inputArray);
String[] expectedOutput = {"s"};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortIntegerArray() {
Integer[] inputArray = {4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {
-231,
-6,
-6,
1,
4,
9,
12,
23,
23,
54,
78,
};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortStringArray() {
String[] inputArray = {
"cbf",
"auk",
"ó",
"(b",
"a",
")",
"au",
"á",
"cba",
"auk",
"(a",
"bhy",
"cba",
};
String[] outputArray = bubbleSort.sort(inputArray);
String[] expectedOutput = {
"(a",
"(b",
")",
"a",
"au",
"auk",
"auk",
"bhy",
"cba",
"cba",
"cbf",
"á",
"ó",
};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortAlreadySortedArray() {
Integer[] inputArray = {-12, -6, -3, 0, 2, 2, 13, 46};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortReversedSortedArray() {
Integer[] inputArray = {46, 13, 2, 2, 0, -3, -6, -12};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {-12, -6, -3, 0, 2, 2, 13, 46};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortAllEqualArray() {
Integer[] inputArray = {2, 2, 2, 2, 2};
Integer[] outputArray = bubbleSort.sort(inputArray);
Integer[] expectedOutput = {2, 2, 2, 2, 2};
assertArrayEquals(outputArray, expectedOutput);
}
@Test
public void bubbleSortMixedCaseStrings() {
String[] inputArray = {"banana", "Apple", "apple", "Banana"};
String[] expectedOutput = {"Apple", "Banana", "apple", "banana"};
String[] outputArray = bubbleSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
/**
* Custom Comparable class for testing.
**/
static class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(this.age, o.age);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
@Test
public void bubbleSortCustomObjects() {
Person[] inputArray = {
new Person("Alice", 32),
new Person("Bob", 25),
new Person("Charlie", 28),
};
Person[] expectedOutput = {
new Person("Bob", 25),
new Person("Charlie", 28),
new Person("Alice", 32),
};
Person[] outputArray = bubbleSort.sort(inputArray);
assertArrayEquals(expectedOutput, outputArray);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java | src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java | package com.thealgorithms.sorts;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
public abstract class SortingAlgorithmTest {
abstract SortAlgorithm getSortAlgorithm();
protected int getGeneratedArraySize() {
return 10_000;
}
@Test
void shouldAcceptWhenEmptyArrayIsPassed() {
Integer[] array = new Integer[] {};
Integer[] expected = new Integer[] {};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenEmptyListIsPassed() {
List<Integer> list = new ArrayList<>();
List<Integer> expected = new ArrayList<>();
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenSingleValuedArrayIsPassed() {
Integer[] array = new Integer[] {2};
Integer[] expected = new Integer[] {2};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenSingleValuedListIsPassed() {
List<Integer> list = List.of(2);
List<Integer> expected = List.of(2);
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenListWithAllPositiveValuesIsPassed() {
Integer[] array = new Integer[] {60, 7, 55, 9, 999, 3};
Integer[] expected = new Integer[] {3, 7, 9, 55, 60, 999};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenArrayWithAllPositiveValuesIsPassed() {
List<Integer> list = List.of(60, 7, 55, 9, 999, 3);
List<Integer> expected = List.of(3, 7, 9, 55, 60, 999);
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenArrayWithAllNegativeValuesIsPassed() {
Integer[] array = new Integer[] {-60, -7, -55, -9, -999, -3};
Integer[] expected = new Integer[] {-999, -60, -55, -9, -7, -3};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenListWithAllNegativeValuesIsPassed() {
List<Integer> list = List.of(-60, -7, -55, -9, -999, -3);
List<Integer> expected = List.of(-999, -60, -55, -9, -7, -3);
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenArrayWithRealNumberValuesIsPassed() {
Integer[] array = new Integer[] {60, -7, 55, 9, -999, -3};
Integer[] expected = new Integer[] {-999, -7, -3, 9, 55, 60};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenListWithRealNumberValuesIsPassed() {
List<Integer> list = List.of(60, -7, 55, 9, -999, -3);
List<Integer> expected = List.of(-999, -7, -3, 9, 55, 60);
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenArrayWithDuplicateValueIsPassed() {
Integer[] array = new Integer[] {60, 7, 55, 55, 999, 3};
Integer[] expected = new Integer[] {3, 7, 55, 55, 60, 999};
Integer[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenListWithDuplicateValueIsPassed() {
List<Integer> list = List.of(60, 7, 55, 55, 999, 3);
List<Integer> expected = List.of(3, 7, 55, 55, 60, 999);
List<Integer> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenStringValueArrayIsPassed() {
String[] array = {"z", "a", "x", "b", "y"};
String[] expected = {"a", "b", "x", "y", "z"};
String[] sorted = getSortAlgorithm().sort(array);
assertArrayEquals(expected, sorted);
}
@Test
void shouldAcceptWhenStringValueListIsPassed() {
List<String> list = List.of("z", "a", "x", "b", "y");
List<String> expected = List.of("a", "b", "x", "y", "z");
List<String> sorted = getSortAlgorithm().sort(list);
assertIterableEquals(expected, sorted);
}
@Test
void shouldAcceptWhenRandomArrayIsPassed() {
int randomSize = SortUtilsRandomGenerator.generateInt(getGeneratedArraySize());
Double[] array = SortUtilsRandomGenerator.generateArray(randomSize);
Double[] sorted = getSortAlgorithm().sort(array);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
void shouldAcceptWhenRandomListIsPassed() {
int randomSize = SortUtilsRandomGenerator.generateInt(getGeneratedArraySize());
Double[] array = SortUtilsRandomGenerator.generateArray(randomSize);
List<Double> list = List.of(array);
List<Double> sorted = getSortAlgorithm().sort(list);
assertTrue(SortUtils.isSorted(sorted));
}
@Test
public void shouldAcceptWhenArrayWithAllIdenticalValuesIsPassed() {
Integer[] array = {1, 1, 1, 1};
Integer[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Integer[] {1, 1, 1, 1}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithAllIdenticalValuesIsPassed() {
List<Integer> list = Arrays.asList(1, 1, 1, 1);
List<Integer> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(1, 1, 1, 1), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithMixedPositiveAndNegativeValuesIsPassed() {
Integer[] array = {-1, 3, -2, 5, 0};
Integer[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Integer[] {-2, -1, 0, 3, 5}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithMixedPositiveAndNegativeValuesIsPassed() {
List<Integer> list = Arrays.asList(-1, 3, -2, 5, 0);
List<Integer> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(-2, -1, 0, 3, 5), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithLargeNumbersIsPassed() {
Long[] array = {10000000000L, 9999999999L, 10000000001L};
Long[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Long[] {9999999999L, 10000000000L, 10000000001L}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithLargeNumbersIsPassed() {
List<Long> list = Arrays.asList(10000000000L, 9999999999L, 10000000001L);
List<Long> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(9999999999L, 10000000000L, 10000000001L), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithMaxIntegerValuesIsPassed() {
Integer[] array = {Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
Integer[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Integer[] {Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithMaxIntegerValuesIsPassed() {
List<Integer> list = Arrays.asList(Integer.MAX_VALUE, Integer.MIN_VALUE, 0);
List<Integer> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(Integer.MIN_VALUE, 0, Integer.MAX_VALUE), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithMinIntegerValuesIsPassed() {
Integer[] array = {Integer.MIN_VALUE, Integer.MAX_VALUE, 0};
Integer[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Integer[] {Integer.MIN_VALUE, 0, Integer.MAX_VALUE}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithMinIntegerValuesIsPassed() {
List<Integer> list = Arrays.asList(Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
List<Integer> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(Integer.MIN_VALUE, 0, Integer.MAX_VALUE), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithSpecialCharactersIsPassed() {
String[] array = {"!", "@", "#", "$"};
String[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new String[] {"!", "#", "$", "@"}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithSpecialCharactersIsPassed() {
List<String> list = Arrays.asList("!", "@", "#", "$");
List<String> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList("!", "#", "$", "@"), sortedList);
}
@Test
public void shouldAcceptWhenArrayWithMixedCaseStringsIsPassed() {
String[] array = {"apple", "Banana", "cherry", "Date"};
String[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new String[] {"Banana", "Date", "apple", "cherry"}, sortedArray);
}
@Test
public void shouldAcceptWhenListWithMixedCaseStringsIsPassed() {
List<String> list = Arrays.asList("apple", "Banana", "cherry", "Date");
List<String> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList("Banana", "Date", "apple", "cherry"), sortedList);
}
@Test
public void shouldHandleArrayWithNullValues() {
Integer[] array = {3, null, 2, null, 1};
org.junit.jupiter.api.Assertions.assertThrows(NullPointerException.class, () -> getSortAlgorithm().sort(array));
}
@Test
public void shouldHandleListWithNullValues() {
List<Integer> list = Arrays.asList(3, null, 2, null, 1);
org.junit.jupiter.api.Assertions.assertThrows(NullPointerException.class, () -> getSortAlgorithm().sort(list));
}
static class CustomObject implements Comparable<CustomObject> {
int value;
CustomObject(int value) {
this.value = value;
}
@Override
public int compareTo(CustomObject o) {
return Integer.compare(this.value, o.value);
}
@Override
public String toString() {
return "CustomObject{"
+ "value=" + value + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CustomObject that = (CustomObject) o;
return value == that.value;
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
}
@Test
public void shouldHandleArrayOfCustomObjects() {
CustomObject[] array = {new CustomObject(3), new CustomObject(1), new CustomObject(2)};
CustomObject[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new CustomObject[] {new CustomObject(1), new CustomObject(2), new CustomObject(3)}, sortedArray);
}
@Test
public void shouldHandleListOfCustomObjects() {
List<CustomObject> list = Arrays.asList(new CustomObject(3), new CustomObject(1), new CustomObject(2));
List<CustomObject> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(new CustomObject(1), new CustomObject(2), new CustomObject(3)), sortedList);
}
@Test
public void shouldHandleArrayOfFloatingPointNumbers() {
Double[] array = {3.3, 2.2, 1.1, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY};
Double[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new Double[] {Double.NEGATIVE_INFINITY, 1.1, 2.2, 3.3, Double.POSITIVE_INFINITY, Double.NaN}, sortedArray);
}
@Test
public void shouldHandleListOfFloatingPointNumbers() {
List<Double> list = Arrays.asList(3.3, 2.2, 1.1, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
List<Double> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList(Double.NEGATIVE_INFINITY, 1.1, 2.2, 3.3, Double.POSITIVE_INFINITY, Double.NaN), sortedList);
}
@Test
public void shouldHandleArrayWithEmptyStrings() {
String[] array = {"apple", "", "banana", ""};
String[] sortedArray = getSortAlgorithm().sort(array);
assertArrayEquals(new String[] {"", "", "apple", "banana"}, sortedArray);
}
@Test
public void shouldHandleListWithEmptyStrings() {
List<String> list = Arrays.asList("apple", "", "banana", "");
List<String> sortedList = getSortAlgorithm().sort(list);
assertEquals(Arrays.asList("", "", "apple", "banana"), sortedList);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java | src/test/java/com/thealgorithms/lineclipping/LiangBarskyTest.java | package com.thealgorithms.lineclipping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.thealgorithms.lineclipping.utils.Line;
import com.thealgorithms.lineclipping.utils.Point;
import org.junit.jupiter.api.Test;
/**
* @author shikarisohan
* @since 10/5/24
*/
class LiangBarskyTest {
LiangBarsky lb = new LiangBarsky(1.0, 1.0, 10.0, 10.0);
@Test
void testLineCompletelyInside() {
Line line = new Line(new Point(2.0, 2.0), new Point(8.0, 8.0));
Line clippedLine = lb.liangBarskyClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(line, clippedLine, "Line inside the window should remain unchanged.");
}
@Test
void testLineCompletelyOutside() {
Line line = new Line(new Point(12.0, 12.0), new Point(15.0, 18.0));
Line clippedLine = lb.liangBarskyClip(line);
assertNull(clippedLine, "Line should be null because it's completely outside.");
}
@Test
void testLinePartiallyInside() {
Line line = new Line(new Point(5.0, 5.0), new Point(12.0, 12.0));
Line expectedClippedLine = new Line(new Point(5.0, 5.0), new Point(10.0, 10.0)); // Clipped at (10, 10)
Line clippedLine = lb.liangBarskyClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Line should be clipped correctly.");
}
@Test
void testDiagonalLineThroughClippingWindow() {
Line line = new Line(new Point(0.0, 0.0), new Point(12.0, 12.0));
Line expectedClippedLine = new Line(new Point(1.0, 1.0), new Point(10.0, 10.0)); // Clipped at both boundaries
Line clippedLine = lb.liangBarskyClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Diagonal line should be clipped correctly.");
}
@Test
void testVerticalLineClipping() {
Line line = new Line(new Point(5.0, 0.0), new Point(5.0, 12.0));
Line expectedClippedLine = new Line(new Point(5.0, 1.0), new Point(5.0, 10.0)); // Clipped at yMin and yMax
Line clippedLine = lb.liangBarskyClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Vertical line should be clipped correctly.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java | src/test/java/com/thealgorithms/lineclipping/CohenSutherlandTest.java | package com.thealgorithms.lineclipping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.thealgorithms.lineclipping.utils.Line;
import com.thealgorithms.lineclipping.utils.Point;
import org.junit.jupiter.api.Test;
/**
* @author shikarisohan
* @since 10/4/24
*/
class CohenSutherlandTest {
// Define the clipping window (1.0, 1.0) to (10.0, 10.0)
CohenSutherland cs = new CohenSutherland(1.0, 1.0, 10.0, 10.0);
@Test
void testLineCompletelyInside() {
// Line fully inside the clipping window
Line line = new Line(new Point(2.0, 2.0), new Point(8.0, 8.0));
Line clippedLine = cs.cohenSutherlandClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(line, clippedLine, "Line inside the window should remain unchanged.");
}
@Test
void testLineCompletelyOutside() {
// Line completely outside and above the clipping window
Line line = new Line(new Point(11.0, 12.0), new Point(15.0, 18.0));
Line clippedLine = cs.cohenSutherlandClip(line);
assertNull(clippedLine, "Line should be null because it's completely outside.");
}
@Test
void testLinePartiallyInside() {
// Line partially inside the clipping window
Line line = new Line(new Point(5.0, 5.0), new Point(12.0, 12.0));
Line expectedClippedLine = new Line(new Point(5.0, 5.0), new Point(10.0, 10.0)); // Clipped at (10, 10)
Line clippedLine = cs.cohenSutherlandClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Line should be clipped correctly.");
}
@Test
void testLineOnBoundary() {
// Line exactly on the boundary of the clipping window
Line line = new Line(new Point(1.0, 5.0), new Point(10.0, 5.0));
Line clippedLine = cs.cohenSutherlandClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(line, clippedLine, "Line on the boundary should remain unchanged.");
}
@Test
void testDiagonalLineThroughClippingWindow() {
// Diagonal line crossing from outside to outside through the window
Line line = new Line(new Point(0.0, 0.0), new Point(12.0, 12.0));
Line expectedClippedLine = new Line(new Point(1.0, 1.0), new Point(10.0, 10.0)); // Clipped at both boundaries
Line clippedLine = cs.cohenSutherlandClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Diagonal line should be clipped correctly.");
}
@Test
void testVerticalLineClipping() {
// Vertical line crossing the top and bottom of the clipping window
Line line = new Line(new Point(5.0, 0.0), new Point(5.0, 12.0));
Line expectedClippedLine = new Line(new Point(5.0, 1.0), new Point(5.0, 10.0)); // Clipped at yMin and yMax
Line clippedLine = cs.cohenSutherlandClip(line);
assertNotNull(clippedLine, "Line should not be null.");
assertEquals(expectedClippedLine, clippedLine, "Vertical line should be clipped correctly.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/devutils/entities/ProcessDetailsTest.java | src/test/java/com/thealgorithms/devutils/entities/ProcessDetailsTest.java | package com.thealgorithms.devutils.entities;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test class for ProcessDetails
* Tests the ProcessDetails entity used in scheduling algorithms
*
* @author Sourav Saha (yashsaha555)
*/
class ProcessDetailsTest {
private ProcessDetails processWithPriority;
private ProcessDetails processWithoutPriority;
@BeforeEach
void setUp() {
// Initialize test objects before each test
processWithPriority = new ProcessDetails("P1", 0, 10, 5);
processWithoutPriority = new ProcessDetails("P2", 2, 8);
}
@Test
void testConstructorWithPriority() {
// Test constructor with priority parameter
ProcessDetails process = new ProcessDetails("P3", 1, 15, 3);
assertEquals("P3", process.getProcessId());
assertEquals(1, process.getArrivalTime());
assertEquals(15, process.getBurstTime());
assertEquals(3, process.getPriority());
assertEquals(0, process.getWaitingTime()); // Default value
assertEquals(0, process.getTurnAroundTimeTime()); // Default value
}
@Test
void testConstructorWithoutPriority() {
// Test constructor without priority parameter
ProcessDetails process = new ProcessDetails("P4", 3, 12);
assertEquals("P4", process.getProcessId());
assertEquals(3, process.getArrivalTime());
assertEquals(12, process.getBurstTime());
assertEquals(0, process.getPriority()); // Default value
assertEquals(0, process.getWaitingTime()); // Default value
assertEquals(0, process.getTurnAroundTimeTime()); // Default value
}
@Test
void testGetProcessId() {
assertEquals("P1", processWithPriority.getProcessId());
assertEquals("P2", processWithoutPriority.getProcessId());
}
@Test
void testGetArrivalTime() {
assertEquals(0, processWithPriority.getArrivalTime());
assertEquals(2, processWithoutPriority.getArrivalTime());
}
@Test
void testGetBurstTime() {
assertEquals(10, processWithPriority.getBurstTime());
assertEquals(8, processWithoutPriority.getBurstTime());
}
@Test
void testGetWaitingTime() {
// Initial waiting time should be 0
assertEquals(0, processWithPriority.getWaitingTime());
assertEquals(0, processWithoutPriority.getWaitingTime());
}
@Test
void testGetTurnAroundTimeTime() {
// Initial turnaround time should be 0
assertEquals(0, processWithPriority.getTurnAroundTimeTime());
assertEquals(0, processWithoutPriority.getTurnAroundTimeTime());
}
@Test
void testGetPriority() {
assertEquals(5, processWithPriority.getPriority());
assertEquals(0, processWithoutPriority.getPriority()); // Default for constructor without priority
}
@Test
void testSetProcessId() {
processWithPriority.setProcessId("NewP1");
assertEquals("NewP1", processWithPriority.getProcessId());
// Test setting null process ID
processWithPriority.setProcessId(null);
assertNull(processWithPriority.getProcessId());
// Test setting empty process ID
processWithPriority.setProcessId("");
assertEquals("", processWithPriority.getProcessId());
}
@Test
void testSetArrivalTime() {
processWithPriority.setArrivalTime(5);
assertEquals(5, processWithPriority.getArrivalTime());
// Test setting negative arrival time
processWithPriority.setArrivalTime(-1);
assertEquals(-1, processWithPriority.getArrivalTime());
// Test setting zero arrival time
processWithPriority.setArrivalTime(0);
assertEquals(0, processWithPriority.getArrivalTime());
}
@Test
void testSetBurstTime() {
processWithPriority.setBurstTime(20);
assertEquals(20, processWithPriority.getBurstTime());
// Test setting zero burst time
processWithPriority.setBurstTime(0);
assertEquals(0, processWithPriority.getBurstTime());
// Test setting very large burst time
processWithPriority.setBurstTime(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, processWithPriority.getBurstTime());
}
@Test
void testSetWaitingTime() {
processWithPriority.setWaitingTime(15);
assertEquals(15, processWithPriority.getWaitingTime());
// Test setting negative waiting time
processWithPriority.setWaitingTime(-5);
assertEquals(-5, processWithPriority.getWaitingTime());
// Test setting zero waiting time
processWithPriority.setWaitingTime(0);
assertEquals(0, processWithPriority.getWaitingTime());
}
@Test
void testSetTurnAroundTimeTime() {
processWithPriority.setTurnAroundTimeTime(25);
assertEquals(25, processWithPriority.getTurnAroundTimeTime());
// Test setting negative turnaround time
processWithPriority.setTurnAroundTimeTime(-10);
assertEquals(-10, processWithPriority.getTurnAroundTimeTime());
// Test setting zero turnaround time
processWithPriority.setTurnAroundTimeTime(0);
assertEquals(0, processWithPriority.getTurnAroundTimeTime());
}
@Test
void testCompleteProcessLifecycle() {
// Test a complete process lifecycle with realistic scheduling values
ProcessDetails process = new ProcessDetails("P5", 0, 10, 2);
// Simulate process execution
process.setWaitingTime(5); // Process waited 5 time units
process.setTurnAroundTimeTime(15); // Total time from arrival to completion
assertEquals("P5", process.getProcessId());
assertEquals(0, process.getArrivalTime());
assertEquals(10, process.getBurstTime());
assertEquals(5, process.getWaitingTime());
assertEquals(15, process.getTurnAroundTimeTime());
assertEquals(2, process.getPriority());
}
@Test
void testProcessWithMinimumValues() {
// Test process with minimum possible values
ProcessDetails process = new ProcessDetails("", 0, 1, 0);
assertEquals("", process.getProcessId());
assertEquals(0, process.getArrivalTime());
assertEquals(1, process.getBurstTime());
assertEquals(0, process.getPriority());
}
@Test
void testProcessWithMaximumValues() {
// Test process with large values
ProcessDetails process = new ProcessDetails("LongProcessName", Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
assertEquals("LongProcessName", process.getProcessId());
assertEquals(Integer.MAX_VALUE, process.getArrivalTime());
assertEquals(Integer.MAX_VALUE, process.getBurstTime());
assertEquals(Integer.MAX_VALUE, process.getPriority());
}
@Test
void testProcessModificationAfterCreation() {
// Test that all fields can be modified after object creation
ProcessDetails process = new ProcessDetails("Original", 1, 5, 3);
// Modify all fields
process.setProcessId("Modified");
process.setArrivalTime(10);
process.setBurstTime(20);
process.setWaitingTime(8);
process.setTurnAroundTimeTime(28);
// Verify all modifications
assertEquals("Modified", process.getProcessId());
assertEquals(10, process.getArrivalTime());
assertEquals(20, process.getBurstTime());
assertEquals(8, process.getWaitingTime());
assertEquals(28, process.getTurnAroundTimeTime());
assertEquals(3, process.getPriority()); // Priority has no setter, should remain unchanged
}
@Test
void testMultipleProcessesIndependence() {
// Test that multiple ProcessDetails objects are independent
ProcessDetails process1 = new ProcessDetails("P1", 0, 5, 1);
ProcessDetails process2 = new ProcessDetails("P2", 2, 8, 2);
// Modify first process
process1.setWaitingTime(10);
process1.setTurnAroundTimeTime(15);
// Verify first process was modified correctly
assertEquals("P1", process1.getProcessId());
assertEquals(0, process1.getArrivalTime());
assertEquals(5, process1.getBurstTime());
assertEquals(1, process1.getPriority());
assertEquals(10, process1.getWaitingTime());
assertEquals(15, process1.getTurnAroundTimeTime());
// Verify second process is unchanged
assertEquals("P2", process2.getProcessId());
assertEquals(2, process2.getArrivalTime());
assertEquals(8, process2.getBurstTime());
assertEquals(2, process2.getPriority());
assertEquals(0, process2.getWaitingTime());
assertEquals(0, process2.getTurnAroundTimeTime());
}
@Test
void testConstructorParameterOrder() {
// Test that constructor parameters are assigned to correct fields
ProcessDetails process = new ProcessDetails("TestProcess", 123, 456, 789);
assertEquals("TestProcess", process.getProcessId());
assertEquals(123, process.getArrivalTime());
assertEquals(456, process.getBurstTime());
assertEquals(789, process.getPriority());
}
@Test
void testTypicalSchedulingScenario() {
// Test a typical scheduling scenario with multiple processes
ProcessDetails[] processes = {new ProcessDetails("P1", 0, 8, 3), new ProcessDetails("P2", 1, 4, 1), new ProcessDetails("P3", 2, 9, 4), new ProcessDetails("P4", 3, 5, 2)};
// Simulate FCFS scheduling calculations
int currentTime = 0;
for (ProcessDetails process : processes) {
if (currentTime < process.getArrivalTime()) {
currentTime = process.getArrivalTime();
}
process.setWaitingTime(currentTime - process.getArrivalTime());
currentTime += process.getBurstTime();
process.setTurnAroundTimeTime(process.getWaitingTime() + process.getBurstTime());
}
// Verify calculations
assertEquals(0, processes[0].getWaitingTime()); // P1: arrives at 0, starts immediately
assertEquals(8, processes[0].getTurnAroundTimeTime()); // P1: 0 + 8
assertEquals(7, processes[1].getWaitingTime()); // P2: arrives at 1, starts at 8
assertEquals(11, processes[1].getTurnAroundTimeTime()); // P2: 7 + 4
assertEquals(10, processes[2].getWaitingTime()); // P3: arrives at 2, starts at 12
assertEquals(19, processes[2].getTurnAroundTimeTime()); // P3: 10 + 9
assertEquals(18, processes[3].getWaitingTime()); // P4: arrives at 3, starts at 21
assertEquals(23, processes[3].getTurnAroundTimeTime()); // P4: 18 + 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/puzzlesandgames/WordBoggleTest.java | src/test/java/com/thealgorithms/puzzlesandgames/WordBoggleTest.java | package com.thealgorithms.puzzlesandgames;
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 java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class WordBoggleTest {
private char[][] board;
@BeforeEach
void setup() {
board = new char[][] {
{'t', 'h', 'i', 's', 'i', 's', 'a'},
{'s', 'i', 'm', 'p', 'l', 'e', 'x'},
{'b', 'x', 'x', 'x', 'x', 'e', 'b'},
{'x', 'o', 'g', 'g', 'l', 'x', 'o'},
{'x', 'x', 'x', 'D', 'T', 'r', 'a'},
{'R', 'E', 'P', 'E', 'A', 'd', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x', 'x'},
{'N', 'O', 'T', 'R', 'E', '_', 'P'},
{'x', 'x', 'D', 'E', 'T', 'A', 'E'},
};
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testBoggleBoard(String[] words, List<String> expectedWords, String testDescription) {
List<String> result = WordBoggle.boggleBoard(board, words);
assertEquals(expectedWords.size(), result.size(), "Test failed for: " + testDescription);
assertTrue(expectedWords.containsAll(result), "Test failed for: " + testDescription);
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new String[] {"this", "is", "not", "a", "simple", "test", "boggle", "board", "REPEATED", "NOTRE_PEATED"}, Arrays.asList("this", "is", "a", "simple", "board", "boggle", "NOTRE_PEATED"), "All words"),
Arguments.of(new String[] {"xyz", "hello", "world"}, List.of(), "No matching words"), Arguments.of(new String[] {}, List.of(), "Empty words array"), Arguments.of(new String[] {"this", "this", "board", "board"}, Arrays.asList("this", "board"), "Duplicate words in input"));
}
@ParameterizedTest
@MethodSource("provideSpecialCases")
void testBoggleBoardSpecialCases(char[][] specialBoard, String[] words, Collection<String> expectedWords, String testDescription) {
List<String> result = WordBoggle.boggleBoard(specialBoard, words);
assertEquals(expectedWords.size(), result.size(), "Test failed for: " + testDescription);
assertTrue(expectedWords.containsAll(result), "Test failed for: " + testDescription);
}
private static Stream<Arguments> provideSpecialCases() {
return Stream.of(Arguments.of(new char[0][0], new String[] {"this", "is", "a", "test"}, List.of(), "Empty board"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/puzzlesandgames/TowerOfHanoiTest.java | src/test/java/com/thealgorithms/puzzlesandgames/TowerOfHanoiTest.java | package com.thealgorithms.puzzlesandgames;
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;
public class TowerOfHanoiTest {
@Test
public void testHanoiWithOneDisc() {
List<String> result = new ArrayList<>();
TowerOfHanoi.shift(1, "Pole1", "Pole2", "Pole3", result);
// Expected output for 1 disc
List<String> expected = List.of("Move 1 from Pole1 to Pole3");
assertEquals(expected, result);
}
@Test
public void testHanoiWithTwoDiscs() {
List<String> result = new ArrayList<>();
TowerOfHanoi.shift(2, "Pole1", "Pole2", "Pole3", result);
// Expected output for 2 discs
List<String> expected = List.of("Move 1 from Pole1 to Pole2", "Move 2 from Pole1 to Pole3", "Move 1 from Pole2 to Pole3");
assertEquals(expected, result);
}
@Test
public void testHanoiWithThreeDiscs() {
List<String> result = new ArrayList<>();
TowerOfHanoi.shift(3, "Pole1", "Pole2", "Pole3", result);
// Expected output for 3 discs
List<String> expected = List.of("Move 1 from Pole1 to Pole3", "Move 2 from Pole1 to Pole2", "Move 1 from Pole3 to Pole2", "Move 3 from Pole1 to Pole3", "Move 1 from Pole2 to Pole1", "Move 2 from Pole2 to Pole3", "Move 1 from Pole1 to Pole3");
assertEquals(expected, result);
}
@Test
public void testHanoiWithZeroDiscs() {
List<String> result = new ArrayList<>();
TowerOfHanoi.shift(0, "Pole1", "Pole2", "Pole3", result);
// There should be no moves if there are 0 discs
assertTrue(result.isEmpty());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisationTest.java | src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisationTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class MatrixChainRecursiveTopDownMemoisationTest {
/**
* Test case for four matrices with dimensions 1x2, 2x3, 3x4, and 4x5.
* The expected minimum number of multiplications is 38.
*/
@Test
void testFourMatrices() {
int[] dimensions = {1, 2, 3, 4, 5};
int expected = 38;
int actual = MatrixChainRecursiveTopDownMemoisation.memoizedMatrixChain(dimensions);
assertEquals(expected, actual, "The minimum number of multiplications should be 38.");
}
/**
* Test case for three matrices with dimensions 10x20, 20x30, and 30x40.
* The expected minimum number of multiplications is 6000.
*/
@Test
void testThreeMatrices() {
int[] dimensions = {10, 20, 30, 40};
int expected = 18000;
int actual = MatrixChainRecursiveTopDownMemoisation.memoizedMatrixChain(dimensions);
assertEquals(expected, actual, "The minimum number of multiplications should be 18000.");
}
/**
* Test case for two matrices with dimensions 5x10 and 10x20.
* The expected minimum number of multiplications is 1000.
*/
@Test
void testTwoMatrices() {
int[] dimensions = {5, 10, 20};
int expected = 1000;
int actual = MatrixChainRecursiveTopDownMemoisation.memoizedMatrixChain(dimensions);
assertEquals(expected, actual, "The minimum number of multiplications should be 1000.");
}
/**
* Test case for a single matrix.
* The expected minimum number of multiplications is 0, as there are no multiplications needed.
*/
@Test
void testSingleMatrix() {
int[] dimensions = {10, 20}; // Single matrix dimensions
int expected = 0;
int actual = MatrixChainRecursiveTopDownMemoisation.memoizedMatrixChain(dimensions);
assertEquals(expected, actual, "The minimum number of multiplications should be 0.");
}
/**
* Test case for matrices with varying dimensions.
* The expected minimum number of multiplications is calculated based on the dimensions provided.
*/
@Test
void testVaryingDimensions() {
int[] dimensions = {2, 3, 4, 5, 6}; // Dimensions for 4 matrices
int expected = 124; // Expected value needs to be calculated based on the problem
int actual = MatrixChainRecursiveTopDownMemoisation.memoizedMatrixChain(dimensions);
assertEquals(expected, actual, "The minimum number of multiplications should be 124.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* @author georgioct@csd.auth.gr
*/
public class OptimalJobSchedulingTest {
@Test
public void testOptimalJobScheduling1() {
int numberProcesses = 5;
int numberMachines = 4;
int[][] run = {{5, 1, 3, 2}, {4, 2, 1, 3}, {1, 5, 2, 1}, {2, 3, 4, 2}, {1, 1, 3, 1}};
int[][] transfer = {{0, 1, 2, 4}, {1, 0, 2, 3}, {2, 2, 0, 1}, {4, 3, 1, 0}};
OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 5}, {5, 8, 6, 6}, {7, 9, 10, 8}, {8, 9, 12, 9}};
for (int i = 0; i < numberProcesses; i++) {
for (int j = 0; j < numberMachines; j++) {
assertEquals(costs[i][j], opt.getCost(i, j));
}
}
}
@Test
public void testOptimalJobScheduling2() {
int numberProcesses = 3;
int numberMachines = 3;
int[][] run = {{5, 1, 3}, {4, 2, 1}, {1, 5, 2}};
int[][] transfer = {{0, 1, 2}, {1, 0, 2}, {2, 2, 0}};
OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
int[][] costs = {{5, 1, 3}, {6, 3, 4}, {5, 8, 6}};
for (int i = 0; i < numberProcesses; i++) {
for (int j = 0; j < numberMachines; j++) {
assertEquals(costs[i][j], opt.getCost(i, j));
}
}
}
@Test
public void testOptimalJobScheduling3() {
int numberProcesses = 6;
int numberMachines = 4;
int[][] run = {
{5, 1, 3, 2},
{4, 2, 1, 1},
{1, 5, 2, 6},
{1, 1, 2, 3},
{2, 1, 4, 6},
{3, 2, 2, 3},
};
int[][] transfer = {
{0, 1, 2, 1},
{1, 0, 2, 3},
{2, 2, 0, 2},
{1, 3, 2, 0},
};
OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 3}, {5, 8, 6, 9}, {6, 7, 8, 9}, {8, 8, 12, 13}, {11, 10, 12, 12}};
for (int i = 0; i < numberProcesses; i++) {
for (int j = 0; j < numberMachines; j++) {
assertEquals(costs[i][j], opt.getCost(i, j));
}
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/SmithWatermanTest.java | src/test/java/com/thealgorithms/dynamicprogramming/SmithWatermanTest.java | package com.thealgorithms.dynamicprogramming;
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;
/**
* Unit tests for the {@code SmithWaterman} class.
*/
class SmithWatermanTest {
@Test
void testIdenticalStrings() {
int score = SmithWaterman.align("GATTACA", "GATTACA", 2, -1, -2);
assertEquals(14, score); // full match, 7*2
}
@Test
void testPartialMatch() {
int score = SmithWaterman.align("GATTACA", "TTAC", 2, -1, -2);
assertEquals(8, score); // best local alignment "TTAC"
}
@Test
void testNoMatch() {
int score = SmithWaterman.align("AAAA", "TTTT", 1, -1, -2);
assertEquals(0, score); // no alignment worth keeping
}
@Test
void testInsertionDeletion() {
int score = SmithWaterman.align("ACGT", "ACGGT", 1, -1, -2);
assertEquals(3, score); // local alignment "ACG"
}
@Test
void testEmptyStrings() {
assertEquals(0, SmithWaterman.align("", "", 1, -1, -2));
}
@ParameterizedTest
@CsvSource({"null,ABC", "ABC,null", "null,null"})
void testNullInputs(String s1, String s2) {
String first = "null".equals(s1) ? null : s1;
String second = "null".equals(s2) ? null : s2;
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> SmithWaterman.align(first, second, 1, -1, -2));
assertEquals("Input strings must not be null.", ex.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/dynamicprogramming/KnapsackZeroOneTest.java | src/test/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class KnapsackZeroOneTest {
@Test
void basicCheck() {
int[] values = {60, 100, 120};
int[] weights = {10, 20, 30};
int capacity = 50;
int expected = 220;
int result = KnapsackZeroOne.compute(values, weights, capacity, values.length);
assertEquals(expected, result);
}
@Test
void zeroCapacity() {
int[] values = {10, 20, 30};
int[] weights = {1, 1, 1};
int capacity = 0;
int result = KnapsackZeroOne.compute(values, weights, capacity, values.length);
assertEquals(0, result);
}
@Test
void zeroItems() {
int[] values = {};
int[] weights = {};
int capacity = 10;
int result = KnapsackZeroOne.compute(values, weights, capacity, 0);
assertEquals(0, result);
}
@Test
void weightsExceedingCapacity() {
int[] values = {10, 20};
int[] weights = {100, 200};
int capacity = 50;
int result = KnapsackZeroOne.compute(values, weights, capacity, values.length);
assertEquals(0, result);
}
@Test
void throwsOnNullArrays() {
assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOne.compute(null, new int[] {1}, 10, 1));
assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOne.compute(new int[] {1}, null, 10, 1));
}
@Test
void throwsOnMismatchedArrayLengths() {
assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOne.compute(new int[] {10, 20}, new int[] {5}, 15, 2));
}
@Test
void throwsOnNegativeInputs() {
assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOne.compute(new int[] {10}, new int[] {5}, -1, 1));
assertThrows(IllegalArgumentException.class, () -> KnapsackZeroOne.compute(new int[] {10}, new int[] {5}, 5, -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/dynamicprogramming/CoinChangeTest.java | src/test/java/com/thealgorithms/dynamicprogramming/CoinChangeTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CoinChangeTest {
@Test
void testChangeBasic() {
int amount = 12;
int[] coins = {2, 4, 5};
assertEquals(5, CoinChange.change(coins, amount));
}
@Test
void testChangeNoCoins() {
int amount = 12;
int[] coins = {};
assertEquals(0, CoinChange.change(coins, amount));
}
@Test
void testChangeNoAmount() {
int amount = 0;
int[] coins = {2, 4, 5};
assertEquals(1, CoinChange.change(coins, amount));
}
@Test
void testChangeImpossibleAmount() {
int amount = 3;
int[] coins = {2, 4, 5};
assertEquals(0, CoinChange.change(coins, amount));
}
@Test
void testMinimumCoinsBasic() {
int amount = 12;
int[] coins = {2, 4, 5};
assertEquals(3, CoinChange.minimumCoins(coins, amount));
}
@Test
void testMinimumCoinsNoCoins() {
int amount = 12;
int[] coins = {};
assertEquals(Integer.MAX_VALUE, CoinChange.minimumCoins(coins, amount));
}
@Test
void testMinimumCoinsNoAmount() {
int amount = 0;
int[] coins = {2, 4, 5};
assertEquals(0, CoinChange.minimumCoins(coins, amount));
}
@Test
void testMinimumCoinsImpossibleAmount() {
int amount = 3;
int[] coins = {2, 4, 5};
assertEquals(Integer.MAX_VALUE, CoinChange.minimumCoins(coins, amount));
}
@Test
void testMinimumCoinsExactAmount() {
int amount = 10;
int[] coins = {1, 5, 10};
assertEquals(1, CoinChange.minimumCoins(coins, amount));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java | src/test/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithmTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class KadaneAlgorithmTest {
@Test
void testMaxSumWithPositiveValues() {
// Test with all positive numbers
int[] input = {89, 56, 98, 123, 26, 75, 12, 40, 39, 68, 91};
int expectedMaxSum = 89 + 56 + 98 + 123 + 26 + 75 + 12 + 40 + 39 + 68 + 91; // sum of all elements
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
}
@Test
void testMaxSumWithMixedValues() {
// Test with mixed positive and negative numbers
int[] input = {1, -2, 3, 4, -1, 2, 1, -5, 4};
int expectedMaxSum = 3 + 4 + -1 + 2 + 1; // max subarray is [3, 4, -1, 2, 1]
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
}
@Test
void testMaxSumWithAllNegativeValues() {
// Test with all negative numbers
int[] input = {-2, -3, -1, -4};
int expectedMaxSum = -1; // max subarray is the least negative number
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
}
@Test
void testMaxSumWithSingleElement() {
// Test with a single positive element
int[] input = {10};
int expectedMaxSum = 10; // max subarray is the single element
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
// Test with a single negative element
input = new int[] {-10};
expectedMaxSum = -10; // max subarray is the single element
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
}
@Test
void testMaxSumWithZero() {
// Test with zeros in the array
int[] input = {0, -1, 2, -2, 0, 3};
int expectedMaxSum = 3; // max subarray is [2, -2, 0, 3]
assertTrue(KadaneAlgorithm.maxSum(input, expectedMaxSum));
}
@Test
void testMaxSumWithEmptyArray() {
// Test with an empty array; should ideally throw an exception or return false
int[] input = {};
assertThrows(ArrayIndexOutOfBoundsException.class, () -> { KadaneAlgorithm.maxSum(input, 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/dynamicprogramming/DPTest.java | src/test/java/com/thealgorithms/dynamicprogramming/DPTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class DPTest {
@Test
void testSumLessThanMinimumFaceValue() {
// When the sum is less than the minimum possible face value
// There are 0 ways to achieve the sum
assertEquals(0, DP.findWays(4, 2, 1)); // 4 faces, 2 dice, sum = 1
}
@Test
void testTwoDiceWithSumEqualToTwo() {
// When there are 2 dice and the sum is equal to the number of dice
// The only way is to have both dice showing 1
assertEquals(1, DP.findWays(2, 2, 2)); // 2 faces, 2 dice, sum = 2
}
@Test
void testTwoDiceWithSumThree() {
// When there are 2 dice and the sum is equal to 3
// Possible combinations are (1,2) and (2,1)
assertEquals(2, DP.findWays(2, 2, 3)); // 2 faces, 2 dice, sum = 3
}
@Test
void testThreeDiceWithSumEight() {
// Test for 3 dice, each having 6 faces
// Possible combinations to make sum of 8
assertEquals(21, DP.findWays(6, 3, 8)); // 6 faces, 3 dice, sum = 8
}
@Test
void testTwoDiceWithSumFive() {
// Test for 2 dice, with 4 faces to make sum of 5
// Possible combinations: (1,4), (2,3), (3,2), (4,1)
assertEquals(4, DP.findWays(4, 2, 5)); // 4 faces, 2 dice, sum = 5
}
@Test
void testThreeDiceWithSumFive() {
// Test for 3 dice, with 4 faces to make sum of 5
// Possible combinations: (1,1,3), (1,2,2), (1,3,1), (2,1,2), (2,2,1), (3,1,1)
assertEquals(6, DP.findWays(4, 3, 5)); // 4 faces, 3 dice, sum = 5
}
@Test
void testEdgeCaseZeroSum() {
// Test for 0 sum with 0 dice
assertEquals(0, DP.findWays(4, 0, 0)); // 4 faces, 0 dice, sum = 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/dynamicprogramming/NeedlemanWunschTest.java | src/test/java/com/thealgorithms/dynamicprogramming/NeedlemanWunschTest.java | package com.thealgorithms.dynamicprogramming;
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;
/**
* Unit Tests for the {@code NeedlemanWunsch} class
*/
class NeedlemanWunschTest {
@Test
void testIdenticalStrings() {
int score = NeedlemanWunsch.align("GATTACA", "GATTACA", 1, -1, -2);
assertEquals(7, score); // All matches, 7*1
}
@Test
void testSimpleMismatch() {
int score = NeedlemanWunsch.align("GATTACA", "GACTATA", 1, -1, -2);
assertEquals(3, score);
}
@Test
void testInsertion() {
int score = NeedlemanWunsch.align("GATTACA", "GATACA", 1, -1, -2);
// One deletion (gap penalty)
assertEquals(4, score);
}
@Test
void testEmptyStrings() {
assertEquals(0, NeedlemanWunsch.align("", "", 1, -1, -2));
}
@Test
void testOneEmpty() {
assertEquals(-14, NeedlemanWunsch.align("GATTACA", "", 1, -1, -2)); // 7 gaps × -2
}
@Test
void testGapHeavyAlignment() {
int score = NeedlemanWunsch.align("AAAA", "AA", 1, -1, -2);
assertEquals(-2, score); // Two matches (2*1) + two gaps (2*-2)
}
@ParameterizedTest
@CsvSource({"null,ABC", "ABC,null", "null,null"})
void testNullInputs(String s1, String s2) {
// Interpret "null" literal as Java null
String first = "null".equals(s1) ? null : s1;
String second = "null".equals(s2) ? null : s2;
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> NeedlemanWunsch.align(first, second, 1, -1, -2));
assertEquals("Input strings must not be null.", ex.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/dynamicprogramming/RegexMatchingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java | package com.thealgorithms.dynamicprogramming;
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 RegexMatchingTest {
private record RegexTestCase(String s, String p, boolean expected) {
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new RegexTestCase("aa", "*", true)), Arguments.of(new RegexTestCase("aa", "a*", true)), Arguments.of(new RegexTestCase("aa", "a", false)), Arguments.of(new RegexTestCase("cb", "?b", true)), Arguments.of(new RegexTestCase("cb", "?a", false)),
Arguments.of(new RegexTestCase("adceb", "*a*b", true)), Arguments.of(new RegexTestCase("acdcb", "a*c?b", false)), Arguments.of(new RegexTestCase("", "*", true)), Arguments.of(new RegexTestCase("", "", true)));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testRegexRecursionMethod1(RegexTestCase testCase) {
assertEquals(testCase.expected(), RegexMatching.regexRecursion(testCase.s(), testCase.p()));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testRegexRecursionMethod2(RegexTestCase testCase) {
assertEquals(testCase.expected(), RegexMatching.regexRecursion(testCase.s(), testCase.p(), 0, 0));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testRegexRecursionMethod3(RegexTestCase testCase) {
assertEquals(testCase.expected(), RegexMatching.regexRecursion(testCase.s(), testCase.p(), 0, 0, new int[testCase.s().length()][testCase.p().length()]));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testRegexBottomUp(RegexTestCase testCase) {
assertEquals(testCase.expected(), RegexMatching.regexBU(testCase.s(), testCase.p()));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequenceTest.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequenceTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class LongestCommonSubsequenceTest {
@Test
public void testLCSBasic() {
String str1 = "ABCBDAB";
String str2 = "BDCAB";
String expected = "BDAB"; // The longest common subsequence
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSIdenticalStrings() {
String str1 = "AGGTAB";
String str2 = "AGGTAB";
String expected = "AGGTAB"; // LCS is the same as the strings
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSNoCommonCharacters() {
String str1 = "ABC";
String str2 = "XYZ";
String expected = ""; // No common subsequence
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithEmptyString() {
String str1 = "";
String str2 = "XYZ";
String expected = ""; // LCS with an empty string should be empty
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithBothEmptyStrings() {
String str1 = "";
String str2 = "";
String expected = ""; // LCS with both strings empty should be empty
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithNullFirstString() {
String str1 = null;
String str2 = "XYZ";
String expected = null; // Should return null if first string is null
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithNullSecondString() {
String str1 = "ABC";
String str2 = null;
String expected = null; // Should return null if second string is null
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithNullBothStrings() {
String str1 = null;
String str2 = null;
String expected = null; // Should return null if both strings are null
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
@Test
public void testLCSWithLongerStringContainingCommonSubsequence() {
String str1 = "ABCDEF";
String str2 = "AEBDF";
String expected = "ABDF"; // Common subsequence is "ABDF"
String result = LongestCommonSubsequence.getLCS(str1, str2);
assertEquals(expected, result);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/CountFriendsPairingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/CountFriendsPairingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class CountFriendsPairingTest {
@Test
void testSmallCase() {
int n = 5;
int[] expectedGolombSequence = {1, 2, 2, 3, 3};
assertTrue(CountFriendsPairing.countFriendsPairing(n, expectedGolombSequence));
}
@Test
void testMismatchSequence() {
int n = 5;
int[] wrongSequence = {1, 2, 2, 2, 3}; // An incorrect sequence
assertFalse(CountFriendsPairing.countFriendsPairing(n, wrongSequence));
}
@Test
void testLargerCase() {
int n = 10;
int[] expectedGolombSequence = {1, 2, 2, 3, 3, 4, 4, 4, 5, 5};
assertTrue(CountFriendsPairing.countFriendsPairing(n, expectedGolombSequence));
}
@Test
void testEdgeCaseSingleElement() {
int n = 1;
int[] expectedGolombSequence = {1};
assertTrue(CountFriendsPairing.countFriendsPairing(n, expectedGolombSequence));
}
@Test
void testEmptySequence() {
int n = 0;
int[] emptySequence = {};
// Test the case where n is 0 (should handle this gracefully)
assertTrue(CountFriendsPairing.countFriendsPairing(n, emptySequence));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/EditDistanceTest.java | src/test/java/com/thealgorithms/dynamicprogramming/EditDistanceTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class EditDistanceTest {
@ParameterizedTest
@CsvSource({"'', '', 0", "'abc', '', 3", "'', 'abcd', 4", "'same', 'same', 0", "'a', 'b', 1", "'abc', 'abd', 1"})
void testMinDistance(String str1, String str2, int expected) {
assertEquals(expected, EditDistance.minDistance(str1, str2));
}
@Test
public void testEditDistanceBothEmptyStrings() {
assertEquals(0, EditDistance.editDistance("", ""));
}
@Test
public void testEditDistanceOneEmptyString() {
assertEquals(5, EditDistance.editDistance("", "hello"));
assertEquals(7, EditDistance.editDistance("worldly", ""));
}
@Test
public void testEditDistanceOneEmptyStringMemoization() {
int[][] storage = new int[1][6];
assertAll("String assertions",
()
-> assertEquals(5, EditDistance.editDistance("", "hello", storage)),
() -> assertEquals(0, storage[0][0]), () -> assertEquals(0, storage[0][1]), () -> assertEquals(0, storage[0][2]), () -> assertEquals(0, storage[0][3]), () -> assertEquals(0, storage[0][4]), () -> assertEquals(5, storage[0][5]));
}
@Test
public void testEditDistanceEqualStrings() {
assertEquals(0, EditDistance.editDistance("test", "test"));
assertEquals(0, EditDistance.editDistance("abc", "abc"));
}
@Test
public void testEditDistanceEqualStringsMemoization() {
int[][] storage = new int[4][4];
assertAll("String assertions",
()
-> assertEquals(0, EditDistance.editDistance("abc", "abc", storage)),
()
-> assertEquals(0, storage[0][0]),
()
-> assertEquals(0, storage[0][1]),
()
-> assertEquals(0, storage[0][2]),
()
-> assertEquals(0, storage[0][3]),
()
-> assertEquals(0, storage[1][0]),
()
-> assertEquals(0, storage[1][1]),
()
-> assertEquals(0, storage[1][2]),
()
-> assertEquals(0, storage[1][3]),
()
-> assertEquals(0, storage[2][0]),
() -> assertEquals(0, storage[2][1]), () -> assertEquals(0, storage[2][2]), () -> assertEquals(0, storage[2][3]), () -> assertEquals(0, storage[3][0]), () -> assertEquals(0, storage[3][1]), () -> assertEquals(0, storage[3][2]), () -> assertEquals(0, storage[3][3]));
}
@Test
public void testEditDistanceOneCharacterDifference() {
assertEquals(1, EditDistance.editDistance("cat", "bat"));
assertEquals(1, EditDistance.editDistance("cat", "cats"));
assertEquals(1, EditDistance.editDistance("cats", "cat"));
}
@Test
public void testEditDistanceOneCharacterDifferenceMemoization() {
int[][] storage = new int[3][3];
assertAll("All assertions",
()
-> assertEquals(1, EditDistance.editDistance("at", "it", storage)),
()
-> assertEquals(0, storage[0][0]),
()
-> assertEquals(1, storage[0][1]),
() -> assertEquals(2, storage[0][2]), () -> assertEquals(1, storage[1][0]), () -> assertEquals(0, storage[1][1]), () -> assertEquals(1, storage[1][2]), () -> assertEquals(2, storage[2][0]), () -> assertEquals(1, storage[2][1]), () -> assertEquals(1, storage[2][2]));
}
@Test
public void testEditDistanceGeneralCases() {
assertEquals(3, EditDistance.editDistance("kitten", "sitting"));
assertEquals(2, EditDistance.editDistance("flaw", "lawn"));
assertEquals(5, EditDistance.editDistance("intention", "execution"));
}
@Test
public void testEditDistanceGeneralCasesMemoization() {
int[][] storage = new int[7][8];
assertEquals(3, EditDistance.editDistance("kitten", "sitting", storage));
assertAll("All assertions", () -> assertEquals(0, storage[0][0]), () -> assertEquals(3, storage[6][7]));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class WildcardMatchingTest {
@Test
public void testMatchingPattern() {
assertTrue(WildcardMatching.isMatch("aa", "a*"));
assertTrue(WildcardMatching.isMatch("adceb", "*a*b"));
}
@Test
public void testNonMatchingPattern() {
assertFalse(WildcardMatching.isMatch("cb", "?a"));
assertFalse(WildcardMatching.isMatch("acdcb", "a*c?b"));
assertFalse(WildcardMatching.isMatch("mississippi", "m*issi*iss?*i"));
}
@Test
public void testEmptyPattern() {
assertTrue(WildcardMatching.isMatch("", ""));
assertFalse(WildcardMatching.isMatch("abc", ""));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogNTest.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogNTest.java | package com.thealgorithms.dynamicprogramming;
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 LongestIncreasingSubsequenceNLogNTest {
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new int[] {10, 9, 2, 5, 3, 7, 101, 18}, 4), Arguments.of(new int[] {0, 1, 0, 3, 2, 3}, 4), Arguments.of(new int[] {7, 7, 7, 7, 7}, 1), Arguments.of(new int[] {1, 3, 5, 4, 7}, 4), Arguments.of(new int[] {}, 0), Arguments.of(new int[] {10}, 1),
Arguments.of(new int[] {3, 10, 2, 1, 20}, 3), Arguments.of(new int[] {50, 3, 10, 7, 40, 80}, 4));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testLengthOfLIS(int[] input, int expected) {
assertEquals(expected, LongestIncreasingSubsequenceNLogN.lengthOfLIS(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/dynamicprogramming/KnapsackTest.java | src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class KnapsackTest {
@Test
public void testKnapSackBasic() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = 5;
int expected = 7; // Maximum value should be 7 (items 1 and 4).
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackEmpty() {
int[] weights = {};
int[] values = {};
int weightCapacity = 10;
int expected = 0; // With no items, the result should be 0.
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackNoCapacity() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 5};
int weightCapacity = 0;
int expected = 0; // With no capacity, the result should be 0.
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackMaxCapacity() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = 10;
int expected = 13; // Maximum value should be 13 (items 1, 3, and 4).
int result = Knapsack.knapSack(weightCapacity, weights, values);
assertEquals(expected, result);
}
@Test
public void testKnapSackThrowsForInputsOfDifferentLength() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 5, 6}; // Different length values array.
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); });
}
@Test
public void testKnapSackThrowsForNullInputs() {
int[] weights = {2, 3, 4};
int[] values = {3, 4, 6};
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, null, values); });
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, null); });
}
@Test
public void testKnapSackThrowsForNegativeCapacity() {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int weightCapacity = -5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, values); });
}
@Test
public void testKnapSackThrowsForNegativeWeight() {
int[] weights = {2, 0, 4};
int[] values = {3, 4, 6};
int weightCapacity = 5;
assertThrows(IllegalArgumentException.class, () -> { Knapsack.knapSack(weightCapacity, weights, 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/dynamicprogramming/BruteForceKnapsackTest.java | src/test/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsackTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BruteForceKnapsackTest {
@Test
void testKnapSackBasicCase() {
int[] val = {60, 100, 120};
int[] wt = {10, 20, 30};
int w = 50;
int n = val.length;
// The expected result for this case is 220 (items 2 and 3 are included)
assertEquals(220, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackNoItems() {
int[] val = {};
int[] wt = {};
int w = 50;
int n = val.length;
// With no items, the maximum value should be 0
assertEquals(0, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackZeroCapacity() {
int[] val = {60, 100, 120};
int[] wt = {10, 20, 30};
int w = 0;
int n = val.length;
// With a knapsack of 0 capacity, no items can be included, so the value is 0
assertEquals(0, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackSingleItemFits() {
int[] val = {100};
int[] wt = {20};
int w = 30;
int n = val.length;
// Only one item, and it fits in the knapsack, so the result is 100
assertEquals(100, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackSingleItemDoesNotFit() {
int[] val = {100};
int[] wt = {20};
int w = 10;
int n = val.length;
// Single item does not fit in the knapsack, so the result is 0
assertEquals(0, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackAllItemsFit() {
int[] val = {20, 30, 40};
int[] wt = {1, 2, 3};
int w = 6;
int n = val.length;
// All items fit into the knapsack, so the result is the sum of all values (20 + 30 + 40 = 90)
assertEquals(90, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackNoneFit() {
int[] val = {100, 200, 300};
int[] wt = {100, 200, 300};
int w = 50;
int n = val.length;
// None of the items fit into the knapsack, so the result is 0
assertEquals(0, BruteForceKnapsack.knapSack(w, wt, val, n));
}
@Test
void testKnapSackSomeItemsFit() {
int[] val = {60, 100, 120};
int[] wt = {10, 20, 30};
int w = 40;
int n = val.length;
// Here, only the 2nd and 1st items should be included for a total value of 160
assertEquals(180, BruteForceKnapsack.knapSack(w, wt, val, 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/dynamicprogramming/TribonacciTest.java | src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code Tribonacci}.
*/
public class TribonacciTest {
/**
* Tests the Tribonacci computation for a set of known values.
*/
@Test
public void testKnownValues() {
assertEquals(0, Tribonacci.compute(0), "The 0th Tribonacci should be 0.");
assertEquals(1, Tribonacci.compute(1), "The 1st Tribonacci should be 1.");
assertEquals(1, Tribonacci.compute(2), "The 2nd Tribonacci should be 1.");
assertEquals(2, Tribonacci.compute(3), "The 3rd Tribonacci should be 2.");
assertEquals(4, Tribonacci.compute(4), "The 4th Tribonacci should be 4.");
assertEquals(7, Tribonacci.compute(5), "The 5th Tribonacci should be 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/dynamicprogramming/ClimbStairsTest.java | src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ClimbStairsTest {
@Test
void climbStairsTestForTwo() {
assertEquals(2, ClimbingStairs.numberOfWays(2));
}
@Test
void climbStairsTestForZero() {
assertEquals(0, ClimbingStairs.numberOfWays(0));
}
@Test
void climbStairsTestForOne() {
assertEquals(1, ClimbingStairs.numberOfWays(1));
}
@Test
void climbStairsTestForFive() {
assertEquals(8, ClimbingStairs.numberOfWays(5));
}
@Test
void climbStairsTestForThree() {
assertEquals(3, ClimbingStairs.numberOfWays(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/dynamicprogramming/MaximumProductSubarrayTest.java | src/test/java/com/thealgorithms/dynamicprogramming/MaximumProductSubarrayTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class MaximumProductSubarrayTest {
/**
* Test case for an array with all positive numbers.
* The expected maximum product is the product of all elements.
*/
@Test
void testAllPositiveNumbers() {
int[] nums = {2, 3, 4};
int expected = 24;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 24.");
}
/**
* Test case for an array with positive and negative numbers.
* The expected maximum product is 24 (subarray [2, -3, -4]).
*/
@Test
void testMixedPositiveAndNegative() {
int[] nums = {2, -3, -4, 1};
int expected = 24;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 24.");
}
/**
* Test case for an array containing zeros.
* The expected maximum product is 24 (subarray [4, 6]).
*/
@Test
void testArrayWithZeros() {
int[] nums = {2, 3, 0, 4, 6};
int expected = 24;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 24.");
}
/**
* Test case for an array with a single element.
* The expected maximum product is the element itself.
*/
@Test
void testSingleElement() {
int[] nums = {5};
int expected = 5;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 5.");
}
/**
* Test case for an array with all negative numbers.
* The expected maximum product is 12 (subarray [-3, -4]).
*/
@Test
void testAllNegativeNumbers() {
int[] nums = {-2, -3, -4};
int expected = 12;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 12.");
}
/**
* Test case for an array with negative numbers where odd count of negatives
* breaks the chain. The expected maximum product is 60 (subarray [-2, -3, 10]).
*/
@Test
void testOddNegativeNumbers() {
int[] nums = {-2, -3, 10, -1};
int expected = 60;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 60.");
}
/**
* Test case for an empty array.
* The expected maximum product is 0.
*/
@Test
void testEmptyArray() {
int[] nums = {};
int expected = 0;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 0 for an empty array.");
}
/**
* Test case for a null array.
* The expected maximum product is 0.
*/
@Test
void testNullArray() {
int[] nums = null;
int expected = 0;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 0 for a null array.");
}
/**
* Test case for an array with alternating positive and negative numbers.
* The expected maximum product is 6 (subarray [2, 3]).
*/
@Test
void testAlternatingNumbers() {
int[] nums = {2, 3, -2, 4};
int expected = 6;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 6.");
}
/**
* Test case for an array with large positive and negative numbers.
* The expected maximum product is 360 (subarray [6, -3, -20]).
*/
@Test
void testLargeNumbers() {
int[] nums = {6, -3, -20, 0, 5};
int expected = 360;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be 360.");
}
/**
* Test case for an array with single negative number.
* The expected maximum product is the negative number itself.
*/
@Test
void testSingleNegativeElement() {
int[] nums = {-8};
int expected = -8;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product should be -8.");
}
/**
* Test case for an array with multiple zeros.
* The expected maximum product is 6 (subarray [2, 3]).
*/
@Test
void testMultipleZeros() {
int[] nums = {0, 2, 3, 0, 4};
int expected = 6;
int actual = MaximumProductSubarray.maxProduct(nums);
assertEquals(expected, actual, "The maximum product 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/dynamicprogramming/MatrixChainMultiplicationTest.java | src/test/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplicationTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
class MatrixChainMultiplicationTest {
@Test
void testMatrixCreation() {
MatrixChainMultiplication.Matrix matrix1 = new MatrixChainMultiplication.Matrix(1, 10, 20);
MatrixChainMultiplication.Matrix matrix2 = new MatrixChainMultiplication.Matrix(2, 20, 30);
assertEquals(1, matrix1.count());
assertEquals(10, matrix1.col());
assertEquals(20, matrix1.row());
assertEquals(2, matrix2.count());
assertEquals(20, matrix2.col());
assertEquals(30, matrix2.row());
}
@Test
void testMatrixChainOrder() {
// Create a list of matrices to be multiplied
ArrayList<MatrixChainMultiplication.Matrix> matrices = new ArrayList<>();
matrices.add(new MatrixChainMultiplication.Matrix(1, 10, 20)); // A(1) = 10 x 20
matrices.add(new MatrixChainMultiplication.Matrix(2, 20, 30)); // A(2) = 20 x 30
// Calculate matrix chain order
MatrixChainMultiplication.Result result = MatrixChainMultiplication.calculateMatrixChainOrder(matrices);
// Expected cost of multiplying A(1) and A(2)
int expectedCost = 6000; // The expected optimal cost of multiplying A(1)(10x20) and A(2)(20x30)
int actualCost = result.getM()[1][2];
assertEquals(expectedCost, actualCost);
}
@Test
void testOptimalParentheses() {
// Create a list of matrices to be multiplied
ArrayList<MatrixChainMultiplication.Matrix> matrices = new ArrayList<>();
matrices.add(new MatrixChainMultiplication.Matrix(1, 10, 20)); // A(1) = 10 x 20
matrices.add(new MatrixChainMultiplication.Matrix(2, 20, 30)); // A(2) = 20 x 30
// Calculate matrix chain order
MatrixChainMultiplication.Result result = MatrixChainMultiplication.calculateMatrixChainOrder(matrices);
// Check the optimal split for parentheses
assertEquals(1, result.getS()[1][2]); // s[1][2] should point to the optimal split
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequenceTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
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 LongestArithmeticSubsequenceTest {
@ParameterizedTest
@MethodSource("provideTestCases")
void testGetLongestArithmeticSubsequenceLength(int[] nums, int expected) {
assertEquals(expected, LongestArithmeticSubsequence.getLongestArithmeticSubsequenceLength(nums));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testGetLongestArithmeticSubsequenceLengthReversedInput(int[] nums, int expected) {
ArrayUtils.reverse(nums);
assertEquals(expected, LongestArithmeticSubsequence.getLongestArithmeticSubsequenceLength(nums));
}
@Test
void testGetLongestArithmeticSubsequenceLengthThrowsForNullInput() {
assertThrows(IllegalArgumentException.class, () -> LongestArithmeticSubsequence.getLongestArithmeticSubsequenceLength(null));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new int[] {3, 6, 9, 12, 15}, 5), Arguments.of(new int[] {1, 7, 10, 13, 14, 19}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 4), Arguments.of(new int[] {}, 0), Arguments.of(new int[] {10}, 1), Arguments.of(new int[] {9, 4, 7, 2, 10}, 3),
Arguments.of(new int[] {1, 2, 2, 2, 2, 5}, 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/dynamicprogramming/PartitionProblemTest.java | src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class PartitionProblemTest {
@Test
public void testIfSumOfTheArrayIsOdd() {
assertFalse(PartitionProblem.partition(new int[] {1, 2, 2}));
}
@Test
public void testIfSizeOfTheArrayIsOne() {
assertFalse(PartitionProblem.partition(new int[] {2}));
}
@Test
public void testIfSumOfTheArrayIsEven1() {
assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6}));
}
@Test
public void testIfSumOfTheArrayIsEven2() {
assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java | package com.thealgorithms.dynamicprogramming;
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 LongestAlternatingSubsequenceTest {
@ParameterizedTest
@MethodSource("provideTestCases")
void testAlternatingLength(int[] arr, int expected) {
assertEquals(expected, LongestAlternatingSubsequence.alternatingLength(arr, arr.length));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new int[] {1}, 1), Arguments.of(new int[] {1, 2}, 2), Arguments.of(new int[] {2, 1}, 2), Arguments.of(new int[] {1, 3, 2, 4, 3, 5}, 6), Arguments.of(new int[] {1, 2, 3, 4, 5}, 2), Arguments.of(new int[] {5, 4, 3, 2, 1}, 2),
Arguments.of(new int[] {10, 22, 9, 33, 49, 50, 31, 60}, 6), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 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/dynamicprogramming/TreeMatchingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/TreeMatchingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.thealgorithms.datastructures.graphs.UndirectedAdjacencyListGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class TreeMatchingTest {
UndirectedAdjacencyListGraph graph;
@BeforeEach
void setUp() {
graph = new UndirectedAdjacencyListGraph();
for (int i = 0; i < 14; i++) {
graph.addNode();
}
}
@Test
void testMaxMatchingForGeneralTree() {
graph.addEdge(0, 1, 20);
graph.addEdge(0, 2, 30);
graph.addEdge(1, 3, 40);
graph.addEdge(1, 4, 10);
graph.addEdge(2, 5, 20);
graph.addEdge(3, 6, 30);
graph.addEdge(3, 7, 30);
graph.addEdge(5, 8, 40);
graph.addEdge(5, 9, 10);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(110, treeMatching.getMaxMatching(0, -1));
}
@Test
void testMaxMatchingForBalancedTree() {
graph.addEdge(0, 1, 20);
graph.addEdge(0, 2, 30);
graph.addEdge(0, 3, 40);
graph.addEdge(1, 4, 10);
graph.addEdge(1, 5, 20);
graph.addEdge(2, 6, 20);
graph.addEdge(3, 7, 30);
graph.addEdge(5, 8, 10);
graph.addEdge(5, 9, 20);
graph.addEdge(7, 10, 10);
graph.addEdge(7, 11, 10);
graph.addEdge(7, 12, 5);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(100, treeMatching.getMaxMatching(0, -1));
}
@Test
void testMaxMatchingForTreeWithVariedEdgeWeights() {
graph.addEdge(0, 1, 20);
graph.addEdge(0, 2, 30);
graph.addEdge(0, 3, 40);
graph.addEdge(0, 4, 50);
graph.addEdge(1, 5, 20);
graph.addEdge(2, 6, 20);
graph.addEdge(3, 7, 30);
graph.addEdge(5, 8, 10);
graph.addEdge(5, 9, 20);
graph.addEdge(7, 10, 10);
graph.addEdge(4, 11, 50);
graph.addEdge(4, 12, 20);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(140, treeMatching.getMaxMatching(0, -1));
}
@Test
void emptyTree() {
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(0, treeMatching.getMaxMatching(0, -1));
}
@Test
void testSingleNodeTree() {
UndirectedAdjacencyListGraph singleNodeGraph = new UndirectedAdjacencyListGraph();
singleNodeGraph.addNode();
TreeMatching treeMatching = new TreeMatching(singleNodeGraph);
assertEquals(0, treeMatching.getMaxMatching(0, -1));
}
@Test
void testLinearTree() {
graph.addEdge(0, 1, 10);
graph.addEdge(1, 2, 20);
graph.addEdge(2, 3, 30);
graph.addEdge(3, 4, 40);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(60, treeMatching.getMaxMatching(0, -1));
}
@Test
void testStarShapedTree() {
graph.addEdge(0, 1, 15);
graph.addEdge(0, 2, 25);
graph.addEdge(0, 3, 35);
graph.addEdge(0, 4, 45);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(45, treeMatching.getMaxMatching(0, -1));
}
@Test
void testUnbalancedTree() {
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 20);
graph.addEdge(1, 3, 30);
graph.addEdge(2, 4, 40);
graph.addEdge(4, 5, 50);
TreeMatching treeMatching = new TreeMatching(graph);
assertEquals(100, treeMatching.getMaxMatching(0, -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/dynamicprogramming/EggDroppingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class EggDroppingTest {
@Test
void hasMultipleEggSingleFloor() {
assertEquals(1, EggDropping.minTrials(3, 1));
}
@Test
void hasSingleEggSingleFloor() {
assertEquals(1, EggDropping.minTrials(1, 1));
}
@Test
void hasSingleEggMultipleFloor() {
assertEquals(3, EggDropping.minTrials(1, 3));
}
@Test
void hasMultipleEggMultipleFloor() {
assertEquals(7, EggDropping.minTrials(100, 101));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java | src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java | package com.thealgorithms.dynamicprogramming;
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.MethodSource;
class SubsetSumTest {
record TestCase(int[] arr, int sum, boolean expected) {
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testSubsetSum(TestCase testCase) {
assertEquals(testCase.expected(), SubsetSum.subsetSum(testCase.arr(), testCase.sum()));
}
private static Stream<TestCase> provideTestCases() {
return Stream.of(new TestCase(new int[] {50, 4, 10, 15, 34}, 64, true), new TestCase(new int[] {50, 4, 10, 15, 34}, 99, true), new TestCase(new int[] {50, 4, 10, 15, 34}, 5, false), new TestCase(new int[] {50, 4, 10, 15, 34}, 66, false), new TestCase(new int[] {}, 0, true),
new TestCase(new int[] {1, 2, 3}, 6, true), new TestCase(new int[] {1, 2, 3}, 7, false), new TestCase(new int[] {3, 34, 4, 12, 5, 2}, 9, true));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java | src/test/java/com/thealgorithms/dynamicprogramming/AbbreviationTest.java | package com.thealgorithms.dynamicprogramming;
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 AbbreviationTest {
@ParameterizedTest
@MethodSource("provideTestCases")
public void testAbbreviation(String a, String b, boolean expected) {
assertEquals(expected, Abbreviation.abbr(a, b));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(
// Example test case from problem description
Arguments.of("daBcd", "ABC", Boolean.TRUE),
// Test case where transformation is impossible
Arguments.of("dBcd", "ABC", Boolean.FALSE),
// Test case with exact match (all uppercase)
Arguments.of("ABC", "ABC", Boolean.TRUE),
// Test case where input string contains all required letters plus extra lowercase letters
Arguments.of("aAbBcC", "ABC", Boolean.TRUE),
// Test case with only lowercase letters in input
Arguments.of("abcd", "ABCD", Boolean.TRUE),
// Test case with an empty second string (b)
Arguments.of("abc", "", Boolean.TRUE),
// Test case with an empty first string (a) but non-empty second string (b)
Arguments.of("", "A", Boolean.FALSE),
// Complex case with interleaved letters
Arguments.of("daBcAbCd", "ABCD", Boolean.FALSE));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java | src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java | package com.thealgorithms.dynamicprogramming;
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 BoardPathTest {
@ParameterizedTest
@MethodSource("provideTestCases")
void testBpR(int start, int end, int expected) {
assertEquals(expected, BoardPath.bpR(start, end));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testBpRS(int start, int end, int expected) {
assertEquals(expected, BoardPath.bpRS(start, end, new int[end + 1]));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testBpIS(int start, int end, int expected) {
assertEquals(expected, BoardPath.bpIS(start, end, new int[end + 1]));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(0, 10, 492), Arguments.of(0, 5, 16), Arguments.of(0, 6, 32), Arguments.of(0, 3, 4), Arguments.of(0, 1, 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/dynamicprogramming/PalindromicPartitioningTest.java | src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java | package com.thealgorithms.dynamicprogramming;
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 PalindromicPartitioningTest {
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("a", 0), Arguments.of("aa", 0), Arguments.of("ab", 1), Arguments.of("ababbbabbababa", 3), Arguments.of("abcde", 4), Arguments.of("abacdcaba", 0));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testMinimalPartitions(String input, int expected) {
assertEquals(expected, PalindromicPartitioning.minimalPartitions(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/dynamicprogramming/ShortestCommonSupersequenceLengthTest.java | src/test/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLengthTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class ShortestCommonSupersequenceLengthTest {
@ParameterizedTest
@CsvSource({"AGGTAB, GXTXAYB, 9", "ABC, ABC, 3", "ABC, DEF, 6", "'', ABC, 3", "ABCD, AB, 4", "ABC, BCD, 4", "A, B, 2"})
void testShortestSupersequence(String input1, String input2, int expected) {
assertEquals(expected, ShortestCommonSupersequenceLength.shortestSuperSequence(input1, input2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java | src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SubsetCountTest {
@Test
void hasMultipleSubset() {
int[] arr = new int[] {1, 2, 3, 3};
assertEquals(3, SubsetCount.getCount(arr, 6));
}
@Test
void singleElementSubset() {
int[] arr = new int[] {1, 1, 1, 1};
assertEquals(4, SubsetCount.getCount(arr, 1));
}
@Test
void hasMultipleSubsetSO() {
int[] arr = new int[] {1, 2, 3, 3};
assertEquals(3, SubsetCount.getCountSO(arr, 6));
}
@Test
void singleSubsetSO() {
int[] arr = new int[] {1, 1, 1, 1};
assertEquals(1, SubsetCount.getCountSO(arr, 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/dynamicprogramming/UniqueSubsequencesCountTest.java | src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class UniqueSubsequencesCountTest {
@ParameterizedTest
@CsvSource({"abc, 7", "abcdashgdhas, 3592", "a, 1", "'a b', 7", "a1b2, 15", "AaBb, 15", "abab, 11"})
void subseqCountParameterizedTest(String input, int expected) {
assertEquals(expected, UniqueSubsequencesCount.countSubseq(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/dynamicprogramming/LongestValidParenthesesTest.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java | package com.thealgorithms.dynamicprogramming;
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 LongestValidParenthesesTest {
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("", 0), Arguments.of("(", 0), Arguments.of(")", 0), Arguments.of("()", 2), Arguments.of("(())", 4), Arguments.of("()()", 4), Arguments.of(")(", 0), Arguments.of("(()", 2), Arguments.of("())(", 2), Arguments.of("(()())", 6), Arguments.of("(((())))", 8),
Arguments.of("(()))(()", 4), Arguments.of("()()()(", 6), Arguments.of("(()())()(", 8), Arguments.of("((((((", 0), Arguments.of("))))))", 0), Arguments.of("(()())(", 6), Arguments.of("))()(", 2), Arguments.of("()((()))", 8), Arguments.of("((()((())))", 10));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testLongestValidParentheses(String input, int expected) {
assertEquals(expected, LongestValidParentheses.getLongestValidParentheses(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/dynamicprogramming/LongestIncreasingSubsequenceTests.java | src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
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 LongestIncreasingSubsequenceTests {
@FunctionalInterface
public interface IntArrayToInt {
int apply(int[] array);
}
@ParameterizedTest
@MethodSource("testCases")
public void testLongestIncreasingSubsequence(final int expected, final int[] input, final IntArrayToInt method) {
assertEquals(expected, method.apply(input));
}
private static Stream<Arguments> testCases() {
final Object[][] testData = {
{0, new int[] {}},
{1, new int[] {1}},
{1, new int[] {2, 2}},
{1, new int[] {3, 3, 3}},
{1, new int[] {4, 4, 4, 4}},
{1, new int[] {5, 5, 5, 5, 5}},
{2, new int[] {1, 2}},
{2, new int[] {1, 2, 2, 2, 2}},
{2, new int[] {1, 0, 2}},
{3, new int[] {1, 10, 2, 30}},
{3, new int[] {5, 8, 3, 7, 9, 1}},
{6, new int[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}},
{4, new int[] {10, 9, 2, 5, 3, 7, 101, 18}},
{4, new int[] {10, 10, 9, 9, 2, 2, 5, 5, 3, 3, 7, 7, 101, 101, 18, 18}},
{4, new int[] {0, 1, 0, 3, 2, 3}},
{2, new int[] {1, 1, 2, 2, 2}},
{3, new int[] {1, 1, 2, 2, 2, 3, 3, 3, 3}},
};
final List<IntArrayToInt> methods = Arrays.asList(LongestIncreasingSubsequence::lis, LongestIncreasingSubsequence::findLISLen);
return Stream.of(testData).flatMap(input -> methods.stream().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/dynamicprogramming/KnapsackMemoizationTest.java | src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KnapsackMemoizationTest {
KnapsackMemoization knapsackMemoization = new KnapsackMemoization();
@Test
void test1() {
int[] weight = {1, 3, 4, 5};
int[] value = {1, 4, 5, 7};
int capacity = 10;
assertEquals(13, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
@Test
void test2() {
int[] weight = {95, 4, 60, 32, 23, 72, 80, 62, 65, 46};
int[] value = {55, 10, 47, 5, 4, 50, 8, 61, 85, 87};
int capacity = 269;
assertEquals(295, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
@Test
void test3() {
int[] weight = {10, 20, 30};
int[] value = {60, 100, 120};
int capacity = 50;
assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
@Test
void test4() {
int[] weight = {1, 2, 3};
int[] value = {10, 20, 30};
int capacity = 0;
assertEquals(0, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
@Test
void test5() {
int[] weight = {1, 2, 3, 8};
int[] value = {10, 20, 30, 40};
int capacity = 50;
assertEquals(100, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java | src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class SumOfSubsetTest {
@Test
void basicCheck() {
assertFalse(SumOfSubset.subsetSum(new int[] {1, 2, 7, 10, 9}, 4, 14));
assertFalse(SumOfSubset.subsetSum(new int[] {2, 15, 1, 6, 7}, 4, 4));
assertTrue(SumOfSubset.subsetSum(new int[] {7, 3, 2, 5, 8}, 4, 14));
assertTrue(SumOfSubset.subsetSum(new int[] {4, 3, 2, 1}, 3, 5));
assertTrue(SumOfSubset.subsetSum(new int[] {1, 7, 2, 9, 10}, 4, 13));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java | src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MaximumSumOfNonAdjacentElementsTest {
// Tests for Approach1
@Test
public void testGetMaxSumApproach1WithEmptyArray() {
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {})); // Empty array
}
@Test
public void testGetMaxSumApproach1WithSingleElement() {
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1})); // Single element
}
@Test
public void testGetMaxSumApproach1WithTwoElementsTakeMax() {
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1, 2})); // Take max of both
}
@Test
public void testGetMaxSumApproach1WithMultipleElements() {
assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5
assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {5, 1, 1, 5})); // 5 + 5
}
// Tests for Approach2
@Test
public void testGetMaxSumApproach2WithEmptyArray() {
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {})); // Empty array
}
@Test
public void testGetMaxSumApproach2WithSingleElement() {
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1})); // Single element
}
@Test
public void testGetMaxSumApproach2WithTwoElementsTakeMax() {
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1, 2})); // Take max of both
}
@Test
public void testGetMaxSumApproach2WithMultipleElements() {
assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5
assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {5, 1, 1, 5})); // 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/dynamicprogramming/SubsetSumSpaceOptimizedTest.java | src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class SubsetSumSpaceOptimizedTest {
@Test
void basicCheck() {
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {7, 3, 2, 5, 8}, 14));
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {4, 3, 2, 1}, 5));
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 7, 2, 9, 10}, 13));
assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 2, 7, 10, 9}, 14));
assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {2, 15, 1, 6, 7}, 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/dynamicprogramming/CatalanNumberTest.java | src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CatalanNumberTest {
@Test
public void testCatalanNumber() {
assertEquals(42, CatalanNumber.findNthCatalan(5));
assertEquals(16796, CatalanNumber.findNthCatalan(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/dynamicprogramming/WineProblemTest.java | src/test/java/com/thealgorithms/dynamicprogramming/WineProblemTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the WineProblem class.
* This test class verifies the correctness of the wine selling problem solutions.
*/
class WineProblemTest {
/**
* Test for wpRecursion method.
*/
@Test
void testWpRecursion() {
int[] wines = {2, 3, 5, 1, 4}; // Prices of wines
int expectedProfit = 50; // The expected maximum profit
assertEquals(expectedProfit, WineProblem.wpRecursion(wines, 0, wines.length - 1), "The maximum profit using recursion should be 50.");
}
/**
* Test for wptd method (Top-Down DP with Memoization).
*/
@Test
void testWptd() {
int[] wines = {2, 3, 5, 1, 4}; // Prices of wines
int expectedProfit = 50; // The expected maximum profit
assertEquals(expectedProfit, WineProblem.wptd(wines, 0, wines.length - 1, new int[wines.length][wines.length]), "The maximum profit using top-down DP should be 50.");
}
/**
* Test for wpbu method (Bottom-Up DP with Tabulation).
*/
@Test
void testWpbu() {
int[] wines = {2, 3, 5, 1, 4}; // Prices of wines
int expectedProfit = 50; // The expected maximum profit
assertEquals(expectedProfit, WineProblem.wpbu(wines), "The maximum profit using bottom-up DP should be 50.");
}
/**
* Test with a single wine.
*/
@Test
void testSingleWine() {
int[] wines = {10}; // Only one wine
int expectedProfit = 10; // Selling the only wine at year 1
assertEquals(expectedProfit, WineProblem.wpbu(wines), "The maximum profit for a single wine should be 10.");
}
/**
* Test with multiple wines of the same price.
*/
@Test
void testSamePriceWines() {
int[] wines = {5, 5, 5}; // All wines have the same price
int expectedProfit = 30; // Profit is 5 * (1 + 2 + 3)
assertEquals(expectedProfit, WineProblem.wpbu(wines), "The maximum profit with same price wines should be 30.");
}
/**
* Test with no wines.
*/
@Test
void testNoWines() {
int[] wines = {};
assertThrows(IllegalArgumentException.class, () -> WineProblem.wpbu(wines), "The maximum profit for no wines should throw an IllegalArgumentException.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java | src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.function.ToIntBiFunction;
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 LevenshteinDistanceTests {
@ParameterizedTest
@MethodSource("testCases")
public void testLevenshteinDistance(final int expected, final String str1, final String str2, final ToIntBiFunction<String, String> dist) {
assertEquals(expected, dist.applyAsInt(str1, str2));
assertEquals(expected, dist.applyAsInt(str2, str1));
assertEquals(0, dist.applyAsInt(str1, str1));
assertEquals(0, dist.applyAsInt(str2, str2));
}
private static Stream<Arguments> testCases() {
final Object[][] testData = {
{0, "", ""},
{0, "Hello, World!", "Hello, World!"},
{4, "", "Rust"},
{3, "horse", "ros"},
{6, "tan", "elephant"},
{8, "execute", "intention"},
{1, "a", "b"},
{1, "a", "aa"},
{1, "a", ""},
{1, "a", "ab"},
{1, "a", "ba"},
{2, "a", "bc"},
{2, "a", "cb"},
};
final List<ToIntBiFunction<String, String>> methods = Arrays.asList(LevenshteinDistance::naiveLevenshteinDistance, LevenshteinDistance::optimizedLevenshteinDistance);
return Stream.of(testData).flatMap(input -> methods.stream().map(method -> Arguments.of(input[0], input[1], input[2], 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/dynamicprogramming/AllConstructTest.java | src/test/java/com/thealgorithms/dynamicprogramming/AllConstructTest.java | package com.thealgorithms.dynamicprogramming;
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 AllConstructTest {
@Test
public void testAllConstructBasic() {
List<List<String>> expected = singletonList(Arrays.asList("he", "l", "l", "o"));
List<List<String>> result = AllConstruct.allConstruct("hello", Arrays.asList("he", "l", "o"));
assertEquals(expected, result);
}
@Test
public void testAllConstructMultipleWays() {
List<List<String>> expected = Arrays.asList(Arrays.asList("purp", "le"), Arrays.asList("p", "ur", "p", "le"));
List<List<String>> result = AllConstruct.allConstruct("purple", Arrays.asList("purp", "p", "ur", "le", "purpl"));
assertEquals(expected, result);
}
@Test
public void testAllConstructNoWays() {
List<List<String>> expected = emptyList();
List<List<String>> result = AllConstruct.allConstruct("abcdef", Arrays.asList("gh", "ijk"));
assertEquals(expected, result);
}
@Test
public void testAllConstructEmptyTarget() {
List<List<String>> expected = singletonList(emptyList());
List<List<String>> result = AllConstruct.allConstruct("", Arrays.asList("a", "b", "c"));
assertEquals(expected, result);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java | src/test/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmaskTest.java | package com.thealgorithms.dynamicprogramming;
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 final class AssignmentUsingBitmaskTest {
@Test
public void testCountNoOfWays() {
int totalTasks = 5;
List<List<Integer>> taskPerformed = Arrays.asList(Arrays.asList(1, 3, 4), Arrays.asList(1, 2, 5), Arrays.asList(3, 4));
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
int ways = assignment.countNoOfWays();
assertEquals(10, ways);
}
@Test
public void testNoPossibleAssignments() {
int totalTasks = 3;
List<List<Integer>> taskPerformed = Arrays.asList(singletonList(2), singletonList(3));
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
int ways = assignment.countNoOfWays();
assertEquals(1, ways);
}
@Test
public void testSinglePersonMultipleTasks() {
int totalTasks = 3;
List<List<Integer>> taskPerformed = singletonList(Arrays.asList(1, 2, 3));
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
int ways = assignment.countNoOfWays();
assertEquals(3, ways);
}
@Test
public void testMultiplePeopleSingleTask() {
int totalTasks = 1;
List<List<Integer>> taskPerformed = Arrays.asList(singletonList(1), singletonList(1));
AssignmentUsingBitmask assignment = new AssignmentUsingBitmask(taskPerformed, totalTasks);
int ways = assignment.countNoOfWays();
assertEquals(0, ways);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java | src/test/java/com/thealgorithms/dynamicprogramming/FibonacciTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class FibonacciTest {
@BeforeEach
void setUp() {
// Clear the cache before each test to avoid interference
Fibonacci.CACHE.clear();
}
@Test
void testFibMemo() {
// Test memoization method
assertEquals(0, Fibonacci.fibMemo(0));
assertEquals(1, Fibonacci.fibMemo(1));
assertEquals(1, Fibonacci.fibMemo(2));
assertEquals(2, Fibonacci.fibMemo(3));
assertEquals(3, Fibonacci.fibMemo(4));
assertEquals(5, Fibonacci.fibMemo(5));
assertEquals(8, Fibonacci.fibMemo(6));
assertEquals(13, Fibonacci.fibMemo(7));
assertEquals(21, Fibonacci.fibMemo(8));
assertEquals(34, Fibonacci.fibMemo(9));
assertEquals(55, Fibonacci.fibMemo(10));
}
@Test
void testFibBotUp() {
// Test bottom-up method
assertEquals(0, Fibonacci.fibBotUp(0));
assertEquals(1, Fibonacci.fibBotUp(1));
assertEquals(1, Fibonacci.fibBotUp(2));
assertEquals(2, Fibonacci.fibBotUp(3));
assertEquals(3, Fibonacci.fibBotUp(4));
assertEquals(5, Fibonacci.fibBotUp(5));
assertEquals(8, Fibonacci.fibBotUp(6));
assertEquals(13, Fibonacci.fibBotUp(7));
assertEquals(21, Fibonacci.fibBotUp(8));
assertEquals(34, Fibonacci.fibBotUp(9));
assertEquals(55, Fibonacci.fibBotUp(10));
}
@Test
void testFibOptimized() {
// Test optimized Fibonacci method
assertEquals(0, Fibonacci.fibOptimized(0));
assertEquals(1, Fibonacci.fibOptimized(1));
assertEquals(1, Fibonacci.fibOptimized(2));
assertEquals(2, Fibonacci.fibOptimized(3));
assertEquals(3, Fibonacci.fibOptimized(4));
assertEquals(5, Fibonacci.fibOptimized(5));
assertEquals(8, Fibonacci.fibOptimized(6));
assertEquals(13, Fibonacci.fibOptimized(7));
assertEquals(21, Fibonacci.fibOptimized(8));
assertEquals(34, Fibonacci.fibOptimized(9));
assertEquals(55, Fibonacci.fibOptimized(10));
}
@Test
void testFibBinet() {
// Test Binet's formula method
assertEquals(0, Fibonacci.fibBinet(0));
assertEquals(1, Fibonacci.fibBinet(1));
assertEquals(1, Fibonacci.fibBinet(2));
assertEquals(2, Fibonacci.fibBinet(3));
assertEquals(3, Fibonacci.fibBinet(4));
assertEquals(5, Fibonacci.fibBinet(5));
assertEquals(8, Fibonacci.fibBinet(6));
assertEquals(13, Fibonacci.fibBinet(7));
assertEquals(21, Fibonacci.fibBinet(8));
assertEquals(34, Fibonacci.fibBinet(9));
assertEquals(55, Fibonacci.fibBinet(10));
}
@Test
void testNegativeInput() {
// Test negative input; Fibonacci is not defined for negative numbers
assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibMemo(-1); });
assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibBotUp(-1); });
assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibOptimized(-1); });
assertThrows(IllegalArgumentException.class, () -> { Fibonacci.fibBinet(-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/dynamicprogramming/RodCuttingTest.java | src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the RodCutting class.
* This test class verifies the correctness of the cutRod method for various input cases.
*/
class RodCuttingTest {
/**
* Test case for cutting a rod of length 1.
* The expected maximum obtainable value is the price of the piece of length 1.
*/
@Test
void testCutRodLength1() {
int[] prices = {1}; // Price for piece of length 1
int length = 1;
int expectedValue = 1;
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 1 should be 1.");
}
/**
* Test case for cutting a rod of length 2.
* The expected maximum obtainable value is the best price combination for length 2.
*/
@Test
void testCutRodLength2() {
int[] prices = {1, 5}; // Prices for lengths 1 and 2
int length = 2;
int expectedValue = 5; // Best value is to cut it into a single piece of length 2
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 2 should be 5.");
}
/**
* Test case for cutting a rod of length 3.
* The expected maximum obtainable value is the best price combination for length 3.
*/
@Test
void testCutRodLength3() {
int[] prices = {1, 5, 8}; // Prices for lengths 1, 2, and 3
int length = 3;
int expectedValue = 8; // Best value is to cut it into a single piece of length 3
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 3 should be 8.");
}
/**
* Test case for cutting a rod of length 4.
* The expected maximum obtainable value is the best price combination for length 4.
*/
@Test
void testCutRodLength4() {
int[] prices = {1, 5, 8, 9}; // Prices for lengths 1, 2, 3, and 4
int length = 4;
int expectedValue = 10; // Best value is to cut it into two pieces of length 2
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 4 should be 10.");
}
/**
* Test case for cutting a rod of length 5.
* The expected maximum obtainable value is the best price combination for length 5.
*/
@Test
void testCutRodLength5() {
int[] prices = {1, 5, 8, 9, 10}; // Prices for lengths 1, 2, 3, 4, and 5
int length = 5;
int expectedValue = 13; // Best value is to cut it into pieces of lengths 2 and 3
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 5 should be 13.");
}
/**
* Test case for cutting a rod of length 0.
* The expected maximum obtainable value should be 0 since the rod has no length.
*/
@Test
void testCutRodLength0() {
int[] prices = {1, 5, 8, 9, 10}; // Prices are irrelevant for length 0
int length = 0;
int expectedValue = 0; // No value obtainable from a rod of length 0
assertEquals(expectedValue, RodCutting.cutRod(prices, length), "The maximum obtainable value for a rod of length 0 should be 0.");
}
/**
* Test case for an empty prices array.
* The expected maximum obtainable value should still be 0 for any length.
*/
@Test
void testCutRodEmptyPrices() {
int[] prices = {};
int length = 5;
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "An empty prices array should throw an IllegalArgumentException.");
}
@Test
void testCutRodNegativeLength() {
int[] prices = {1, 5, 8, 9, 10}; // Prices are irrelevant for negative length
int length = -1;
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "A negative rod length should throw an IllegalArgumentException.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/NewManShanksPrimeTest.java | src/test/java/com/thealgorithms/dynamicprogramming/NewManShanksPrimeTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the NewManShanksPrime class.
* This test class verifies the correctness of the nthManShanksPrime method
* for various input cases.
*/
class NewManShanksPrimeTest {
/**
* Test case for the 1st New Man Shanks prime.
* The expected answer is 1.
*/
@Test
void testNthManShanksPrime1() {
int n = 1;
int expectedAnswer = 1;
assertTrue(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 1st New Man Shanks prime should be 1.");
}
/**
* Test case for the 2nd New Man Shanks prime.
* The expected answer is 3.
*/
@Test
void testNthManShanksPrime2() {
int n = 2;
int expectedAnswer = 3;
assertTrue(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 2nd New Man Shanks prime should be 3.");
}
/**
* Test case for the 3rd New Man Shanks prime.
* The expected answer is 7.
*/
@Test
void testNthManShanksPrime3() {
int n = 3;
int expectedAnswer = 7;
assertTrue(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 3rd New Man Shanks prime should be 7.");
}
/**
* Test case for the 4th New Man Shanks prime.
* The expected answer is 17.
*/
@Test
void testNthManShanksPrime4() {
int n = 4;
int expectedAnswer = 17;
assertTrue(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 4th New Man Shanks prime should be 17.");
}
/**
* Test case for the 5th New Man Shanks prime.
* The expected answer is 41.
*/
@Test
void testNthManShanksPrime5() {
int n = 5;
int expectedAnswer = 41;
assertTrue(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 5th New Man Shanks prime should be 41.");
}
/**
* Test case with an incorrect expected answer.
* For n = 2, the expected answer is 3.
*/
@Test
void testNthManShanksPrimeIncorrectAnswer() {
int n = 2;
int expectedAnswer = 4; // Incorrect expected value
assertFalse(NewManShanksPrime.nthManShanksPrime(n, expectedAnswer), "The 2nd New Man Shanks prime should not be 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/dynamicprogramming/BoundaryFillTest.java | src/test/java/com/thealgorithms/dynamicprogramming/BoundaryFillTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BoundaryFillTest {
private int[][] image;
@BeforeEach
void setUp() {
image = new int[][] {{0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 0, 0, 3, 0, 0}, {0, 3, 0, 0, 3, 3, 3}, {0, 3, 3, 3, 0, 0, 3}, {0, 0, 0, 3, 0, 0, 3}, {0, 0, 0, 3, 3, 3, 3}};
}
@Test
void testGetPixel() {
assertEquals(3, BoundaryFill.getPixel(image, 1, 1));
assertEquals(0, BoundaryFill.getPixel(image, 2, 2));
assertEquals(3, BoundaryFill.getPixel(image, 4, 3));
}
@Test
void testPutPixel() {
BoundaryFill.putPixel(image, 2, 2, 5);
assertEquals(5, BoundaryFill.getPixel(image, 2, 2));
BoundaryFill.putPixel(image, 0, 0, 7);
assertEquals(7, BoundaryFill.getPixel(image, 0, 0));
}
@Test
void testBoundaryFill() {
BoundaryFill.boundaryFill(image, 2, 2, 5, 3);
int[][] expectedImage = {{0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 5, 5, 3, 0, 0}, {0, 3, 5, 5, 3, 3, 3}, {0, 3, 3, 3, 5, 5, 3}, {0, 0, 0, 3, 5, 5, 3}, {0, 0, 0, 3, 3, 3, 3}};
for (int i = 0; i < image.length; i++) {
assertArrayEquals(expectedImage[i], image[i]);
}
}
@Test
void testBoundaryFillEdgeCase() {
BoundaryFill.boundaryFill(image, 1, 1, 3, 3);
int[][] expectedImage = {{0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 0, 0, 3, 0, 0}, {0, 3, 0, 0, 3, 3, 3}, {0, 3, 3, 3, 0, 0, 3}, {0, 0, 0, 3, 0, 0, 3}, {0, 0, 0, 3, 3, 3, 3}};
for (int i = 0; i < image.length; i++) {
assertArrayEquals(expectedImage[i], image[i]);
}
}
@Test
void testBoundaryFillInvalidCoordinates() {
BoundaryFill.boundaryFill(image, -1, -1, 5, 3);
int[][] expectedImage = {{0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 0, 0, 3, 0, 0}, {0, 3, 0, 0, 3, 3, 3}, {0, 3, 3, 3, 0, 0, 3}, {0, 0, 0, 3, 0, 0, 3}, {0, 0, 0, 3, 3, 3, 3}};
for (int i = 0; i < image.length; i++) {
assertArrayEquals(expectedImage[i], image[i]);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java | src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java | package com.thealgorithms.dynamicprogramming;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class MinimumSumPartitionTest {
@Test
public void testMinimumSumPartitionWithEvenSum() {
int[] array = {1, 6, 11, 4};
assertEquals(0, MinimumSumPartition.minimumSumPartition(array));
}
@Test
public void testMinimumSumPartitionWithOddSum() {
int[] array = {36, 7, 46, 40};
assertEquals(23, MinimumSumPartition.minimumSumPartition(array));
}
@Test
public void testMinimumSumPartitionWithSingleElement() {
int[] array = {7};
assertEquals(7, MinimumSumPartition.minimumSumPartition(array));
}
@Test
public void testMinimumSumPartitionWithLargeNumbers() {
int[] array = {100, 200, 300, 400, 500};
assertEquals(100, MinimumSumPartition.minimumSumPartition(array));
}
@Test
public void testMinimumSumPartitionWithEmptyArray() {
int[] array = {};
assertEquals(0, MinimumSumPartition.minimumSumPartition(array));
}
@Test
public void testMinimumSumPartitionThrowsForNegativeArray() {
int[] array = {4, 1, -6, 7};
assertThrows(IllegalArgumentException.class, () -> { MinimumSumPartition.minimumSumPartition(array); });
}
}
| 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.