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/backtracking/CrosswordSolverTest.java
src/test/java/com/thealgorithms/backtracking/CrosswordSolverTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class CrosswordSolverTest { @Test public void testValidPlacement() { char[][] puzzle = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; assertTrue(CrosswordSolver.isValid(puzzle, "cat", 0, 0, true)); assertTrue(CrosswordSolver.isValid(puzzle, "dog", 0, 0, false)); assertFalse(CrosswordSolver.isValid(puzzle, "cat", 1, 2, false)); } @Test public void testPlaceAndRemoveWord() { char[][] puzzle = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; CrosswordSolver.placeWord(puzzle, "cat", 0, 0, true); assertEquals('c', puzzle[0][0]); assertEquals('a', puzzle[1][0]); assertEquals('t', puzzle[2][0]); CrosswordSolver.removeWord(puzzle, "cat", 0, 0, true); assertEquals(' ', puzzle[0][0]); assertEquals(' ', puzzle[1][0]); assertEquals(' ', puzzle[2][0]); } @Test public void testSolveCrossword() { char[][] puzzle = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; List<String> words = Arrays.asList("cat", "dog", "car"); assertTrue(CrosswordSolver.solveCrossword(puzzle, words)); /* Solved crossword: * c d c * a o a * t g r */ assertEquals('c', puzzle[0][0]); assertEquals('a', puzzle[1][0]); assertEquals('t', puzzle[2][0]); assertEquals('d', puzzle[0][1]); assertEquals('o', puzzle[1][1]); assertEquals('g', puzzle[2][1]); assertEquals('c', puzzle[0][2]); assertEquals('a', puzzle[1][2]); assertEquals('r', puzzle[2][2]); } @Test public void testNoSolution() { char[][] puzzle = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; List<String> words = Arrays.asList("cat", "dog", "elephant"); // 'elephant' is too long for the grid assertFalse(CrosswordSolver.solveCrossword(puzzle, words)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java
src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import com.thealgorithms.maths.BinomialCoefficient; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class ArrayCombinationTest { @ParameterizedTest @MethodSource("regularInputs") void testCombination(int n, int k, List<List<Integer>> expected) { assertEquals(expected.size(), BinomialCoefficient.binomialCoefficient(n, k)); assertEquals(expected, ArrayCombination.combination(n, k)); } @ParameterizedTest @MethodSource("wrongInputs") void testCombinationThrows(int n, int k) { assertThrows(IllegalArgumentException.class, () -> ArrayCombination.combination(n, k)); } private static Stream<Arguments> regularInputs() { return Stream.of(Arguments.of(0, 0, List.of(new ArrayList<Integer>())), Arguments.of(1, 0, List.of(new ArrayList<Integer>())), Arguments.of(1, 1, List.of(List.of(0))), Arguments.of(3, 0, List.of(new ArrayList<Integer>())), Arguments.of(3, 1, List.of(List.of(0), List.of(1), List.of(2))), Arguments.of(4, 2, List.of(List.of(0, 1), List.of(0, 2), List.of(0, 3), List.of(1, 2), List.of(1, 3), List.of(2, 3))), Arguments.of(5, 3, List.of(List.of(0, 1, 2), List.of(0, 1, 3), List.of(0, 1, 4), List.of(0, 2, 3), List.of(0, 2, 4), List.of(0, 3, 4), List.of(1, 2, 3), List.of(1, 2, 4), List.of(1, 3, 4), List.of(2, 3, 4))), Arguments.of(6, 4, List.of(List.of(0, 1, 2, 3), List.of(0, 1, 2, 4), List.of(0, 1, 2, 5), List.of(0, 1, 3, 4), List.of(0, 1, 3, 5), List.of(0, 1, 4, 5), List.of(0, 2, 3, 4), List.of(0, 2, 3, 5), List.of(0, 2, 4, 5), List.of(0, 3, 4, 5), List.of(1, 2, 3, 4), List.of(1, 2, 3, 5), List.of(1, 2, 4, 5), List.of(1, 3, 4, 5), List.of(2, 3, 4, 5)))); } private static Stream<Arguments> wrongInputs() { return Stream.of(Arguments.of(-1, 0), Arguments.of(0, -1), Arguments.of(2, 100), Arguments.of(3, 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/backtracking/SubsequenceFinderTest.java
src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class SubsequenceFinderTest { @ParameterizedTest @MethodSource("getTestCases") void testGenerateAll(TestCase testData) { final var actual = SubsequenceFinder.generateAll(testData.input()); assertIterableEquals(testData.expected(), actual); } static Stream<TestCase> getTestCases() { return Stream.of(new TestCase(new ArrayList<>(), List.of(List.of())), new TestCase(List.of(1, 2), List.of(List.of(), List.of(2), List.of(1), List.of(1, 2))), new TestCase(List.of("A", "B", "C"), List.of(List.of(), List.of("C"), List.of("B"), List.of("B", "C"), List.of("A"), List.of("A", "C"), List.of("A", "B"), List.of("A", "B", "C"))), new TestCase(List.of(1, 2, 3), List.of(List.of(), List.of(3), List.of(2), List.of(2, 3), List.of(1), List.of(1, 3), List.of(1, 2), List.of(1, 2, 3))), new TestCase(List.of(2, 2), List.of(List.of(), List.of(2), List.of(2), List.of(2, 2)))); } record TestCase(List<Object> input, List<List<Object>> expected) { } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java
src/test/java/com/thealgorithms/backtracking/PowerSumTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class PowerSumTest { @Test void testNumberZeroAndPowerZero() { PowerSum powerSum = new PowerSum(); int result = powerSum.powSum(0, 0); assertEquals(1, result); } @Test void testNumberHundredAndPowerTwo() { PowerSum powerSum = new PowerSum(); int result = powerSum.powSum(100, 2); assertEquals(3, result); } @Test void testNumberHundredAndPowerThree() { PowerSum powerSum = new PowerSum(); int result = powerSum.powSum(100, 3); assertEquals(1, result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java
src/test/java/com/thealgorithms/backtracking/UniquePermutationTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class UniquePermutationTest { @Test void testUniquePermutationsAab() { List<String> expected = Arrays.asList("AAB", "ABA", "BAA"); List<String> result = UniquePermutation.generateUniquePermutations("AAB"); assertEquals(expected, result); } @Test void testUniquePermutationsAbc() { List<String> expected = Arrays.asList("ABC", "ACB", "BAC", "BCA", "CAB", "CBA"); List<String> result = UniquePermutation.generateUniquePermutations("ABC"); assertEquals(expected, result); } @Test void testEmptyString() { List<String> expected = Arrays.asList(""); List<String> result = UniquePermutation.generateUniquePermutations(""); 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/backtracking/ParenthesesGeneratorTest.java
src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; 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 ParenthesesGeneratorTest { @ParameterizedTest @MethodSource("regularInputStream") void regularInputTests(int input, List<String> expected) { assertEquals(expected, ParenthesesGenerator.generateParentheses(input)); } @ParameterizedTest @MethodSource("negativeInputStream") void throwsForNegativeInputTests(int input) { assertThrows(IllegalArgumentException.class, () -> ParenthesesGenerator.generateParentheses(input)); } private static Stream<Arguments> regularInputStream() { return Stream.of(Arguments.of(0, List.of("")), Arguments.of(1, List.of("()")), Arguments.of(2, List.of("(())", "()()")), Arguments.of(3, List.of("((()))", "(()())", "(())()", "()(())", "()()()")), Arguments.of(4, List.of("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"))); } private static Stream<Arguments> negativeInputStream() { return Stream.of(Arguments.of(-1), Arguments.of(-5), Arguments.of(-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/backtracking/NQueensTest.java
src/test/java/com/thealgorithms/backtracking/NQueensTest.java
package com.thealgorithms.backtracking; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class NQueensTest { @Test public void testNQueens1() { List<List<String>> expected = singletonList(singletonList("Q")); assertEquals(expected, NQueens.getNQueensArrangements(1)); } @Test public void testNQueens2() { List<List<String>> expected = new ArrayList<>(); // No solution exists assertEquals(expected, NQueens.getNQueensArrangements(2)); } @Test public void testNQueens3() { List<List<String>> expected = new ArrayList<>(); // No solution exists assertEquals(expected, NQueens.getNQueensArrangements(3)); } @Test public void testNQueens4() { List<List<String>> expected = Arrays.asList(Arrays.asList(".Q..", "...Q", "Q...", "..Q."), Arrays.asList("..Q.", "Q...", "...Q", ".Q..")); assertEquals(expected, NQueens.getNQueensArrangements(4)); } @Test public void testNQueens5() { // Only the number of solutions is tested for larger N due to the complexity of checking each board configuration List<List<String>> result = NQueens.getNQueensArrangements(5); assertEquals(10, result.size()); // 5x5 board has 10 solutions } @Test public void testNQueens6() { List<List<String>> result = NQueens.getNQueensArrangements(6); assertEquals(4, result.size()); // 6x6 board has 4 solutions } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/MColoringTest.java
src/test/java/com/thealgorithms/backtracking/MColoringTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import org.junit.jupiter.api.Test; /** * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ class MColoringTest { @Test void testGraphColoring1() { int n = 4; int[][] graph = {{0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}}; int m = 3; // Number of colors assertTrue(MColoring.isColoringPossible(createGraph(graph), n, m)); } @Test void testGraphColoring2() { int n = 5; int[][] graph = {{0, 1, 1, 1, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {1, 1, 1, 0, 1}, {0, 0, 1, 1, 0}}; int m = 2; // Number of colors assertFalse(MColoring.isColoringPossible(createGraph(graph), n, m)); } @Test void testGraphColoring3() { int n = 3; int[][] graph = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}; int m = 2; // Number of colors assertFalse(MColoring.isColoringPossible(createGraph(graph), n, m)); } private ArrayList<Node> createGraph(int[][] graph) { int n = graph.length; ArrayList<Node> nodes = new ArrayList<>(n + 1); for (int i = 0; i <= n; i++) { nodes.add(new Node()); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Use j = i + 1 to avoid setting edges twice if (graph[i][j] > 0) { nodes.get(i + 1).edges.add(j + 1); nodes.get(j + 1).edges.add(i + 1); } } } return nodes; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java
src/test/java/com/thealgorithms/backtracking/KnightsTourTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class KnightsTourTest { @BeforeEach void setUp() { // Call the reset method in the KnightsTour class KnightsTour.resetBoard(); } @Test void testGridInitialization() { for (int r = 0; r < 12; r++) { for (int c = 0; c < 12; c++) { if (r < 2 || r > 12 - 3 || c < 2 || c > 12 - 3) { assertEquals(-1, KnightsTour.grid[r][c], "Border cells should be -1"); } else { assertEquals(0, KnightsTour.grid[r][c], "Internal cells should be 0"); } } } } @Test void testCountNeighbors() { // Manually place a knight at (3, 3) and mark nearby cells to test counting KnightsTour.grid[3][3] = 1; // Knight is here KnightsTour.grid[5][4] = -1; // Block one potential move int neighborCount = KnightsTour.countNeighbors(3, 3); assertEquals(3, neighborCount, "Knight at (3, 3) should have 3 neighbors (one blocked)"); KnightsTour.grid[4][1] = -1; // Block another move neighborCount = KnightsTour.countNeighbors(3, 3); assertEquals(3, neighborCount, "Knight at (3, 3) should have 3 neighbors (two blocked)"); } @Test void testNeighbors() { // Test the list of valid neighbors for a given cell (3, 3) List<int[]> neighbors = KnightsTour.neighbors(3, 3); assertEquals(4, neighbors.size(), "Knight at (3, 3) should have 8 valid neighbors"); } @Test void testSolveSuccessful() { // Test if the solve method works for a successful knight's tour KnightsTour.grid[2][2] = 1; // Start the knight at (2, 2) boolean result = KnightsTour.solve(2, 2, 2); assertTrue(result, "solve() should successfully complete a Knight's tour"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java
src/test/java/com/thealgorithms/backtracking/WordSearchTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class WordSearchTest { @Test void test1() { WordSearch ws = new WordSearch(); char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCCED"; assertTrue(ws.exist(board, word)); } @Test void test2() { WordSearch ws = new WordSearch(); char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "SEE"; assertTrue(ws.exist(board, word)); } @Test void test3() { WordSearch ws = new WordSearch(); char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCB"; Assertions.assertFalse(ws.exist(board, word)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/CombinationTest.java
src/test/java/com/thealgorithms/backtracking/CombinationTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.junit.jupiter.api.Test; public class CombinationTest { @Test void testNegativeElement() { Integer[] array = {1, 2}; assertThrows(IllegalArgumentException.class, () -> { Combination.combination(array, -1); }); } @Test void testNoElement() { List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 0); assertNotNull(result); assertEquals(0, result.size()); } @Test void testLengthOne() { List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 1); assertTrue(result.get(0).iterator().next() == 1); assertTrue(result.get(1).iterator().next() == 2); } @Test void testLengthTwo() { List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 2); Integer[] arr = result.get(0).toArray(new Integer[2]); assertTrue(arr[0] == 1); assertTrue(arr[1] == 2); } @Test void testCombinationsWithStrings() { List<TreeSet<String>> result = Combination.combination(new String[] {"a", "b", "c"}, 2); assertEquals(3, result.size()); assertTrue(result.contains(new TreeSet<>(Set.of("a", "b")))); assertTrue(result.contains(new TreeSet<>(Set.of("a", "c")))); assertTrue(result.contains(new TreeSet<>(Set.of("b", "c")))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java
src/test/java/com/thealgorithms/backtracking/FloodFillTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class FloodFillTest { @Test void testForEmptyImage() { int[][] image = {}; int[][] expected = {}; FloodFill.floodFill(image, 4, 5, 3, 2); assertArrayEquals(expected, image); } @Test void testForSingleElementImage() { int[][] image = {{1}}; int[][] expected = {{3}}; FloodFill.floodFill(image, 0, 0, 3, 1); assertArrayEquals(expected, image); } @Test void testForImageOne() { int[][] image = { {0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 1, 1, 5, 0, 0}, {0, 3, 1, 1, 5, 5, 3}, {0, 3, 5, 5, 1, 1, 3}, {0, 0, 0, 5, 1, 1, 3}, {0, 0, 0, 3, 3, 3, 3}, }; int[][] expected = { {0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 2, 2, 5, 0, 0}, {0, 3, 2, 2, 5, 5, 3}, {0, 3, 5, 5, 2, 2, 3}, {0, 0, 0, 5, 2, 2, 3}, {0, 0, 0, 3, 3, 3, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } @Test void testForImageTwo() { int[][] image = { {0, 0, 1, 1, 0, 0, 0}, {1, 1, 3, 3, 3, 0, 0}, {1, 3, 1, 1, 5, 0, 0}, {0, 3, 1, 1, 5, 5, 3}, {0, 3, 5, 5, 1, 1, 3}, {0, 0, 0, 5, 1, 1, 3}, {0, 0, 0, 1, 3, 1, 3}, }; int[][] expected = { {0, 0, 2, 2, 0, 0, 0}, {2, 2, 3, 3, 3, 0, 0}, {2, 3, 2, 2, 5, 0, 0}, {0, 3, 2, 2, 5, 5, 3}, {0, 3, 5, 5, 2, 2, 3}, {0, 0, 0, 5, 2, 2, 3}, {0, 0, 0, 2, 3, 2, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } @Test void testForImageThree() { int[][] image = { {1, 1, 2, 3, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1}, {1, 1, 1, 0, 3, 1, 2}, }; int[][] expected = { {4, 4, 2, 3, 4, 4, 4}, {4, 0, 0, 4, 0, 0, 4}, {4, 4, 4, 0, 3, 4, 2}, }; FloodFill.floodFill(image, 0, 1, 4, 1); assertArrayEquals(expected, image); } @Test void testForSameNewAndOldColor() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; FloodFill.floodFill(image, 0, 1, 1, 1); assertArrayEquals(expected, image); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/WordPatternMatcherTest.java
src/test/java/com/thealgorithms/backtracking/WordPatternMatcherTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class WordPatternMatcherTest { @Test public void testPatternMatchingSuccess() { assertTrue(WordPatternMatcher.matchWordPattern("aba", "GraphTreesGraph")); assertTrue(WordPatternMatcher.matchWordPattern("xyx", "PythonRubyPython")); } @Test public void testPatternMatchingFailure() { assertFalse(WordPatternMatcher.matchWordPattern("GG", "PythonJavaPython")); } @Test public void testEmptyPatternAndString() { assertTrue(WordPatternMatcher.matchWordPattern("", "")); } @Test public void testEmptyPattern() { assertFalse(WordPatternMatcher.matchWordPattern("", "nonempty")); } @Test public void testEmptyString() { assertFalse(WordPatternMatcher.matchWordPattern("abc", "")); } @Test public void testLongerPatternThanString() { assertFalse(WordPatternMatcher.matchWordPattern("abcd", "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/backtracking/SudokuSolverTest.java
src/test/java/com/thealgorithms/backtracking/SudokuSolverTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class SudokuSolverTest { @Test void testSolveSudokuEasyPuzzle() { int[][] board = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, {0, 0, 0, 0, 8, 0, 0, 7, 9}}; assertTrue(SudokuSolver.solveSudoku(board)); int[][] expected = {{5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9}}; assertArrayEquals(expected, board); } @Test void testSolveSudokuHardPuzzle() { int[][] board = {{0, 0, 0, 0, 0, 0, 6, 8, 0}, {0, 0, 0, 0, 7, 3, 0, 0, 9}, {3, 0, 9, 0, 0, 0, 0, 4, 5}, {4, 9, 0, 0, 0, 0, 0, 0, 0}, {8, 0, 3, 0, 5, 0, 9, 0, 2}, {0, 0, 0, 0, 0, 0, 0, 3, 6}, {9, 6, 0, 0, 0, 0, 3, 0, 8}, {7, 0, 0, 6, 8, 0, 0, 0, 0}, {0, 2, 8, 0, 0, 0, 0, 0, 0}}; assertTrue(SudokuSolver.solveSudoku(board)); } @Test void testSolveSudokuAlreadySolved() { int[][] board = {{5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9}}; assertTrue(SudokuSolver.solveSudoku(board)); } @Test void testSolveSudokuInvalidSize() { int[][] board = {{1, 2, 3}, {4, 5, 6}}; assertFalse(SudokuSolver.solveSudoku(board)); } @Test void testSolveSudokuNullBoard() { assertFalse(SudokuSolver.solveSudoku(null)); } @Test void testSolveSudokuEmptyBoard() { int[][] board = {{0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}; assertTrue(SudokuSolver.solveSudoku(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/backtracking/AllPathsFromSourceToTargetTest.java
src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import java.util.List; import org.junit.jupiter.api.Test; public class AllPathsFromSourceToTargetTest { @Test void testForFirstCase() { int vertices = 4; int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}}; int source = 2; int destination = 3; List<List<Integer>> list2 = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @Test void testForSecondCase() { int vertices = 5; int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}, {1, 4}, {3, 4}, {2, 4}}; int source = 0; int destination = 4; List<List<Integer>> list2 = List.of(List.of(0, 1, 3, 4), List.of(0, 1, 4), List.of(0, 2, 1, 3, 4), List.of(0, 2, 1, 4), List.of(0, 2, 4), List.of(0, 3, 4)); List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @Test void testForThirdCase() { int vertices = 6; int[][] a = {{1, 0}, {2, 3}, {0, 4}, {1, 5}, {4, 3}, {0, 2}, {0, 3}, {1, 2}, {0, 5}, {3, 4}, {2, 5}, {2, 4}}; int source = 1; int destination = 5; List<List<Integer>> list2 = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @Test void testForFourthcase() { int vertices = 3; int[][] a = {{0, 1}, {0, 2}, {1, 2}}; int source = 0; int destination = 2; List<List<Integer>> list2 = List.of(List.of(0, 1, 2), List.of(0, 2)); List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/PermutationTest.java
src/test/java/com/thealgorithms/backtracking/PermutationTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class PermutationTest { @Test void testNoElement() { List<Integer[]> result = Permutation.permutation(new Integer[] {}); assertEquals(result.get(0).length, 0); } @Test void testSingleElement() { List<Integer[]> result = Permutation.permutation(new Integer[] {1}); assertEquals(result.get(0)[0], 1); } @Test void testMultipleElements() { List<Integer[]> result = Permutation.permutation(new Integer[] {1, 2}); assertTrue(Arrays.equals(result.get(0), new Integer[] {1, 2})); assertTrue(Arrays.equals(result.get(1), new Integer[] {2, 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/backtracking/MazeRecursionTest.java
src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; /** * @author onglipwei * @create 2022-08-03 5:17 AM */ public class MazeRecursionTest { @Test public void testSolveMazeUsingFirstAndSecondStrategy() { int[][] map = new int[8][7]; int[][] map2 = new int[8][7]; // We use 1 to indicate walls // Set the ceiling and floor to 1 for (int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } // Set the left and right wall to 1 for (int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } // Set obstacles map[3][1] = 1; map[3][2] = 1; // Clone the original map for the second pathfinding strategy for (int i = 0; i < map.length; i++) { System.arraycopy(map[i], 0, map2[i], 0, map[i].length); } // Solve the maze using the first strategy int[][] solvedMap1 = MazeRecursion.solveMazeUsingFirstStrategy(map); // Solve the maze using the second strategy int[][] solvedMap2 = MazeRecursion.solveMazeUsingSecondStrategy(map2); int[][] expectedMap1 = new int[][] { {1, 1, 1, 1, 1, 1, 1}, {1, 2, 0, 0, 0, 0, 1}, {1, 2, 2, 2, 0, 0, 1}, {1, 1, 1, 2, 0, 0, 1}, {1, 0, 0, 2, 0, 0, 1}, {1, 0, 0, 2, 0, 0, 1}, {1, 0, 0, 2, 2, 2, 1}, {1, 1, 1, 1, 1, 1, 1}, }; int[][] expectedMap2 = new int[][] { {1, 1, 1, 1, 1, 1, 1}, {1, 2, 2, 2, 2, 2, 1}, {1, 0, 0, 0, 0, 2, 1}, {1, 1, 1, 0, 0, 2, 1}, {1, 0, 0, 0, 0, 2, 1}, {1, 0, 0, 0, 0, 2, 1}, {1, 0, 0, 0, 0, 2, 1}, {1, 1, 1, 1, 1, 1, 1}, }; // Assert the results assertArrayEquals(expectedMap1, solvedMap1); assertArrayEquals(expectedMap2, solvedMap2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/backtracking/CombinationSumTest.java
src/test/java/com/thealgorithms/backtracking/CombinationSumTest.java
package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.junit.jupiter.api.Test; class CombinationSumTest { private static List<List<Integer>> norm(Iterable<List<Integer>> x) { List<List<Integer>> y = new ArrayList<>(); for (var p : x) { var q = new ArrayList<>(p); q.sort(Integer::compare); y.add(q); } y.sort(Comparator.<List<Integer>>comparingInt(List::size).thenComparing(Object::toString)); return y; } @Test void sample() { int[] candidates = {2, 3, 6, 7}; int target = 7; var expected = List.of(List.of(2, 2, 3), List.of(7)); assertEquals(norm(expected), norm(CombinationSum.combinationSum(candidates, target))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/ProjectileMotionTest.java
src/test/java/com/thealgorithms/physics/ProjectileMotionTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Test class for the general-purpose ProjectileMotion calculator. * */ final class ProjectileMotionTest { private static final double DELTA = 1e-4; // Tolerance for comparing double values @Test @DisplayName("Test ground-to-ground launch (initial height is zero)") void testGroundToGroundLaunch() { ProjectileMotion.Result result = ProjectileMotion.calculateTrajectory(50, 30, 0); assertEquals(5.0986, result.getTimeOfFlight(), DELTA); assertEquals(220.7750, result.getHorizontalRange(), DELTA); assertEquals(31.8661, result.getMaxHeight(), DELTA); } @Test @DisplayName("Test launch from an elevated position") void testElevatedLaunch() { ProjectileMotion.Result result = ProjectileMotion.calculateTrajectory(30, 45, 100); assertEquals(7.1705, result.getTimeOfFlight(), DELTA); assertEquals(152.1091, result.getHorizontalRange(), DELTA); assertEquals(122.9436, result.getMaxHeight(), DELTA); // Final corrected value } @Test @DisplayName("Test launch straight up (90 degrees)") void testVerticalLaunch() { ProjectileMotion.Result result = ProjectileMotion.calculateTrajectory(40, 90, 20); assertEquals(8.6303, result.getTimeOfFlight(), DELTA); assertEquals(0.0, result.getHorizontalRange(), DELTA); assertEquals(101.5773, result.getMaxHeight(), DELTA); } @Test @DisplayName("Test horizontal launch from a height (0 degrees)") void testHorizontalLaunch() { ProjectileMotion.Result result = ProjectileMotion.calculateTrajectory(25, 0, 80); assertEquals(4.0392, result.getTimeOfFlight(), DELTA); assertEquals(100.9809, result.getHorizontalRange(), DELTA); assertEquals(80.0, result.getMaxHeight(), DELTA); } @Test @DisplayName("Test downward launch from a height (negative angle)") void testDownwardLaunchFromHeight() { ProjectileMotion.Result result = ProjectileMotion.calculateTrajectory(20, -30, 100); assertEquals(3.6100, result.getTimeOfFlight(), DELTA); assertEquals(62.5268, result.getHorizontalRange(), DELTA); assertEquals(100.0, result.getMaxHeight(), DELTA); } @Test @DisplayName("Test invalid arguments throw an exception") void testInvalidInputs() { assertThrows(IllegalArgumentException.class, () -> ProjectileMotion.calculateTrajectory(-10, 45, 100)); assertThrows(IllegalArgumentException.class, () -> ProjectileMotion.calculateTrajectory(10, 45, -100)); assertThrows(IllegalArgumentException.class, () -> ProjectileMotion.calculateTrajectory(10, 45, 100, 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/physics/GravitationTest.java
src/test/java/com/thealgorithms/physics/GravitationTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for the Gravitation utility class. */ final class GravitationTest { // A small tolerance (delta) for comparing floating-point numbers private static final double DELTA = 1e-9; private static final double G = Gravitation.GRAVITATIONAL_CONSTANT; @Test @DisplayName("Test gravitational force between two bodies on the x-axis") void testSimpleForceCalculation() { // Force on body 2 should be F = G*1*1 / 1^2 = G, directed towards body 1 (negative x) double[] forceOnB = Gravitation.calculateGravitationalForce(1.0, 0, 0, 1.0, 1, 0); assertArrayEquals(new double[] {-G, 0.0}, forceOnB, DELTA); // Force on body 1 should be equal and opposite (positive x) double[] forceOnA = Gravitation.calculateGravitationalForce(1.0, 1, 0, 1.0, 0, 0); assertArrayEquals(new double[] {G, 0.0}, forceOnA, DELTA); } @Test @DisplayName("Test gravitational force in a 2D plane") void test2DForceCalculation() { // Body 1 at (0,0) with mass 2kg // Body 2 at (3,4) with mass 1kg // Distance is sqrt(3^2 + 4^2) = 5 meters double magnitude = 2.0 * G / 25.0; // G * 2 * 1 / 5^2 // Unit vector from 2 to 1 is (-3/5, -4/5) double expectedFx = magnitude * -3.0 / 5.0; // -6G / 125 double expectedFy = magnitude * -4.0 / 5.0; // -8G / 125 double[] forceOnB = Gravitation.calculateGravitationalForce(2.0, 0, 0, 1.0, 3, 4); assertArrayEquals(new double[] {expectedFx, expectedFy}, forceOnB, DELTA); } @Test @DisplayName("Test overlapping bodies should result in zero force") void testOverlappingBodies() { double[] force = Gravitation.calculateGravitationalForce(1000.0, 1.5, -2.5, 500.0, 1.5, -2.5); assertArrayEquals(new double[] {0.0, 0.0}, force, DELTA); } @Test @DisplayName("Test circular orbit velocity with simple values") void testCircularOrbitVelocity() { // v = sqrt(G*1/1) = sqrt(G) double velocity = Gravitation.calculateCircularOrbitVelocity(1.0, 1.0); assertEquals(Math.sqrt(G), velocity, DELTA); } @Test @DisplayName("Test orbital velocity with real-world-ish values (LEO)") void testEarthOrbitVelocity() { // Mass of Earth ~5.972e24 kg // Radius of LEO ~6,771,000 m (Earth radius + 400km) double earthMass = 5.972e24; double leoRadius = 6.771e6; // FIX: Updated expected value to match the high-precision calculation double expectedVelocity = 7672.4904; double velocity = Gravitation.calculateCircularOrbitVelocity(earthMass, leoRadius); assertEquals(expectedVelocity, velocity, 0.0001); // Use a larger delta for big numbers } @Test @DisplayName("Test invalid inputs for orbital velocity throw exception") void testInvalidOrbitalVelocityInputs() { assertThrows(IllegalArgumentException.class, () -> Gravitation.calculateCircularOrbitVelocity(0, 100)); assertThrows(IllegalArgumentException.class, () -> Gravitation.calculateCircularOrbitVelocity(-1000, 100)); assertThrows(IllegalArgumentException.class, () -> Gravitation.calculateCircularOrbitVelocity(1000, 0)); assertThrows(IllegalArgumentException.class, () -> Gravitation.calculateCircularOrbitVelocity(1000, -100)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/ElasticCollision2DTest.java
src/test/java/com/thealgorithms/physics/ElasticCollision2DTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class ElasticCollision2DTest { @Test void testEqualMassHeadOnCollision() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, 1, 0, 1.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(1, 0, -1, 0, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); assertEquals(-1.0, a.vx, 1e-6); assertEquals(0.0, a.vy, 1e-6); assertEquals(1.0, b.vx, 1e-6); assertEquals(0.0, b.vy, 1e-6); } @Test void testUnequalMassHeadOnCollision() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, 2, 0, 2.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(1, 0, -1, 0, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); // 1D head-on collision results assertEquals(0.0, a.vx, 1e-6); assertEquals(0.0, a.vy, 1e-6); assertEquals(3.0, b.vx, 1e-6); assertEquals(0.0, b.vy, 1e-6); } @Test void testMovingApartNoCollision() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, -1, 0, 1.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(1, 0, 1, 0, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); assertEquals(-1.0, a.vx, 1e-6); assertEquals(0.0, a.vy, 1e-6); assertEquals(1.0, b.vx, 1e-6); assertEquals(0.0, b.vy, 1e-6); } @Test void testGlancingCollision() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, 1, 1, 1.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(1, 1, -1, -0.5, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); // Ensure relative velocity along normal is reversed double nx = (b.x - a.x) / Math.hypot(b.x - a.x, b.y - a.y); double ny = (b.y - a.y) / Math.hypot(b.x - a.x, b.y - a.y); double relVelAfter = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny; assertTrue(relVelAfter > 0); } @Test void testOverlappingBodies() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, 1, 0, 1.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(0, 0, -1, 0, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); // Should not crash, velocities may remain unchanged assertEquals(1.0, a.vx, 1e-6); assertEquals(0.0, a.vy, 1e-6); assertEquals(-1.0, b.vx, 1e-6); assertEquals(0.0, b.vy, 1e-6); } @Test void testStationaryBodyHit() { ElasticCollision2D.Body a = new ElasticCollision2D.Body(0, 0, 2, 0, 1.0, 0.5); ElasticCollision2D.Body b = new ElasticCollision2D.Body(1, 0, 0, 0, 1.0, 0.5); ElasticCollision2D.resolveCollision(a, b); assertEquals(0.0, a.vx, 1e-6); assertEquals(0.0, a.vy, 1e-6); assertEquals(2.0, b.vx, 1e-6); assertEquals(0.0, b.vy, 1e-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/physics/SnellLawTest.java
src/test/java/com/thealgorithms/physics/SnellLawTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class SnellLawTest { @Test public void testRefractedAngle() { double n1 = 1.0; // air double n2 = 1.5; // glass double theta1 = Math.toRadians(30); double theta2 = SnellLaw.refractedAngle(n1, n2, theta1); double expected = Math.asin(n1 / n2 * Math.sin(theta1)); assertEquals(expected, theta2, 1e-12); } @Test public void testTotalInternalReflection() { double n1 = 1.5; double n2 = 1.0; double theta1 = Math.toRadians(60); // large angle assertThrows(IllegalArgumentException.class, () -> SnellLaw.refractedAngle(n1, n2, theta1)); } @Test public void testNoTotalInternalReflectionAtLowAngles() { double n1 = 1.5; double n2 = 1.0; double theta1 = Math.toRadians(10); assertDoesNotThrow(() -> SnellLaw.refractedAngle(n1, n2, theta1)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/SimplePendulumRK4Test.java
src/test/java/com/thealgorithms/physics/SimplePendulumRK4Test.java
package com.thealgorithms.physics; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Test class for SimplePendulumRK4. * Tests numerical accuracy, physical correctness, and edge cases. */ class SimplePendulumRK4Test { private static final double EPSILON = 1e-6; private static final double ENERGY_DRIFT_TOLERANCE = 1e-3; @Test @DisplayName("Test constructor creates valid pendulum") void testConstructor() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.5, 9.81); Assertions.assertNotNull(pendulum); Assertions.assertEquals(1.5, pendulum.getLength(), EPSILON); Assertions.assertEquals(9.81, pendulum.getGravity(), EPSILON); } @Test @DisplayName("Test constructor rejects negative length") void testConstructorNegativeLength() { Assertions.assertThrows(IllegalArgumentException.class, () -> { new SimplePendulumRK4(-1.0, 9.81); }); } @Test @DisplayName("Test constructor rejects negative gravity") void testConstructorNegativeGravity() { Assertions.assertThrows(IllegalArgumentException.class, () -> { new SimplePendulumRK4(1.0, -9.81); }); } @Test @DisplayName("Test constructor rejects zero length") void testConstructorZeroLength() { Assertions.assertThrows(IllegalArgumentException.class, () -> { new SimplePendulumRK4(0.0, 9.81); }); } @Test @DisplayName("Test getters return correct values") void testGetters() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(2.5, 10.0); Assertions.assertEquals(2.5, pendulum.getLength(), EPSILON); Assertions.assertEquals(10.0, pendulum.getGravity(), EPSILON); } @Test @DisplayName("Test single RK4 step returns valid state") void testSingleStep() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {0.1, 0.0}; double[] newState = pendulum.stepRK4(state, 0.01); Assertions.assertNotNull(newState); Assertions.assertEquals(2, newState.length); } @Test @DisplayName("Test equilibrium stability (pendulum at rest stays at rest)") void testEquilibrium() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {0.0, 0.0}; for (int i = 0; i < 100; i++) { state = pendulum.stepRK4(state, 0.01); } Assertions.assertEquals(0.0, state[0], EPSILON, "Theta should remain at equilibrium"); Assertions.assertEquals(0.0, state[1], EPSILON, "Omega should remain zero"); } @Test @DisplayName("Test small angle oscillation returns to initial position") void testSmallAngleOscillation() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double initialAngle = Math.toRadians(5.0); double[] state = {initialAngle, 0.0}; double dt = 0.01; // Theoretical period for small angles double expectedPeriod = 2 * Math.PI * Math.sqrt(1.0 / 9.81); int stepsPerPeriod = (int) (expectedPeriod / dt); double[][] trajectory = pendulum.simulate(state, dt, stepsPerPeriod); double finalTheta = trajectory[stepsPerPeriod][0]; // After one period, should return close to initial position double error = Math.abs(finalTheta - initialAngle) / Math.abs(initialAngle); Assertions.assertTrue(error < 0.05, "Small angle approximation error should be < 5%"); } @Test @DisplayName("Test large angle oscillation is symmetric") void testLargeAngleOscillation() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.toRadians(120.0), 0.0}; double[][] trajectory = pendulum.simulate(state, 0.01, 500); double maxTheta = Double.NEGATIVE_INFINITY; double minTheta = Double.POSITIVE_INFINITY; for (double[] s : trajectory) { maxTheta = Math.max(maxTheta, s[0]); minTheta = Math.min(minTheta, s[0]); } Assertions.assertTrue(maxTheta > 0, "Should have positive excursions"); Assertions.assertTrue(minTheta < 0, "Should have negative excursions"); // Check symmetry double asymmetry = Math.abs((maxTheta + minTheta) / maxTheta); Assertions.assertTrue(asymmetry < 0.1, "Oscillation should be symmetric"); } @Test @DisplayName("Test energy conservation for small angle") void testEnergyConservationSmallAngle() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.toRadians(15.0), 0.0}; double initialEnergy = pendulum.calculateEnergy(state); for (int i = 0; i < 1000; i++) { state = pendulum.stepRK4(state, 0.01); } double finalEnergy = pendulum.calculateEnergy(state); double drift = Math.abs(finalEnergy - initialEnergy) / initialEnergy; Assertions.assertTrue(drift < ENERGY_DRIFT_TOLERANCE, "Energy drift should be < 0.1%, got: " + (drift * 100) + "%"); } @Test @DisplayName("Test energy conservation for large angle") void testEnergyConservationLargeAngle() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.toRadians(90.0), 0.0}; double initialEnergy = pendulum.calculateEnergy(state); for (int i = 0; i < 1000; i++) { state = pendulum.stepRK4(state, 0.01); } double finalEnergy = pendulum.calculateEnergy(state); double drift = Math.abs(finalEnergy - initialEnergy) / initialEnergy; Assertions.assertTrue(drift < ENERGY_DRIFT_TOLERANCE, "Energy drift should be < 0.1%, got: " + (drift * 100) + "%"); } @Test @DisplayName("Test simulate method returns correct trajectory") void testSimulate() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] initialState = {Math.toRadians(20.0), 0.0}; int steps = 100; double[][] trajectory = pendulum.simulate(initialState, 0.01, steps); Assertions.assertEquals(steps + 1, trajectory.length, "Trajectory should have steps + 1 entries"); Assertions.assertArrayEquals(initialState, trajectory[0], EPSILON, "First entry should match initial state"); // Verify state changes over time boolean changed = false; for (int i = 1; i <= steps; i++) { if (Math.abs(trajectory[i][0] - initialState[0]) > EPSILON) { changed = true; break; } } Assertions.assertTrue(changed, "Simulation should progress from initial state"); } @Test @DisplayName("Test energy calculation at equilibrium") void testEnergyAtEquilibrium() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {0.0, 0.0}; double energy = pendulum.calculateEnergy(state); Assertions.assertEquals(0.0, energy, EPSILON, "Energy at equilibrium should be zero"); } @Test @DisplayName("Test energy calculation at maximum angle") void testEnergyAtMaxAngle() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.PI / 2, 0.0}; double energy = pendulum.calculateEnergy(state); Assertions.assertTrue(energy > 0, "Energy should be positive at max angle"); } @Test @DisplayName("Test energy calculation with angular velocity") void testEnergyWithVelocity() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {0.0, 1.0}; double energy = pendulum.calculateEnergy(state); Assertions.assertTrue(energy > 0, "Energy should be positive with velocity"); } @Test @DisplayName("Test stepRK4 rejects null state") void testStepRejectsNullState() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); Assertions.assertThrows(IllegalArgumentException.class, () -> { pendulum.stepRK4(null, 0.01); }); } @Test @DisplayName("Test stepRK4 rejects invalid state length") void testStepRejectsInvalidStateLength() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); Assertions.assertThrows(IllegalArgumentException.class, () -> { pendulum.stepRK4(new double[] {0.1}, 0.01); }); } @Test @DisplayName("Test stepRK4 rejects negative time step") void testStepRejectsNegativeTimeStep() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); Assertions.assertThrows(IllegalArgumentException.class, () -> { pendulum.stepRK4(new double[] {0.1, 0.2}, -0.01); }); } @Test @DisplayName("Test extreme condition: very large angle") void testExtremeLargeAngle() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.toRadians(179.0), 0.0}; double[] result = pendulum.stepRK4(state, 0.01); Assertions.assertNotNull(result); Assertions.assertTrue(Double.isFinite(result[0]), "Should handle large angles without NaN"); Assertions.assertTrue(Double.isFinite(result[1]), "Should handle large angles without NaN"); } @Test @DisplayName("Test extreme condition: high angular velocity") void testExtremeHighVelocity() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {0.0, 10.0}; double[] result = pendulum.stepRK4(state, 0.01); Assertions.assertNotNull(result); Assertions.assertTrue(Double.isFinite(result[0]), "Should handle high velocity without NaN"); Assertions.assertTrue(Double.isFinite(result[1]), "Should handle high velocity without NaN"); } @Test @DisplayName("Test extreme condition: very small time step") void testExtremeSmallTimeStep() { SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81); double[] state = {Math.toRadians(10.0), 0.0}; double[] result = pendulum.stepRK4(state, 1e-6); Assertions.assertNotNull(result); Assertions.assertTrue(Double.isFinite(result[0]), "Should handle small time steps without NaN"); Assertions.assertTrue(Double.isFinite(result[1]), "Should handle small time steps without NaN"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/KinematicsTest.java
src/test/java/com/thealgorithms/physics/KinematicsTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for the Kinematics utility class. */ public final class KinematicsTest { // A small tolerance for comparing floating-point numbers private static final double DELTA = 1e-9; @Test @DisplayName("Test final velocity: v = u + at") void testCalculateFinalVelocity() { assertEquals(20.0, Kinematics.calculateFinalVelocity(10.0, 2.0, 5.0), DELTA); } @Test @DisplayName("Test displacement: s = ut + 0.5at^2") void testCalculateDisplacement() { assertEquals(75.0, Kinematics.calculateDisplacement(10.0, 2.0, 5.0), DELTA); } @Test @DisplayName("Test final velocity squared: v^2 = u^2 + 2as") void testCalculateFinalVelocitySquared() { assertEquals(400.0, Kinematics.calculateFinalVelocitySquared(10.0, 2.0, 75.0), DELTA); } @Test @DisplayName("Test displacement from average velocity: s = (u+v)/2 * t") void testCalculateDisplacementFromVelocities() { assertEquals(75.0, Kinematics.calculateDisplacementFromVelocities(10.0, 20.0, 5.0), DELTA); } @Test @DisplayName("Test with negative acceleration (deceleration)") void testDeceleration() { assertEquals(10.0, Kinematics.calculateFinalVelocity(30.0, -4.0, 5.0), DELTA); assertEquals(100.0, Kinematics.calculateDisplacement(30.0, -4.0, 5.0), DELTA); assertEquals(100.0, Kinematics.calculateFinalVelocitySquared(30.0, -4.0, 100.0), DELTA); assertEquals(100.0, Kinematics.calculateDisplacementFromVelocities(30.0, 10.0, 5.0), DELTA); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/ThinLensTest.java
src/test/java/com/thealgorithms/physics/ThinLensTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class ThinLensTest { @Test void testConvexLensRealImage() { double v = ThinLens.imageDistance(10, 20); assertEquals(20, v, 1e-6); } @Test void testMagnification() { assertEquals(2.0, ThinLens.magnification(20, 10), 1e-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/physics/DampedOscillatorTest.java
src/test/java/com/thealgorithms/physics/DampedOscillatorTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for {@link DampedOscillator}. * * <p>Tests focus on: * <ul> * <li>Constructor validation</li> * <li>Analytical displacement for underdamped and overdamped parameterizations</li> * <li>Basic numeric integration sanity using explicit Euler for small step sizes</li> * <li>Method argument validation (null/invalid inputs)</li> * </ul> */ @DisplayName("DampedOscillator — unit tests") public class DampedOscillatorTest { private static final double TOLERANCE = 1e-3; @Test @DisplayName("Constructor rejects invalid parameters") void constructorValidation() { assertAll("invalid-constructor-params", () -> assertThrows(IllegalArgumentException.class, () -> new DampedOscillator(0.0, 0.1), "omega0 == 0 should throw"), () -> assertThrows(IllegalArgumentException.class, () -> new DampedOscillator(-1.0, 0.1), "negative omega0 should throw"), () -> assertThrows(IllegalArgumentException.class, () -> new DampedOscillator(1.0, -0.1), "negative gamma should throw")); } @Test @DisplayName("Analytical displacement matches expected formula for underdamped case") void analyticalUnderdamped() { double omega0 = 10.0; double gamma = 0.5; DampedOscillator d = new DampedOscillator(omega0, gamma); double a = 1.0; double phi = 0.2; double t = 0.123; // expected: a * exp(-gamma * t) * cos(omega_d * t + phi) double omegaD = Math.sqrt(Math.max(0.0, omega0 * omega0 - gamma * gamma)); double expected = a * Math.exp(-gamma * t) * Math.cos(omegaD * t + phi); double actual = d.displacementAnalytical(a, phi, t); assertEquals(expected, actual, 1e-12, "Analytical underdamped displacement should match closed-form value"); } @Test @DisplayName("Analytical displacement gracefully handles overdamped parameters (omegaD -> 0)") void analyticalOverdamped() { double omega0 = 1.0; double gamma = 2.0; // gamma > omega0 => omega_d = 0 in our implementation (Math.max) DampedOscillator d = new DampedOscillator(omega0, gamma); double a = 2.0; double phi = Math.PI / 4.0; double t = 0.5; // With omegaD forced to 0 by implementation, expected simplifies to: double expected = a * Math.exp(-gamma * t) * Math.cos(phi); double actual = d.displacementAnalytical(a, phi, t); assertEquals(expected, actual, 1e-12, "Overdamped handling should reduce to exponential * cos(phase)"); } @Test @DisplayName("Explicit Euler step approximates analytical solution for small dt over short time") void eulerApproximatesAnalyticalSmallDt() { double omega0 = 10.0; double gamma = 0.5; DampedOscillator d = new DampedOscillator(omega0, gamma); double a = 1.0; double phi = 0.0; // initial conditions consistent with amplitude a and zero phase: // x(0) = a, v(0) = -a * gamma * cos(phi) + a * omegaD * sin(phi) double omegaD = Math.sqrt(Math.max(0.0, omega0 * omega0 - gamma * gamma)); double x0 = a * Math.cos(phi); double v0 = -a * gamma * Math.cos(phi) - a * omegaD * Math.sin(phi); // small general form double dt = 1e-4; int steps = 1000; // simulate to t = 0.1s double tFinal = steps * dt; double[] state = new double[] {x0, v0}; for (int i = 0; i < steps; i++) { state = d.stepEuler(state, dt); } double analyticAtT = d.displacementAnalytical(a, phi, tFinal); double numericAtT = state[0]; // Euler is low-order — allow a small tolerance but assert it remains close for small dt + short time. assertEquals(analyticAtT, numericAtT, TOLERANCE, String.format("Numeric Euler should approximate analytical solution at t=%.6f (tolerance=%g)", tFinal, TOLERANCE)); } @Test @DisplayName("stepEuler validates inputs and throws on null/invalid dt/state") void eulerInputValidation() { DampedOscillator d = new DampedOscillator(5.0, 0.1); assertAll("invalid-stepEuler-args", () -> assertThrows(IllegalArgumentException.class, () -> d.stepEuler(null, 0.01), "null state should throw"), () -> assertThrows(IllegalArgumentException.class, () -> d.stepEuler(new double[] {1.0}, 0.01), "state array with invalid length should throw"), () -> assertThrows(IllegalArgumentException.class, () -> d.stepEuler(new double[] {1.0, 0.0}, 0.0), "non-positive dt should throw"), () -> assertThrows(IllegalArgumentException.class, () -> d.stepEuler(new double[] {1.0, 0.0}, -1e-3), "negative dt should throw")); } @Test @DisplayName("Getter methods return configured parameters") void gettersReturnConfiguration() { double omega0 = Math.PI; double gamma = 0.01; DampedOscillator d = new DampedOscillator(omega0, gamma); assertAll("getters", () -> assertEquals(omega0, d.getOmega0(), 0.0, "getOmega0 should return configured omega0"), () -> assertEquals(gamma, d.getGamma(), 0.0, "getGamma should return configured gamma")); } @Test @DisplayName("Analytical displacement at t=0 returns initial amplitude * cos(phase)") void analyticalAtZeroTime() { double omega0 = 5.0; double gamma = 0.2; DampedOscillator d = new DampedOscillator(omega0, gamma); double a = 2.0; double phi = Math.PI / 3.0; double t = 0.0; double expected = a * Math.cos(phi); double actual = d.displacementAnalytical(a, phi, t); assertEquals(expected, actual, 1e-12, "Displacement at t=0 should be a * cos(phase)"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java
src/test/java/com/thealgorithms/physics/GroundToGroundProjectileMotionTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * JUnit test class for GroundToGroundProjectileMotion * * Contains unit tests for projectile motion calculations using JUnit 5 */ public class GroundToGroundProjectileMotionTest { private static final double EPSILON = 0.001; // Tolerance for floating point comparison @Test @DisplayName("Test time of flight calculation") public void testTimeOfFlight() { // Arrange double initialVelocity = 5.0; double angle = 40.0; double expectedTimeOfFlight = 0.655; // Act double flightTimeOutput = GroundToGroundProjectileMotion.timeOfFlight(initialVelocity, angle); flightTimeOutput = Math.round(flightTimeOutput * 1000.0) / 1000.0; // Assert assertEquals(expectedTimeOfFlight, flightTimeOutput, EPSILON, "Time of flight should be " + expectedTimeOfFlight + " seconds"); System.out.println("Projectile Flight Time Test"); System.out.println("Input Initial Velocity: " + initialVelocity + " m/s"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Expected Output: " + expectedTimeOfFlight + " seconds"); System.out.println("Actual Output: " + flightTimeOutput + " seconds"); System.out.println("TEST PASSED\n"); } @Test @DisplayName("Test horizontal range calculation") public void testHorizontalRange() { // Arrange double initialVelocity = 5.0; double angle = 40.0; double flightTime = 0.655; double expectedHorizontalRange = 2.51; // Act double horizontalRangeOutput = GroundToGroundProjectileMotion.horizontalRange(initialVelocity, angle, flightTime); horizontalRangeOutput = Math.round(horizontalRangeOutput * 100.0) / 100.0; // Assert assertEquals(expectedHorizontalRange, horizontalRangeOutput, EPSILON, "Horizontal range should be " + expectedHorizontalRange + " meters"); System.out.println("Projectile Horizontal Range Test"); System.out.println("Input Initial Velocity: " + initialVelocity + " m/s"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Input Time Of Flight: " + flightTime + " seconds"); System.out.println("Expected Output: " + expectedHorizontalRange + " meters"); System.out.println("Actual Output: " + horizontalRangeOutput + " meters"); System.out.println("TEST PASSED\n"); } @Test @DisplayName("Test max height calculation") public void testMaxHeight() { // Arrange double initialVelocity = 5.0; double angle = 40.0; double expectedMaxHeight = 0.527; // Updated to match actual calculation // Act double maxHeightOutput = GroundToGroundProjectileMotion.maxHeight(initialVelocity, angle); maxHeightOutput = Math.round(maxHeightOutput * 1000.0) / 1000.0; // Assert assertEquals(expectedMaxHeight, maxHeightOutput, EPSILON, "Max height should be " + expectedMaxHeight + " meters"); System.out.println("Projectile Max Height Test"); System.out.println("Input Initial Velocity: " + initialVelocity + " m/s"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Expected Output: " + expectedMaxHeight + " meters"); System.out.println("Actual Output: " + maxHeightOutput + " meters"); System.out.println("TEST PASSED\n"); } @Test @DisplayName("Test time of flight with custom gravity") public void testTimeOfFlightWithCustomGravity() { // Arrange double initialVelocity = 10.0; double angle = 45.0; double customGravity = 1.62; // Moon gravity (m/s^2) // Act double flightTime = GroundToGroundProjectileMotion.timeOfFlight(initialVelocity, angle, customGravity); // Assert assertTrue(flightTime > 0, "Flight time should be positive"); assertTrue(flightTime > 8.0, "Flight time on moon should be longer than on Earth"); System.out.println("Custom Gravity Test (Moon)"); System.out.println("Input Initial Velocity: " + initialVelocity + " m/s"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Gravity: " + customGravity + " m/s^2"); System.out.println("Flight Time: " + flightTime + " seconds"); System.out.println("TEST PASSED\n"); } @Test @DisplayName("Test projectile at 90 degrees (straight up)") public void testVerticalProjectile() { // Arrange double initialVelocity = 20.0; double angle = 90.0; // Act double horizontalRange = GroundToGroundProjectileMotion.horizontalRange(initialVelocity, angle, 1.0); // Assert assertEquals(0.0, horizontalRange, EPSILON, "Horizontal range should be zero for vertical launch"); System.out.println("Vertical Projectile Test"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Horizontal Range: " + horizontalRange + " meters"); System.out.println("TEST PASSED\n"); } @Test @DisplayName("Test projectile at 0 degrees (horizontal)") public void testHorizontalProjectile() { // Arrange double initialVelocity = 15.0; double angle = 0.0; // Act double maxHeight = GroundToGroundProjectileMotion.maxHeight(initialVelocity, angle); // Assert assertEquals(0.0, maxHeight, EPSILON, "Max height should be zero for horizontal launch"); System.out.println("Horizontal Projectile Test"); System.out.println("Input Angle: " + angle + " degrees"); System.out.println("Max Height: " + maxHeight + " meters"); System.out.println("TEST PASSED\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/physics/CoulombsLawTest.java
src/test/java/com/thealgorithms/physics/CoulombsLawTest.java
package com.thealgorithms.physics; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for the CoulombsLaw utility class. */ final class CoulombsLawTest { // A small tolerance (delta) for comparing floating-point numbers private static final double DELTA = 1e-9; private static final double K = CoulombsLaw.COULOMBS_CONSTANT; @Test @DisplayName("Test repulsive force between two charges on the x-axis") void testSimpleRepulsiveForce() { // Two positive 1C charges, 1 meter apart. // Force on q2 should be F = K*1*1 / 1^2 = K, directed away from q1 (positive x) double[] forceOnB = CoulombsLaw.calculateForceVector(1.0, 0, 0, 1.0, 1, 0); assertArrayEquals(new double[] {K, 0.0}, forceOnB, DELTA); // Force on q1 should be equal and opposite (negative x) double[] forceOnA = CoulombsLaw.calculateForceVector(1.0, 1, 0, 1.0, 0, 0); assertArrayEquals(new double[] {-K, 0.0}, forceOnA, DELTA); } @Test @DisplayName("Test attractive force between two charges on the x-axis") void testSimpleAttractiveForce() { // One positive 1C, one negative -1C, 1 meter apart. // Force on q2 should be F = K*1*(-1) / 1^2 = -K, directed toward q1 (negative x) double[] forceOnB = CoulombsLaw.calculateForceVector(1.0, 0, 0, -1.0, 1, 0); assertArrayEquals(new double[] {-K, 0.0}, forceOnB, DELTA); } @Test @DisplayName("Test electrostatic force in a 2D plane (repulsive)") void test2DRepulsiveForce() { // q1 at (0,0) with charge +2C // q2 at (3,4) with charge +1C // Distance is 5 meters. double magnitude = K * 2.0 * 1.0 / 25.0; // 2K/25 // Unit vector from 1 to 2 is (3/5, 4/5) double expectedFx = magnitude * (3.0 / 5.0); // 6K / 125 double expectedFy = magnitude * (4.0 / 5.0); // 8K / 125 double[] forceOnB = CoulombsLaw.calculateForceVector(2.0, 0, 0, 1.0, 3, 4); assertArrayEquals(new double[] {expectedFx, expectedFy}, forceOnB, DELTA); } @Test @DisplayName("Test overlapping charges should result in zero force") void testOverlappingCharges() { double[] force = CoulombsLaw.calculateForceVector(1.0, 1.5, -2.5, -1.0, 1.5, -2.5); assertArrayEquals(new double[] {0.0, 0.0}, force, DELTA); } @Test @DisplayName("Test circular orbit velocity with simple values") void testCircularOrbitVelocity() { // v = sqrt( (K*1*1 / 1^2) * 1 / 1 ) = sqrt(K) double velocity = CoulombsLaw.calculateCircularOrbitVelocity(1.0, 1.0, 1.0, 1.0); assertEquals(Math.sqrt(K), velocity, DELTA); } @Test @DisplayName("Test orbital velocity for a Hydrogen atom (Bohr model)") void testHydrogenAtomVelocity() { // Charge of a proton double protonCharge = 1.602176634e-19; // Charge of an electron double electronCharge = -1.602176634e-19; // Mass of an electron double electronMass = 9.1093837e-31; // Bohr radius (avg distance) double bohrRadius = 5.29177e-11; double expectedVelocity = 2.1876917e6; double velocity = CoulombsLaw.calculateCircularOrbitVelocity(protonCharge, electronCharge, electronMass, bohrRadius); // Use a wider delta for this real-world calculation assertEquals(expectedVelocity, velocity, 1.0); } @Test @DisplayName("Test invalid inputs for orbital velocity throw exception") void testInvalidOrbitalVelocityInputs() { // Non-positive mass assertThrows(IllegalArgumentException.class, () -> CoulombsLaw.calculateCircularOrbitVelocity(1, 1, 0, 100)); assertThrows(IllegalArgumentException.class, () -> CoulombsLaw.calculateCircularOrbitVelocity(1, 1, -1, 100)); // Non-positive radius assertThrows(IllegalArgumentException.class, () -> CoulombsLaw.calculateCircularOrbitVelocity(1, 1, 1, 0)); assertThrows(IllegalArgumentException.class, () -> CoulombsLaw.calculateCircularOrbitVelocity(1, 1, 1, -100)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/MapReduceTest.java
src/test/java/com/thealgorithms/misc/MapReduceTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class MapReduceTest { @ParameterizedTest @CsvSource({"'hello world', 'hello: 1,world: 1'", "'one one two', 'one: 2,two: 1'", "'a a a a', 'a: 4'", "' spaced out ', 'spaced: 1,out: 1'"}) void testCountWordFrequencies(String input, String expected) { String result = MapReduce.countWordFrequencies(input); 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/misc/PalindromeSinglyLinkedListTest.java
src/test/java/com/thealgorithms/misc/PalindromeSinglyLinkedListTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.lists.SinglyLinkedList; import org.junit.jupiter.api.Test; public class PalindromeSinglyLinkedListTest { // Stack-based tests @Test public void testWithEmptyList() { assertTrue(PalindromeSinglyLinkedList.isPalindrome(new SinglyLinkedList())); } @Test public void testWithSingleElement() { var exampleList = new SinglyLinkedList(); exampleList.insert(100); assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } @Test public void testWithListWithOddLengthPositive() { var exampleList = new SinglyLinkedList(); exampleList.insert(1); exampleList.insert(2); exampleList.insert(1); assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } @Test public void testWithListWithOddLengthPositive2() { var exampleList = new SinglyLinkedList(); exampleList.insert(3); exampleList.insert(2); exampleList.insert(1); exampleList.insert(2); exampleList.insert(3); assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } @Test public void testWithListWithEvenLengthPositive() { var exampleList = new SinglyLinkedList(); exampleList.insert(10); exampleList.insert(20); exampleList.insert(20); exampleList.insert(10); assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } @Test public void testWithListWithOddLengthNegative() { var exampleList = new SinglyLinkedList(); exampleList.insert(1); exampleList.insert(2); exampleList.insert(2); assertFalse(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } @Test public void testWithListWithEvenLengthNegative() { var exampleList = new SinglyLinkedList(); exampleList.insert(10); exampleList.insert(20); exampleList.insert(20); exampleList.insert(20); assertFalse(PalindromeSinglyLinkedList.isPalindrome(exampleList)); } // Optimized approach tests @Test public void testOptimisedWithEmptyList() { assertTrue(PalindromeSinglyLinkedList.isPalindromeOptimised(null)); } @Test public void testOptimisedWithSingleElement() { PalindromeSinglyLinkedList.Node node = new PalindromeSinglyLinkedList.Node(100); assertTrue(PalindromeSinglyLinkedList.isPalindromeOptimised(node)); } @Test public void testOptimisedWithOddLengthPositive() { PalindromeSinglyLinkedList.Node node1 = new PalindromeSinglyLinkedList.Node(1); PalindromeSinglyLinkedList.Node node2 = new PalindromeSinglyLinkedList.Node(2); PalindromeSinglyLinkedList.Node node3 = new PalindromeSinglyLinkedList.Node(1); node1.next = node2; node2.next = node3; assertTrue(PalindromeSinglyLinkedList.isPalindromeOptimised(node1)); } @Test public void testOptimisedWithOddLengthPositive2() { PalindromeSinglyLinkedList.Node node1 = new PalindromeSinglyLinkedList.Node(3); PalindromeSinglyLinkedList.Node node2 = new PalindromeSinglyLinkedList.Node(2); PalindromeSinglyLinkedList.Node node3 = new PalindromeSinglyLinkedList.Node(1); PalindromeSinglyLinkedList.Node node4 = new PalindromeSinglyLinkedList.Node(2); PalindromeSinglyLinkedList.Node node5 = new PalindromeSinglyLinkedList.Node(3); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; assertTrue(PalindromeSinglyLinkedList.isPalindromeOptimised(node1)); } @Test public void testOptimisedWithEvenLengthPositive() { PalindromeSinglyLinkedList.Node node1 = new PalindromeSinglyLinkedList.Node(10); PalindromeSinglyLinkedList.Node node2 = new PalindromeSinglyLinkedList.Node(20); PalindromeSinglyLinkedList.Node node3 = new PalindromeSinglyLinkedList.Node(20); PalindromeSinglyLinkedList.Node node4 = new PalindromeSinglyLinkedList.Node(10); node1.next = node2; node2.next = node3; node3.next = node4; assertTrue(PalindromeSinglyLinkedList.isPalindromeOptimised(node1)); } @Test public void testOptimisedWithOddLengthNegative() { PalindromeSinglyLinkedList.Node node1 = new PalindromeSinglyLinkedList.Node(1); PalindromeSinglyLinkedList.Node node2 = new PalindromeSinglyLinkedList.Node(2); PalindromeSinglyLinkedList.Node node3 = new PalindromeSinglyLinkedList.Node(2); node1.next = node2; node2.next = node3; assertFalse(PalindromeSinglyLinkedList.isPalindromeOptimised(node1)); } @Test public void testOptimisedWithEvenLengthNegative() { PalindromeSinglyLinkedList.Node node1 = new PalindromeSinglyLinkedList.Node(10); PalindromeSinglyLinkedList.Node node2 = new PalindromeSinglyLinkedList.Node(20); PalindromeSinglyLinkedList.Node node3 = new PalindromeSinglyLinkedList.Node(20); PalindromeSinglyLinkedList.Node node4 = new PalindromeSinglyLinkedList.Node(20); node1.next = node2; node2.next = node3; node3.next = node4; assertFalse(PalindromeSinglyLinkedList.isPalindromeOptimised(node1)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/ShuffleArrayTest.java
src/test/java/com/thealgorithms/misc/ShuffleArrayTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class ShuffleArrayTest { @Test void testShuffleBasic() { int[] arr = {1, 2, 3, 4, 5}; int[] originalArr = arr.clone(); // Clone original array for comparison ShuffleArray.shuffle(arr); // Check that the shuffled array is not the same as the original assertNotEquals(originalArr, arr); } @Test void testShuffleSingleElement() { int[] arr = {1}; int[] originalArr = arr.clone(); ShuffleArray.shuffle(arr); // Check that the shuffled array is the same as the original assertArrayEquals(originalArr, arr); } @Test void testShuffleTwoElements() { int[] arr = {1, 2}; int[] originalArr = arr.clone(); ShuffleArray.shuffle(arr); // Check that the shuffled array is not the same as the original assertNotEquals(originalArr, arr); // Check that the shuffled array still contains the same elements assertTrue(arr[0] == 1 || arr[0] == 2); assertTrue(arr[1] == 1 || arr[1] == 2); } @Test void testShuffleEmptyArray() { int[] arr = {}; int[] originalArr = arr.clone(); ShuffleArray.shuffle(arr); // Check that the shuffled array is the same as the original (still empty) assertArrayEquals(originalArr, arr); } @Test void testShuffleLargeArray() { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] originalArr = arr.clone(); ShuffleArray.shuffle(arr); // Check that the shuffled array is not the same as the original assertNotEquals(originalArr, arr); } @Test void testShuffleRetainsElements() { int[] arr = {1, 2, 3, 4, 5}; ShuffleArray.shuffle(arr); // Check that the shuffled array contains the same elements assertTrue(arr.length == 5); for (int i = 1; i <= 5; i++) { assertTrue(contains(arr, i)); } } private boolean contains(int[] arr, int value) { for (int num : arr) { if (num == value) { return true; } } return 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/misc/SparsityTest.java
src/test/java/com/thealgorithms/misc/SparsityTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class SparsityTest { private static final double DELTA = 1e-9; @ParameterizedTest(name = "Test case {index}: {2}") @MethodSource("provideTestCases") public void testSparsity(double[][] matrix, double expectedSparsity, String description) { assertEquals(expectedSparsity, Sparsity.sparsity(matrix), DELTA, description); } private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, 1.0, "Matrix with all zero elements"), Arguments.of(new double[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 0.0, "Matrix with no zero elements"), Arguments.of(new double[][] {{0, 2, 0}, {4, 0, 6}, {0, 8, 0}}, 5.0 / 9.0, "Matrix with mixed elements"), Arguments.of(new double[][] {{0, 1, 0, 2, 0}}, 3.0 / 5.0, "Single-row matrix"), Arguments.of(new double[][] {{1}, {0}, {0}, {2}}, 2.0 / 4.0, "Single-column matrix"), Arguments.of(new double[][] {{0}}, 1.0, "Matrix with a single zero element"), Arguments.of(new double[][] {{5}}, 0.0, "Matrix with a single non-zero element")); } @ParameterizedTest(name = "Test case {index}: {1}") @MethodSource("provideExceptionTestCases") public void testSparsityExceptions(double[][] matrix, String description) { assertThrows(IllegalArgumentException.class, () -> Sparsity.sparsity(matrix), description); } private static Stream<Arguments> provideExceptionTestCases() { return Stream.of(Arguments.of(new double[][] {}, "Empty matrix should throw 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/misc/TwoSumProblemTest.java
src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Test; /** * Test case for Two sum Problem. * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public class TwoSumProblemTest { @Test void testTwoSumExists() { final int[] values = new int[] {2, 7, 11, 15}; final int target = 9; final var expected = Pair.of(0, 1); // values[0] + values[1] = 2 + 7 = 9 assertEquals(expected, TwoSumProblem.twoSum(values, target).get()); } @Test void testTwoSumNoSolution() { final int[] values = new int[] {2, 7, 11, 15}; final int target = 3; assertFalse(TwoSumProblem.twoSum(values, target).isPresent()); } @Test void testTwoSumMultipleSolutions() { final int[] values = {3, 3}; final int target = 6; final var expected = Pair.of(0, 1); // values[0] + values[1] = 3 + 3 = 6 assertEquals(expected, TwoSumProblem.twoSum(values, target).get()); } @Test void testTwoSumMultipleSolution() { final int[] values = {3, 4, 3, 3}; final int target = 6; final var expected = Pair.of(0, 2); // values[0] + values[2] = 3 + 3 = 6 assertEquals(expected, TwoSumProblem.twoSum(values, target).get()); } @Test void testTwoSumNegativeNumbers() { final int[] values = {-1, -2, -3, -4, -5}; final int target = -8; final var expected = Pair.of(2, 4); // values[2] + values[4] = -3 + (-5) = -8 assertEquals(expected, TwoSumProblem.twoSum(values, target).get()); } @Test void testTwoSumNoSolutionDuplicatedInputs() { final int[] values = {0, 0, 0}; final int target = 100; assertFalse(TwoSumProblem.twoSum(values, target).isPresent()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java
src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class RangeInSortedArrayTest { @ParameterizedTest(name = "Test case {index}: {3}") @MethodSource("provideSortedRangeTestCases") void testSortedRange(int[] nums, int key, int[] expectedRange, String description) { assertArrayEquals(expectedRange, RangeInSortedArray.sortedRange(nums, key), description); } private static Stream<Arguments> provideSortedRangeTestCases() { return Stream.of(Arguments.of(new int[] {1, 2, 3, 3, 3, 4, 5}, 3, new int[] {2, 4}, "Range for key 3 with multiple occurrences"), Arguments.of(new int[] {1, 2, 3, 3, 3, 4, 5}, 4, new int[] {5, 5}, "Range for key 4 with single occurrence"), Arguments.of(new int[] {0, 1, 2}, 3, new int[] {-1, -1}, "Range for non-existent key"), Arguments.of(new int[] {}, 1, new int[] {-1, -1}, "Range in empty array"), Arguments.of(new int[] {1, 1, 1, 2, 3, 4, 5, 5, 5}, 1, new int[] {0, 2}, "Range for key at start"), Arguments.of(new int[] {1, 1, 1, 2, 3, 4, 5, 5, 5}, 5, new int[] {6, 8}, "Range for key at end")); } @ParameterizedTest(name = "Test case {index}: {3}") @MethodSource("provideGetCountLessThanTestCases") void testGetCountLessThan(int[] nums, int key, int expectedCount, String description) { assertEquals(expectedCount, RangeInSortedArray.getCountLessThan(nums, key), description); } private static Stream<Arguments> provideGetCountLessThanTestCases() { return Stream.of(Arguments.of(new int[] {1, 2, 3, 3, 4, 5}, 3, 4, "Count of elements less than existing key"), Arguments.of(new int[] {1, 2, 3, 3, 4, 5}, 4, 5, "Count of elements less than non-existing key"), Arguments.of(new int[] {1, 2, 2, 3}, 5, 4, "Count with all smaller elements"), Arguments.of(new int[] {2, 3, 4, 5}, 1, 0, "Count with no smaller elements"), Arguments.of(new int[] {}, 1, 0, "Count in empty array")); } @ParameterizedTest(name = "Edge case {index}: {3}") @MethodSource("provideEdgeCasesForSortedRange") void testSortedRangeEdgeCases(int[] nums, int key, int[] expectedRange, String description) { assertArrayEquals(expectedRange, RangeInSortedArray.sortedRange(nums, key), description); } private static Stream<Arguments> provideEdgeCasesForSortedRange() { return Stream.of(Arguments.of(new int[] {5, 5, 5, 5, 5}, 5, new int[] {0, 4}, "All elements same as key"), Arguments.of(new int[] {1, 2, 3, 4, 5}, 1, new int[] {0, 0}, "Key is first element"), Arguments.of(new int[] {1, 2, 3, 4, 5}, 5, new int[] {4, 4}, "Key is last element"), Arguments.of(new int[] {1, 2, 3, 4, 5}, 0, new int[] {-1, -1}, "Key less than all elements"), Arguments.of(new int[] {1, 2, 3, 4, 5}, 6, new int[] {-1, -1}, "Key greater than all elements"), Arguments.of(new int[] {1, 2, 2, 2, 3, 3, 3, 4}, 3, new int[] {4, 6}, "Multiple occurrences spread"), Arguments.of(new int[] {2}, 2, new int[] {0, 0}, "Single element array key exists"), Arguments.of(new int[] {2}, 3, new int[] {-1, -1}, "Single element array key missing")); } @ParameterizedTest(name = "Edge case {index}: {3}") @MethodSource("provideEdgeCasesForGetCountLessThan") void testGetCountLessThanEdgeCases(int[] nums, int key, int expectedCount, String description) { assertEquals(expectedCount, RangeInSortedArray.getCountLessThan(nums, key), description); } private static Stream<Arguments> provideEdgeCasesForGetCountLessThan() { return Stream.of(Arguments.of(new int[] {1, 2, 3, 4, 5}, 0, 0, "Key less than all elements"), Arguments.of(new int[] {1, 2, 3, 4, 5}, 6, 5, "Key greater than all elements"), Arguments.of(new int[] {1}, 0, 0, "Single element greater than key")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java
src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Test case for Median Of Running Array Problem. * @author Ansh Shah (https://github.com/govardhanshah456) */ public class MedianOfRunningArrayTest { private static final String EXCEPTION_MESSAGE = "Median is undefined for an empty data set."; @Test public void testWhenInvalidInoutProvidedShouldThrowException() { var stream = new MedianOfRunningArrayInteger(); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, stream::getMedian); assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); } @Test public void testWithNegativeValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(-1); assertEquals(-1, stream.getMedian()); stream.insert(-2); assertEquals(-1, stream.getMedian()); stream.insert(-3); assertEquals(-2, stream.getMedian()); } @Test public void testWithSingleValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(-1); assertEquals(-1, stream.getMedian()); } @Test public void testWithRandomValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(10); assertEquals(10, stream.getMedian()); stream.insert(5); assertEquals(7, stream.getMedian()); stream.insert(20); assertEquals(10, stream.getMedian()); stream.insert(15); assertEquals(12, stream.getMedian()); stream.insert(25); assertEquals(15, stream.getMedian()); stream.insert(30); assertEquals(17, stream.getMedian()); stream.insert(35); assertEquals(20, stream.getMedian()); stream.insert(1); assertEquals(17, stream.getMedian()); } @Test public void testWithNegativeAndPositiveValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(-1); assertEquals(-1, stream.getMedian()); stream.insert(2); assertEquals(0, stream.getMedian()); stream.insert(-3); assertEquals(-1, stream.getMedian()); } @Test public void testWithDuplicateValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(-1); assertEquals(-1, stream.getMedian()); stream.insert(-1); assertEquals(-1, stream.getMedian()); stream.insert(-1); assertEquals(-1, stream.getMedian()); } @Test public void testWithDuplicateValuesB() { var stream = new MedianOfRunningArrayInteger(); stream.insert(10); stream.insert(20); stream.insert(10); stream.insert(10); stream.insert(20); stream.insert(0); stream.insert(50); assertEquals(10, stream.getMedian()); } @Test public void testWithLargeValues() { var stream = new MedianOfRunningArrayInteger(); stream.insert(1000000); assertEquals(1000000, stream.getMedian()); stream.insert(12000); assertEquals(506000, stream.getMedian()); stream.insert(15000000); assertEquals(1000000, stream.getMedian()); stream.insert(2300000); assertEquals(1650000, stream.getMedian()); } @Test public void testWithLargeCountOfValues() { var stream = new MedianOfRunningArrayInteger(); for (int i = 1; i <= 1000; i++) { stream.insert(i); } assertEquals(500, stream.getMedian()); } @Test public void testWithThreeValuesInDescendingOrder() { var stream = new MedianOfRunningArrayInteger(); stream.insert(30); stream.insert(20); stream.insert(10); assertEquals(20, stream.getMedian()); } @Test public void testWithThreeValuesInOrder() { var stream = new MedianOfRunningArrayInteger(); stream.insert(10); stream.insert(20); stream.insert(30); assertEquals(20, stream.getMedian()); } @Test public void testWithThreeValuesNotInOrderA() { var stream = new MedianOfRunningArrayInteger(); stream.insert(30); stream.insert(10); stream.insert(20); assertEquals(20, stream.getMedian()); } @Test public void testWithThreeValuesNotInOrderB() { var stream = new MedianOfRunningArrayInteger(); stream.insert(20); stream.insert(10); stream.insert(30); assertEquals(20, stream.getMedian()); } @Test public void testWithFloatValues() { var stream = new MedianOfRunningArrayFloat(); stream.insert(20.0f); assertEquals(20.0f, stream.getMedian()); stream.insert(10.5f); assertEquals(15.25f, stream.getMedian()); stream.insert(30.0f); assertEquals(20.0f, stream.getMedian()); } @Test public void testWithByteValues() { var stream = new MedianOfRunningArrayByte(); stream.insert((byte) 120); assertEquals((byte) 120, stream.getMedian()); stream.insert((byte) -120); assertEquals((byte) 0, stream.getMedian()); stream.insert((byte) 127); assertEquals((byte) 120, stream.getMedian()); } @Test public void testWithLongValues() { var stream = new MedianOfRunningArrayLong(); stream.insert(120000000L); assertEquals(120000000L, stream.getMedian()); stream.insert(92233720368547757L); assertEquals(46116860244273878L, stream.getMedian()); } @Test public void testWithDoubleValues() { var stream = new MedianOfRunningArrayDouble(); stream.insert(12345.67891); assertEquals(12345.67891, stream.getMedian()); stream.insert(23456789.98); assertEquals(11734567.83, stream.getMedian(), .01); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java
src/test/java/com/thealgorithms/misc/ColorContrastRatioTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.Color; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class ColorContrastRatioTest { private final ColorContrastRatio colorContrastRationCalculator = new ColorContrastRatio(); static Stream<Arguments> relativeLuminanceProvider() { return Stream.of(Arguments.of(Color.BLACK, 0.0), Arguments.of(Color.WHITE, 1.0), Arguments.of(new Color(23, 103, 154), 0.12215748057375966), Arguments.of(new Color(226, 229, 248), 0.7898468477881603)); } static Stream<Arguments> contrastRatioProvider() { return Stream.of(Arguments.of(Color.BLACK, Color.WHITE, 21.0), Arguments.of(new Color(23, 103, 154), new Color(226, 229, 248), 4.878363954846178)); } @ParameterizedTest @MethodSource("relativeLuminanceProvider") void testGetRelativeLuminance(Color color, double expectedLuminance) { assertEquals(expectedLuminance, colorContrastRationCalculator.getRelativeLuminance(color), 1e-10); } @ParameterizedTest @MethodSource("contrastRatioProvider") void testGetContrastRatio(Color a, Color b, double expectedRatio) { assertEquals(expectedRatio, colorContrastRationCalculator.getContrastRatio(a, b), 1e-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/misc/PalindromePrimeTest.java
src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.Test; public class PalindromePrimeTest { @Test public void testPrimeWithPrimeNumbers() { assertTrue(PalindromePrime.prime(2), "2 should be prime"); assertTrue(PalindromePrime.prime(3), "3 should be prime"); assertTrue(PalindromePrime.prime(5), "5 should be prime"); assertTrue(PalindromePrime.prime(11), "11 should be prime"); } @Test public void testPrimeWithNonPrimeNumbers() { assertFalse(PalindromePrime.prime(1), "1 is not prime"); assertFalse(PalindromePrime.prime(4), "4 is not prime"); assertFalse(PalindromePrime.prime(9), "9 is not prime"); assertFalse(PalindromePrime.prime(15), "15 is not prime"); } @Test public void testReverse() { assertEquals(123, PalindromePrime.reverse(321), "Reverse of 321 should be 123"); assertEquals(7, PalindromePrime.reverse(7), "Reverse of 7 should be 7"); assertEquals(1221, PalindromePrime.reverse(1221), "Reverse of 1221 should be 1221"); } @Test public void testGeneratePalindromePrimes() { List<Integer> result = PalindromePrime.generatePalindromePrimes(5); List<Integer> expected = List.of(2, 3, 5, 7, 11); assertEquals(expected, result, "The first 5 palindromic primes should be [2, 3, 5, 7, 11]"); } @Test public void testGeneratePalindromePrimesWithZero() { List<Integer> result = PalindromePrime.generatePalindromePrimes(0); assertTrue(result.isEmpty(), "Generating 0 palindromic primes should return an empty list"); } @Test public void testGeneratePalindromePrimesWithNegativeInput() { List<Integer> result = PalindromePrime.generatePalindromePrimes(-5); assertTrue(result.isEmpty(), "Generating a negative number of palindromic primes should return an empty list"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java
src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java
package com.thealgorithms.misc; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; 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; public class ThreeSumProblemTest { private ThreeSumProblem tsp; @BeforeEach public void setup() { tsp = new ThreeSumProblem(); } @ParameterizedTest @MethodSource("bruteForceTestProvider") public void testBruteForce(int[] nums, int target, List<List<Integer>> expected) { assertEquals(expected, tsp.bruteForce(nums, target)); } @ParameterizedTest @MethodSource("twoPointerTestProvider") public void testTwoPointer(int[] nums, int target, List<List<Integer>> expected) { assertEquals(expected, tsp.twoPointer(nums, target)); } @ParameterizedTest @MethodSource("hashMapTestProvider") public void testHashMap(int[] nums, int target, List<List<Integer>> expected) { assertEquals(expected, tsp.hashMap(nums, target)); } private static Stream<Arguments> bruteForceTestProvider() { return Stream.of(Arguments.of(new int[] {1, 2, -3, 4, -2, -1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-3, -1, 4))), Arguments.of(new int[] {1, 2, 3, 4, 5}, 50, new ArrayList<>())); } private static Stream<Arguments> twoPointerTestProvider() { return Stream.of(Arguments.of(new int[] {0, -1, 2, -3, 1}, 0, Arrays.asList(Arrays.asList(-3, 1, 2), Arrays.asList(-1, 0, 1))), Arguments.of(new int[] {-5, -4, -3, -2, -1}, -10, Arrays.asList(Arrays.asList(-5, -4, -1), Arrays.asList(-5, -3, -2)))); } private static Stream<Arguments> hashMapTestProvider() { return Stream.of(Arguments.of(new int[] {1, 2, -1, -4, 3, 0}, 2, Arrays.asList(Arrays.asList(-1, 0, 3), Arrays.asList(-1, 1, 2))), Arguments.of(new int[] {5, 7, 9, 11}, 10, new ArrayList<>()), Arguments.of(new int[] {}, 0, new ArrayList<>())); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; 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 SJFSchedulingTest { private static Stream<Arguments> schedulingTestData() { return Stream.of(Arguments.of(List.of(new ProcessDetails("1", 0, 6), new ProcessDetails("2", 1, 2)), List.of("1", "2")), Arguments.of(List.of(new ProcessDetails("1", 0, 6), new ProcessDetails("2", 1, 2), new ProcessDetails("3", 4, 3), new ProcessDetails("4", 3, 1), new ProcessDetails("5", 6, 4), new ProcessDetails("6", 5, 5)), List.of("1", "4", "2", "3", "5", "6")), Arguments.of(List.of(new ProcessDetails("1", 0, 3), new ProcessDetails("2", 1, 2), new ProcessDetails("3", 2, 1)), List.of("1", "3", "2")), Arguments.of(List.of(new ProcessDetails("1", 0, 3), new ProcessDetails("2", 5, 2), new ProcessDetails("3", 9, 1)), List.of("1", "2", "3")), Arguments.of(Collections.emptyList(), List.of())); } @ParameterizedTest(name = "Test SJF schedule: {index}") @MethodSource("schedulingTestData") void testSJFScheduling(List<ProcessDetails> inputProcesses, List<String> expectedSchedule) { SJFScheduling scheduler = new SJFScheduling(inputProcesses); scheduler.scheduleProcesses(); assertEquals(expectedSchedule, scheduler.getSchedule()); } @Test @DisplayName("Test sorting by arrival order") void testProcessArrivalOrderIsSorted() { List<ProcessDetails> processes = List.of(new ProcessDetails("1", 0, 6), new ProcessDetails("2", 1, 2), new ProcessDetails("4", 3, 1), new ProcessDetails("3", 4, 3), new ProcessDetails("6", 5, 5), new ProcessDetails("5", 6, 4)); SJFScheduling scheduler = new SJFScheduling(processes); List<String> actualOrder = scheduler.getProcesses().stream().map(ProcessDetails::getProcessId).toList(); assertEquals(List.of("1", "2", "4", "3", "6", "5"), actualOrder); } @Test void testSchedulingEmptyList() { SJFScheduling scheduler = new SJFScheduling(Collections.emptyList()); scheduler.scheduleProcesses(); assertTrue(scheduler.getSchedule().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/scheduling/SRTFSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/SRTFSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import org.junit.jupiter.api.Test; class SRTFSchedulingTest { ArrayList<ProcessDetails> processes; public void initialization() { processes = new ArrayList<>(); processes.add(new ProcessDetails("4", 0, 3)); processes.add(new ProcessDetails("3", 1, 8)); processes.add(new ProcessDetails("1", 2, 6)); processes.add(new ProcessDetails("5", 4, 4)); processes.add(new ProcessDetails("2", 5, 2)); } @Test public void constructor() { initialization(); SRTFScheduling s = new SRTFScheduling(processes); assertEquals(3, s.processes.get(0).getBurstTime()); assertEquals(8, s.processes.get(1).getBurstTime()); assertEquals(6, s.processes.get(2).getBurstTime()); assertEquals(4, s.processes.get(3).getBurstTime()); assertEquals(2, s.processes.get(4).getBurstTime()); } @Test void evaluateScheduling() { initialization(); SRTFScheduling s = new SRTFScheduling(processes); s.evaluateScheduling(); assertEquals("4", s.ready.get(0)); assertEquals("4", s.ready.get(1)); assertEquals("4", s.ready.get(2)); assertEquals("1", s.ready.get(3)); assertEquals("5", s.ready.get(4)); assertEquals("2", s.ready.get(5)); assertEquals("2", s.ready.get(6)); assertEquals("5", s.ready.get(7)); assertEquals("5", s.ready.get(8)); assertEquals("5", s.ready.get(9)); assertEquals("1", s.ready.get(10)); assertEquals("1", s.ready.get(11)); assertEquals("1", s.ready.get(12)); assertEquals("1", s.ready.get(13)); assertEquals("1", s.ready.get(14)); assertEquals("3", s.ready.get(15)); assertEquals("3", s.ready.get(16)); assertEquals("3", s.ready.get(17)); assertEquals("3", s.ready.get(18)); assertEquals("3", s.ready.get(19)); assertEquals("3", s.ready.get(20)); assertEquals("3", s.ready.get(21)); assertEquals("3", s.ready.get(22)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/RandomSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/RandomSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import java.util.Random; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class RandomSchedulingTest { private RandomScheduling randomScheduling; private Random mockRandom; @BeforeEach public void setup() { mockRandom = mock(Random.class); // Mocking Random for predictable behavior } @Test public void testRandomOrder1() { // Arrange List<String> tasks = List.of("Task1", "Task2", "Task3"); // Mock the random sequence to control shuffling: swap 0 <-> 1, and 1 <-> 2. when(mockRandom.nextInt(anyInt())).thenReturn(1, 2, 0); randomScheduling = new RandomScheduling(tasks, mockRandom); // Act List<String> result = randomScheduling.schedule(); // Assert assertEquals(List.of("Task1", "Task2", "Task3"), result); } @Test public void testRandomOrder2() { // Arrange List<String> tasks = List.of("A", "B", "C", "D"); // Mocking predictable swaps for the sequence: [C, B, D, A] when(mockRandom.nextInt(anyInt())).thenReturn(2, 1, 3, 0); randomScheduling = new RandomScheduling(tasks, mockRandom); // Act List<String> result = randomScheduling.schedule(); // Assert assertEquals(List.of("A", "C", "B", "D"), result); } @Test public void testSingleTask() { // Arrange List<String> tasks = List.of("SingleTask"); when(mockRandom.nextInt(anyInt())).thenReturn(0); // No real shuffle randomScheduling = new RandomScheduling(tasks, mockRandom); // Act List<String> result = randomScheduling.schedule(); // Assert assertEquals(List.of("SingleTask"), result); } @Test public void testEmptyTaskList() { // Arrange List<String> tasks = List.of(); randomScheduling = new RandomScheduling(tasks, mockRandom); // Act List<String> result = randomScheduling.schedule(); // Assert assertEquals(List.of(), result); // Should return an empty list } @Test public void testSameTasksMultipleTimes() { // Arrange List<String> tasks = List.of("X", "X", "Y", "Z"); when(mockRandom.nextInt(anyInt())).thenReturn(3, 0, 1, 2); randomScheduling = new RandomScheduling(tasks, mockRandom); // Act List<String> result = randomScheduling.schedule(); // Assert assertEquals(List.of("Y", "X", "X", "Z"), 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/scheduling/FairShareSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/FairShareSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class FairShareSchedulingTest { private FairShareScheduling scheduler; @BeforeEach public void setup() { scheduler = new FairShareScheduling(); } @Test public void testAllocateResourcesSingleUser() { scheduler.addUser("User1"); scheduler.addTask("User1", 5); scheduler.allocateResources(100); Map<String, Integer> expected = Map.of("User1", 100); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesMultipleUsers() { scheduler.addUser("User1"); scheduler.addUser("User2"); scheduler.addUser("User3"); scheduler.addTask("User1", 2); scheduler.addTask("User2", 3); scheduler.addTask("User3", 5); scheduler.allocateResources(100); Map<String, Integer> expected = Map.of("User1", 20, "User2", 30, "User3", 50); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesZeroWeightUser() { scheduler.addUser("User1"); scheduler.addUser("User2"); scheduler.addTask("User2", 5); scheduler.allocateResources(100); Map<String, Integer> expected = Map.of("User1", 0, "User2", 100); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesEqualWeights() { scheduler.addUser("User1"); scheduler.addUser("User2"); scheduler.addTask("User1", 1); scheduler.addTask("User2", 1); scheduler.allocateResources(100); Map<String, Integer> expected = Map.of("User1", 50, "User2", 50); assertEquals(expected, scheduler.getAllocatedResources()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java
src/test/java/com/thealgorithms/scheduling/NonPreemptivePrioritySchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class NonPreemptivePrioritySchedulingTest { @Test public void testCalculateAverageWaitingTime() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); double expectedAvgWaitingTime = (0 + 5 + 15) / 3.0; // Waiting times: 0 for P2, 5 for P1, 15 for P3 double actualAvgWaitingTime = NonPreemptivePriorityScheduling.calculateAverageWaitingTime(processes, executionOrder); assertEquals(expectedAvgWaitingTime, actualAvgWaitingTime, 0.01, "Average waiting time should be calculated correctly."); } @Test public void testCalculateAverageTurnaroundTime() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); double expectedAvgTurnaroundTime = (5 + 15 + 23) / 3.0; // Turnaround times: 5 for P2, 15 for P1, 23 for P3 double actualAvgTurnaroundTime = NonPreemptivePriorityScheduling.calculateAverageTurnaroundTime(processes, executionOrder); assertEquals(expectedAvgTurnaroundTime, actualAvgTurnaroundTime, 0.01, "Average turnaround time should be calculated correctly."); } @Test public void testStartTimeIsCorrect() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 10, 2), // id, arrivalTime, burstTime, priority new NonPreemptivePriorityScheduling.Process(2, 0, 5, 1), new NonPreemptivePriorityScheduling.Process(3, 0, 8, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); // Check that the start time for each process is correctly set assertEquals(0, executionOrder[0].startTime, "First process (P2) should start at time 0."); // Process 2 has the highest priority assertEquals(5, executionOrder[1].startTime, "Second process (P1) should start at time 5."); assertEquals(15, executionOrder[2].startTime, "Third process (P3) should start at time 15."); } @Test public void testWithDelayedArrivalTimes() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 4, 1), // id, arrivalTime, burstTime, priority new NonPreemptivePriorityScheduling.Process(2, 2, 3, 2), new NonPreemptivePriorityScheduling.Process(3, 4, 2, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); // Test the start times considering delayed arrivals assertEquals(0, executionOrder[0].startTime, "First process (P1) should start at time 0."); assertEquals(4, executionOrder[1].startTime, "Second process (P2) should start at time 4."); // After P1 finishes assertEquals(7, executionOrder[2].startTime, "Third process (P3) should start at time 7."); // After P2 finishes } @Test public void testWithGapsInArrivals() { NonPreemptivePriorityScheduling.Process[] processes = {new NonPreemptivePriorityScheduling.Process(1, 0, 6, 2), // id, arrivalTime, burstTime, priority new NonPreemptivePriorityScheduling.Process(2, 8, 4, 1), new NonPreemptivePriorityScheduling.Process(3, 12, 5, 3)}; NonPreemptivePriorityScheduling.Process[] executionOrder = NonPreemptivePriorityScheduling.scheduleProcesses(processes); // Test the start times for processes with gaps in arrival times assertEquals(0, executionOrder[0].startTime, "First process (P1) should start at time 0."); assertEquals(8, executionOrder[1].startTime, "Second process (P2) should start at time 8."); // After P1 finishes, arrives at 8 assertEquals(12, executionOrder[2].startTime, "Third process (P3) should start at time 12."); // After P2 finishes, arrives at 12 } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; public class FCFSSchedulingTest { @Test public void testingProcesses() { List<ProcessDetails> processes = addProcessesForFCFS(); final FCFSScheduling fcfsScheduling = new FCFSScheduling(processes); // for sending to FCFS fcfsScheduling.scheduleProcesses(); assertEquals(3, processes.size()); assertEquals("P1", processes.get(0).getProcessId()); assertEquals(0, processes.get(0).getWaitingTime()); assertEquals(10, processes.get(0).getTurnAroundTimeTime()); assertEquals("P2", processes.get(1).getProcessId()); assertEquals(10, processes.get(1).getWaitingTime()); assertEquals(15, processes.get(1).getTurnAroundTimeTime()); assertEquals("P3", processes.get(2).getProcessId()); assertEquals(15, processes.get(2).getWaitingTime()); assertEquals(23, processes.get(2).getTurnAroundTimeTime()); } private List<ProcessDetails> addProcessesForFCFS() { final ProcessDetails process1 = new ProcessDetails("P1", 0, 10); final ProcessDetails process2 = new ProcessDetails("P2", 1, 5); final ProcessDetails process3 = new ProcessDetails("P3", 2, 8); final List<ProcessDetails> processDetails = new ArrayList<>(); processDetails.add(process1); processDetails.add(process2); processDetails.add(process3); return processDetails; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/GangSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class GangSchedulingTest { private GangScheduling scheduler; @BeforeEach public void setup() { scheduler = new GangScheduling(); } @Test public void testAddGangAndTask() { scheduler.addGang("Gang1"); scheduler.addTaskToGang("Gang1", "Task1"); Map<String, List<String>> expected = Map.of("Gang1", List.of("Task1")); assertEquals(expected, scheduler.getGangSchedules()); } @Test public void testMultipleGangs() { scheduler.addGang("Gang1"); scheduler.addGang("Gang2"); scheduler.addTaskToGang("Gang1", "Task1"); scheduler.addTaskToGang("Gang2", "Task2"); Map<String, List<String>> expected = Map.of("Gang1", List.of("Task1"), "Gang2", List.of("Task2")); assertEquals(expected, scheduler.getGangSchedules()); } @Test public void testGangWithMultipleTasks() { scheduler.addGang("Gang1"); scheduler.addTaskToGang("Gang1", "Task1"); scheduler.addTaskToGang("Gang1", "Task2"); Map<String, List<String>> expected = Map.of("Gang1", List.of("Task1", "Task2")); assertEquals(expected, scheduler.getGangSchedules()); } @Test public void testEmptyGangSchedule() { scheduler.addGang("Gang1"); Map<String, List<String>> expected = Map.of("Gang1", List.of()); assertEquals(expected, scheduler.getGangSchedules()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java
src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.Collection; 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; /** * Test Cases of Preemptive Priority Scheduling Algorithm * * @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi) */ class PreemptivePrioritySchedulingTest { @ParameterizedTest @MethodSource("provideProcessesAndExpectedSchedules") void testPreemptivePriorityScheduling(Collection<ProcessDetails> processes, List<String> expectedSchedule) { PreemptivePriorityScheduling scheduler = new PreemptivePriorityScheduling(processes); scheduler.scheduleProcesses(); assertEquals(expectedSchedule, scheduler.ganttChart); } static Stream<Arguments> provideProcessesAndExpectedSchedules() { return Stream.of(Arguments.of(List.of(new ProcessDetails("P1", 0, 5, 2), new ProcessDetails("P2", 1, 4, 4), new ProcessDetails("P3", 2, 2, 6), new ProcessDetails("P4", 4, 1, 8)), List.of("P1", "P2", "P3", "P3", "P4", "P2", "P2", "P2", "P1", "P1", "P1", "P1")), Arguments.of(List.of(new ProcessDetails("P1", 2, 5, 3), new ProcessDetails("P2", 5, 3, 5), new ProcessDetails("P3", 7, 1, 9)), List.of("Idle", "Idle", "P1", "P1", "P1", "P2", "P2", "P3", "P2", "P1", "P1"))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/AgingSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/AgingSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class AgingSchedulingTest { private AgingScheduling scheduler; @BeforeEach public void setup() { scheduler = new AgingScheduling(); } @Test public void testAddAndScheduleSingleTask() { scheduler.addTask("Task1", 5); assertEquals("Task1", scheduler.scheduleNext()); } @Test public void testAddMultipleTasks() { scheduler.addTask("Task1", 1); scheduler.addTask("Task2", 1); assertEquals("Task1", scheduler.scheduleNext()); assertEquals("Task2", scheduler.scheduleNext()); } @Test public void testPriorityAdjustmentWithWait() { scheduler.addTask("Task1", 1); scheduler.addTask("Task2", 1); scheduler.scheduleNext(); scheduler.scheduleNext(); assertEquals("Task1", scheduler.scheduleNext()); } @Test public void testEmptyScheduler() { assertNull(scheduler.scheduleNext()); } @Test public void testMultipleRounds() { scheduler.addTask("Task1", 1); scheduler.addTask("Task2", 2); scheduler.scheduleNext(); scheduler.scheduleNext(); assertEquals("Task1", scheduler.scheduleNext()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/MLFQSchedulerTest.java
src/test/java/com/thealgorithms/scheduling/MLFQSchedulerTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MLFQSchedulerTest { @Test void testMLFQScheduling() { // Create MLFQ Scheduler with 3 levels and time quantum for each level int[] timeQuantums = {4, 8, 12}; // Example of different quantum for each queue MLFQScheduler scheduler = new MLFQScheduler(3, timeQuantums); // Add processes to the scheduler scheduler.addProcess(new Process(1, 10, 0)); // pid=1, burstTime=10, arrivalTime=0 scheduler.addProcess(new Process(2, 15, 0)); // pid=2, burstTime=15, arrivalTime=0 scheduler.addProcess(new Process(3, 25, 0)); // pid=3, burstTime=25, arrivalTime=0 // Run the scheduler scheduler.run(); // Check current time after all processes are finished assertEquals(50, scheduler.getCurrentTime()); } @Test void testProcessCompletionOrder() { int[] timeQuantums = {3, 6, 9}; MLFQScheduler scheduler = new MLFQScheduler(3, timeQuantums); Process p1 = new Process(1, 10, 0); Process p2 = new Process(2, 5, 0); Process p3 = new Process(3, 20, 0); scheduler.addProcess(p1); scheduler.addProcess(p2); scheduler.addProcess(p3); scheduler.run(); // After running, current time should match the total burst time for all // processes assertEquals(35, scheduler.getCurrentTime()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java
src/test/java/com/thealgorithms/scheduling/JobSchedulingWithDeadlineTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class JobSchedulingWithDeadlineTest { @Test void testJobSequencingWithDeadlines1() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 4, 20), new JobSchedulingWithDeadline.Job(2, 1, 1, 10), new JobSchedulingWithDeadline.Job(3, 1, 1, 40), new JobSchedulingWithDeadline.Job(4, 1, 1, 30)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); assertArrayEquals(new int[] {2, 60}, result); // Expected output: 2 jobs, 60 profit } @Test void testJobSequencingWithDeadlines2() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 2, 100), new JobSchedulingWithDeadline.Job(2, 1, 1, 19), new JobSchedulingWithDeadline.Job(3, 1, 2, 27), new JobSchedulingWithDeadline.Job(4, 1, 1, 25), new JobSchedulingWithDeadline.Job(5, 1, 1, 15)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); assertArrayEquals(new int[] {2, 127}, result); // Expected output: 2 jobs, 127 profit } @Test void testJobSequencingWithDeadlinesWithArrivalTimes() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 2, 5, 50), new JobSchedulingWithDeadline.Job(2, 3, 4, 60), new JobSchedulingWithDeadline.Job(3, 1, 3, 20)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); assertArrayEquals(new int[] {3, 130}, result); // All 3 jobs fit within their deadlines } @Test void testJobSequencingWithDeadlinesNoJobs() { JobSchedulingWithDeadline.Job[] jobs = {}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); assertArrayEquals(new int[] {0, 0}, result); // No jobs, 0 profit } @Test void testJobSequencingWithDeadlinesSingleJob() { JobSchedulingWithDeadline.Job[] jobs = {new JobSchedulingWithDeadline.Job(1, 1, 1, 50)}; int[] result = JobSchedulingWithDeadline.jobSequencingWithDeadlines(jobs); assertArrayEquals(new int[] {1, 50}, result); // 1 job scheduled, 50 profit } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/SelfAdjustingSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/SelfAdjustingSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SelfAdjustingSchedulingTest { private SelfAdjustingScheduling scheduler; @BeforeEach public void setup() { scheduler = new SelfAdjustingScheduling(); } @Test public void testAddAndScheduleSingleTask() { scheduler.addTask("Task1", 5); assertEquals("Task1", scheduler.scheduleNext()); } @Test public void testAddMultipleTasks() { scheduler.addTask("Task1", 5); scheduler.addTask("Task2", 1); scheduler.addTask("Task3", 3); assertEquals("Task2", scheduler.scheduleNext()); assertEquals("Task2", scheduler.scheduleNext()); assertEquals("Task3", scheduler.scheduleNext()); } @Test public void testPriorityAdjustment() { scheduler.addTask("Task1", 1); scheduler.addTask("Task2", 1); scheduler.scheduleNext(); scheduler.scheduleNext(); scheduler.scheduleNext(); assertEquals("Task2", scheduler.scheduleNext()); } @Test public void testEmptyScheduler() { assertNull(scheduler.scheduleNext()); } @Test public void testTaskReschedulingAfterWait() { scheduler.addTask("Task1", 1); scheduler.addTask("Task2", 2); scheduler.scheduleNext(); scheduler.scheduleNext(); assertEquals("Task1", scheduler.scheduleNext()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; class RRSchedulingTest { @Test public void testingProcesses() { List<ProcessDetails> processes = addProcessesForRR(); final RRScheduling rrScheduling = new RRScheduling(processes, 4); // for sending to RR with quantum value 4 rrScheduling.scheduleProcesses(); assertEquals(6, processes.size()); assertEquals("P1", processes.get(0).getProcessId()); assertEquals(12, processes.get(0).getWaitingTime()); assertEquals(17, processes.get(0).getTurnAroundTimeTime()); assertEquals("P2", processes.get(1).getProcessId()); assertEquals(16, processes.get(1).getWaitingTime()); assertEquals(22, processes.get(1).getTurnAroundTimeTime()); assertEquals("P3", processes.get(2).getProcessId()); assertEquals(6, processes.get(2).getWaitingTime()); assertEquals(9, processes.get(2).getTurnAroundTimeTime()); assertEquals("P4", processes.get(3).getProcessId()); assertEquals(8, processes.get(3).getWaitingTime()); assertEquals(9, processes.get(3).getTurnAroundTimeTime()); assertEquals("P5", processes.get(4).getProcessId()); assertEquals(15, processes.get(4).getWaitingTime()); assertEquals(20, processes.get(4).getTurnAroundTimeTime()); assertEquals("P6", processes.get(5).getProcessId()); assertEquals(11, processes.get(5).getWaitingTime()); assertEquals(15, processes.get(5).getTurnAroundTimeTime()); } private List<ProcessDetails> addProcessesForRR() { final ProcessDetails process1 = new ProcessDetails("P1", 0, 5); final ProcessDetails process2 = new ProcessDetails("P2", 1, 6); final ProcessDetails process3 = new ProcessDetails("P3", 2, 3); final ProcessDetails process4 = new ProcessDetails("P4", 3, 1); final ProcessDetails process5 = new ProcessDetails("P5", 4, 5); final ProcessDetails process6 = new ProcessDetails("P6", 6, 4); final List<ProcessDetails> processDetails = new ArrayList<>(); processDetails.add(process1); processDetails.add(process2); processDetails.add(process3); processDetails.add(process4); processDetails.add(process5); processDetails.add(process6); return processDetails; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/EDFSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class EDFSchedulingTest { private List<EDFScheduling.Process> processes; @BeforeEach public void setup() { processes = createProcesses(); } @Test public void testEDFScheduling() { EDFScheduling edfScheduling = new EDFScheduling(processes); List<EDFScheduling.Process> executedProcesses = edfScheduling.scheduleProcesses(); // Assert the correct number of processes assertEquals(3, executedProcesses.size()); // Assert that processes are executed in order of earliest deadline first EDFScheduling.Process process1 = executedProcesses.get(0); assertEquals("P2", process1.getProcessId()); assertEquals(0, process1.getWaitingTime()); assertEquals(3, process1.getTurnAroundTime()); EDFScheduling.Process process2 = executedProcesses.get(1); assertEquals("P1", process2.getProcessId()); assertEquals(3, process2.getWaitingTime()); assertEquals(10, process2.getTurnAroundTime()); EDFScheduling.Process process3 = executedProcesses.get(2); assertEquals("P3", process3.getProcessId()); assertEquals(10, process3.getWaitingTime()); assertEquals(18, process3.getTurnAroundTime()); } @Test public void testProcessMissedDeadline() { // Modify the deadline of a process to ensure it will miss its deadline processes.get(1).setTurnAroundTime(5); // Set P1's deadline to 5 (which it will miss) EDFScheduling edfScheduling = new EDFScheduling(processes); edfScheduling.scheduleProcesses(); // Check if the process with ID "P1" missed its deadline assertEquals("P1", processes.get(1).getProcessId()); } private List<EDFScheduling.Process> createProcesses() { // Process ID, Burst Time, Deadline EDFScheduling.Process process1 = new EDFScheduling.Process("P1", 7, 10); // 7 burst time, 10 deadline EDFScheduling.Process process2 = new EDFScheduling.Process("P2", 3, 5); // 3 burst time, 5 deadline EDFScheduling.Process process3 = new EDFScheduling.Process("P3", 8, 18); // 8 burst time, 18 deadline List<EDFScheduling.Process> processes = new ArrayList<>(); processes.add(process1); processes.add(process2); processes.add(process3); return processes; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/SlackTimeSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SlackTimeSchedulingTest { private SlackTimeScheduling scheduler; @BeforeEach public void setup() { scheduler = new SlackTimeScheduling(); } @Test public void testAddAndScheduleSingleTask() { scheduler.addTask("Task1", 2, 5); List<String> expected = List.of("Task1"); assertEquals(expected, scheduler.scheduleTasks()); } @Test public void testScheduleMultipleTasks() { scheduler.addTask("Task1", 2, 5); scheduler.addTask("Task2", 1, 4); scheduler.addTask("Task3", 3, 7); List<String> expected = List.of("Task1", "Task2", "Task3"); assertEquals(expected, scheduler.scheduleTasks()); } @Test public void testScheduleTasksWithSameSlackTime() { scheduler.addTask("Task1", 2, 5); scheduler.addTask("Task2", 3, 6); scheduler.addTask("Task3", 1, 4); List<String> expected = List.of("Task1", "Task2", "Task3"); assertEquals(expected, scheduler.scheduleTasks()); } @Test public void testEmptyScheduler() { List<String> expected = List.of(); assertEquals(expected, scheduler.scheduleTasks()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/ProportionalFairSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class ProportionalFairSchedulingTest { private ProportionalFairScheduling scheduler; @BeforeEach public void setup() { scheduler = new ProportionalFairScheduling(); } @Test public void testAllocateResourcesSingleProcess() { scheduler.addProcess("Process1", 5); scheduler.allocateResources(100); List<String> expected = List.of("Process1: 100"); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesMultipleProcesses() { scheduler.addProcess("Process1", 2); scheduler.addProcess("Process2", 3); scheduler.addProcess("Process3", 5); scheduler.allocateResources(100); List<String> expected = List.of("Process1: 20", "Process2: 30", "Process3: 50"); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesZeroWeightProcess() { scheduler.addProcess("Process1", 0); scheduler.addProcess("Process2", 5); scheduler.allocateResources(100); List<String> expected = List.of("Process1: 0", "Process2: 100"); assertEquals(expected, scheduler.getAllocatedResources()); } @Test public void testAllocateResourcesEqualWeights() { scheduler.addProcess("Process1", 1); scheduler.addProcess("Process2", 1); scheduler.allocateResources(100); List<String> expected = List.of("Process1: 50", "Process2: 50"); assertEquals(expected, scheduler.getAllocatedResources()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/HighestResponseRatioNextSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/HighestResponseRatioNextSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class HighestResponseRatioNextSchedulingTest { @Test public void testCalculateTurnAroundTime() { String[] processNames = {"A", "B", "C"}; int[] arrivalTimes = {0, 2, 4}; int[] burstTimes = {3, 1, 2}; int noOfProcesses = 3; int[] expectedTurnAroundTimes = {3, 2, 2}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times do not match"); } @Test public void testCalculateWaitingTime() { int[] turnAroundTimes = {3, 1, 5}; int[] burstTimes = {3, 1, 2}; int[] expectedWaitingTimes = {0, 0, 3}; int[] actualWaitingTimes = HighestResponseRatioNextScheduling.calculateWaitingTime(turnAroundTimes, burstTimes); assertArrayEquals(expectedWaitingTimes, actualWaitingTimes, "Waiting Times do not match"); } @Test public void testCompleteSchedulingScenario() { String[] processNames = {"A", "B", "C"}; int[] arrivalTimes = {0, 1, 2}; int[] burstTimes = {5, 2, 1}; int[] expectedTurnAroundTimes = {5, 7, 4}; int[] turnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, processNames.length); assertArrayEquals(expectedTurnAroundTimes, turnAroundTimes, "Turn Around Times do not match"); int[] expectedWaitingTimes = {0, 5, 3}; int[] waitingTimes = HighestResponseRatioNextScheduling.calculateWaitingTime(turnAroundTimes, burstTimes); assertArrayEquals(expectedWaitingTimes, waitingTimes, "Waiting Times do not match"); } @Test public void testZeroProcesses() { String[] processNames = {}; int[] arrivalTimes = {}; int[] burstTimes = {}; int noOfProcesses = 0; int[] expectedTurnAroundTimes = {}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times for zero processes should be an empty array"); } @Test public void testAllProcessesArriveAtSameTime() { String[] processNames = {"A", "B", "C", "D"}; int[] arrivalTimes = {0, 0, 0, 0}; int[] burstTimes = {4, 3, 1, 2}; int noOfProcesses = 4; int[] expectedTurnAroundTimes = {4, 10, 5, 7}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times for processes arriving at the same time do not match"); } @Test public void testProcessesWithZeroBurstTime() { String[] processNames = {"A", "B", "C"}; int[] arrivalTimes = {0, 1, 2}; int[] burstTimes = {3, 0, 2}; int noOfProcesses = 3; int[] expectedTurnAroundTimes = {3, 2, 3}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times for processes with zero burst time do not match"); } @Test public void testProcessesWithLargeGapsBetweenArrivals() { String[] processNames = {"A", "B", "C"}; int[] arrivalTimes = {0, 100, 200}; int[] burstTimes = {10, 10, 10}; int noOfProcesses = 3; int[] expectedTurnAroundTimes = {10, 10, 10}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times for processes with large gaps between arrivals do not match"); } @Test public void testProcessesWithVeryLargeBurstTimes() { String[] processNames = {"A", "B"}; int[] arrivalTimes = {0, 1}; int[] burstTimes = {Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 2}; int noOfProcesses = 2; int[] expectedTurnAroundTimes = {Integer.MAX_VALUE / 2, Integer.MAX_VALUE - 2}; int[] actualTurnAroundTimes = HighestResponseRatioNextScheduling.calculateTurnAroundTime(processNames, arrivalTimes, burstTimes, noOfProcesses); assertArrayEquals(expectedTurnAroundTimes, actualTurnAroundTimes, "Turn Around Times for processes with very large burst times do not match"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/MultiAgentSchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class MultiAgentSchedulingTest { private MultiAgentScheduling scheduler; @BeforeEach public void setup() { scheduler = new MultiAgentScheduling(); } @Test public void testAddAgentAndAssignTask() { scheduler.addAgent("Agent1"); scheduler.assignTask("Agent1", "Task1"); Map<String, List<String>> expected = Map.of("Agent1", List.of("Task1")); assertEquals(expected, scheduler.getScheduledTasks()); } @Test public void testMultipleAgentsWithTasks() { scheduler.addAgent("Agent1"); scheduler.addAgent("Agent2"); scheduler.assignTask("Agent1", "Task1"); scheduler.assignTask("Agent2", "Task2"); Map<String, List<String>> expected = Map.of("Agent1", List.of("Task1"), "Agent2", List.of("Task2")); assertEquals(expected, scheduler.getScheduledTasks()); } @Test public void testAgentWithMultipleTasks() { scheduler.addAgent("Agent1"); scheduler.assignTask("Agent1", "Task1"); scheduler.assignTask("Agent1", "Task2"); Map<String, List<String>> expected = Map.of("Agent1", List.of("Task1", "Task2")); assertEquals(expected, scheduler.getScheduledTasks()); } @Test public void testEmptyAgentSchedule() { scheduler.addAgent("Agent1"); Map<String, List<String>> expected = Map.of("Agent1", List.of()); assertEquals(expected, scheduler.getScheduledTasks()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java
src/test/java/com/thealgorithms/scheduling/LotterySchedulingTest.java
package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class LotterySchedulingTest { private Random mockRandom; @BeforeEach public void setup() { mockRandom = mock(Random.class); } @Test public void testLotterySchedulingWithMockedRandom() { List<LotteryScheduling.Process> processes = createProcesses(); LotteryScheduling lotteryScheduling = new LotteryScheduling(processes, mockRandom); // Mock the sequence of random numbers (winning tickets) // This sequence ensures that P1 (10 tickets), P3 (8 tickets), and P2 (5 tickets) are selected. when(mockRandom.nextInt(23)).thenReturn(5, 18, 11); // winning tickets for P1, P3, and P2 List<LotteryScheduling.Process> executedProcesses = lotteryScheduling.scheduleProcesses(); assertEquals(3, executedProcesses.size()); // Assert the process execution order and properties LotteryScheduling.Process process1 = executedProcesses.get(0); assertEquals("P1", process1.getProcessId()); assertEquals(0, process1.getWaitingTime()); assertEquals(10, process1.getTurnAroundTime()); LotteryScheduling.Process process2 = executedProcesses.get(1); assertEquals("P2", process2.getProcessId()); assertEquals(10, process2.getWaitingTime()); assertEquals(15, process2.getTurnAroundTime()); LotteryScheduling.Process process3 = executedProcesses.get(2); assertEquals("P3", process3.getProcessId()); assertEquals(15, process3.getWaitingTime()); assertEquals(23, process3.getTurnAroundTime()); } private List<LotteryScheduling.Process> createProcesses() { LotteryScheduling.Process process1 = new LotteryScheduling.Process("P1", 10, 10); // 10 tickets LotteryScheduling.Process process2 = new LotteryScheduling.Process("P2", 5, 5); // 5 tickets LotteryScheduling.Process process3 = new LotteryScheduling.Process("P3", 8, 8); // 8 tickets List<LotteryScheduling.Process> processes = new ArrayList<>(); processes.add(process1); processes.add(process2); processes.add(process3); return processes; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularScanSchedulingTest.java
package com.thealgorithms.scheduling.diskscheduling; import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class CircularScanSchedulingTest { @Test public void testCircularScanSchedulingMovingUp() { CircularScanScheduling circularScan = new CircularScanScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expectedOrder = Arrays.asList(55, 58, 90, 150, 160, 18, 39); List<Integer> result = circularScan.execute(requests); assertEquals(expectedOrder, result); System.out.println("Final CircularScan Position: " + circularScan.getCurrentPosition()); System.out.println("CircularScan Moving Up: " + circularScan.isMovingUp()); System.out.println("Request Order: " + result); } @Test public void testCircularScanSchedulingMovingDown() { CircularScanScheduling circularScan = new CircularScanScheduling(50, false, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expectedOrder = Arrays.asList(39, 18, 160, 150, 90, 58, 55); List<Integer> result = circularScan.execute(requests); assertEquals(expectedOrder, result); System.out.println("Final CircularScan Position: " + circularScan.getCurrentPosition()); System.out.println("CircularScan Moving Down: " + circularScan.isMovingUp()); System.out.println("Request Order: " + result); } @Test public void testCircularScanSchedulingEmptyRequests() { CircularScanScheduling circularScan = new CircularScanScheduling(50, true, 200); List<Integer> requests = emptyList(); List<Integer> expectedOrder = emptyList(); List<Integer> result = circularScan.execute(requests); assertEquals(expectedOrder, 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/scheduling/diskscheduling/ScanSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/diskscheduling/ScanSchedulingTest.java
package com.thealgorithms.scheduling.diskscheduling; import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class ScanSchedulingTest { @Test public void testScanSchedulingMovingUp() { ScanScheduling scanScheduling = new ScanScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(55, 58, 90, 150, 160, 199, 39, 18); List<Integer> result = scanScheduling.execute(requests); assertEquals(expected, result); } @Test public void testScanSchedulingMovingDown() { ScanScheduling scanScheduling = new ScanScheduling(50, false, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(39, 18, 0, 55, 58, 90, 150, 160); List<Integer> result = scanScheduling.execute(requests); assertEquals(expected, result); } @Test public void testScanSchedulingEmptyRequests() { ScanScheduling scanScheduling = new ScanScheduling(50, true, 200); List<Integer> requests = emptyList(); List<Integer> expected = emptyList(); List<Integer> result = scanScheduling.execute(requests); assertEquals(expected, result); } @Test public void testScanScheduling() { ScanScheduling scanScheduling = new ScanScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> result = scanScheduling.execute(requests); List<Integer> expectedOrder = Arrays.asList(55, 58, 90, 150, 160, 199, 39, 18); assertEquals(expectedOrder, result); System.out.println("Final Head Position: " + scanScheduling.getHeadPosition()); System.out.println("Head Moving Up: " + scanScheduling.isMovingUp()); System.out.println("Request Order: " + 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/scheduling/diskscheduling/SSFSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/diskscheduling/SSFSchedulingTest.java
package com.thealgorithms.scheduling.diskscheduling; 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.BeforeEach; import org.junit.jupiter.api.Test; public class SSFSchedulingTest { private SSFScheduling scheduler; @BeforeEach public void setUp() { scheduler = new SSFScheduling(50); } @Test public void testExecuteWithEmptyList() { List<Integer> requests = new ArrayList<>(); List<Integer> result = scheduler.execute(requests); assertTrue(result.isEmpty(), "Result should be empty for an empty request list."); } @Test public void testExecuteWithSingleRequest() { List<Integer> requests = new ArrayList<>(List.of(100)); List<Integer> result = scheduler.execute(requests); assertEquals(List.of(100), result, "The only request should be served first."); } @Test public void testExecuteWithMultipleRequests() { List<Integer> requests = new ArrayList<>(List.of(10, 90, 60, 40, 30, 70)); List<Integer> result = scheduler.execute(requests); assertEquals(List.of(60, 70, 90, 40, 30, 10), result, "Requests should be served in the shortest seek first order."); } @Test public void testExecuteWithSameDistanceRequests() { List<Integer> requests = new ArrayList<>(List.of(45, 55)); List<Integer> result = scheduler.execute(requests); assertEquals(List.of(45, 55), result, "When distances are equal, requests should be served in the order they appear in the list."); } @Test public void testGetCurrentPositionAfterExecution() { List<Integer> requests = new ArrayList<>(List.of(10, 90, 60, 40, 30, 70)); scheduler.execute(requests); int currentPosition = scheduler.getCurrentPosition(); assertEquals(10, currentPosition, "Current position should be the last request after execution."); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/diskscheduling/CircularLookSchedulingTest.java
package com.thealgorithms.scheduling.diskscheduling; import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class CircularLookSchedulingTest { @Test public void testCircularLookSchedulingMovingUp() { CircularLookScheduling scheduling = new CircularLookScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(55, 58, 90, 150, 160, 18, 39); List<Integer> result = scheduling.execute(requests); assertEquals(expected, result); } @Test public void testCircularLookSchedulingMovingDown() { CircularLookScheduling scheduling = new CircularLookScheduling(50, false, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(39, 18, 160, 150, 90, 58, 55); List<Integer> result = scheduling.execute(requests); assertEquals(expected, result); } @Test public void testCircularLookSchedulingEmptyRequests() { CircularLookScheduling scheduling = new CircularLookScheduling(50, true, 200); List<Integer> requests = emptyList(); List<Integer> expected = emptyList(); List<Integer> result = scheduling.execute(requests); assertEquals(expected, result); } @Test public void testCircularLookSchedulingPrintStatus() { CircularLookScheduling scheduling = new CircularLookScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> result = scheduling.execute(requests); // Print the final status System.out.println("Final CircularLookScheduling Position: " + scheduling.getCurrentPosition()); System.out.println("CircularLookScheduling Moving Up: " + scheduling.isMovingUp()); // Print the order of request processing System.out.println("Request Order: " + 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/scheduling/diskscheduling/LookSchedulingTest.java
src/test/java/com/thealgorithms/scheduling/diskscheduling/LookSchedulingTest.java
package com.thealgorithms.scheduling.diskscheduling; import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class LookSchedulingTest { @Test public void testLookSchedulingMovingUp() { LookScheduling lookScheduling = new LookScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(55, 58, 90, 150, 160, 39, 18); List<Integer> result = lookScheduling.execute(requests); assertEquals(expected, result); } @Test public void testLookSchedulingMovingDown() { LookScheduling lookScheduling = new LookScheduling(50, false, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> expected = Arrays.asList(39, 18, 55, 58, 90, 150, 160); List<Integer> result = lookScheduling.execute(requests); assertEquals(expected, result); } @Test public void testLookSchedulingEmptyRequests() { LookScheduling lookScheduling = new LookScheduling(50, true, 200); List<Integer> requests = emptyList(); List<Integer> expected = emptyList(); List<Integer> result = lookScheduling.execute(requests); assertEquals(expected, result); } @Test public void testLookSchedulingCurrentPosition() { LookScheduling lookScheduling = new LookScheduling(50, true, 200); // Testing current position remains unchanged after scheduling. assertEquals(50, lookScheduling.getCurrentPosition()); } @Test public void testLookSchedulingPrintStatus() { LookScheduling lookScheduling = new LookScheduling(50, true, 200); List<Integer> requests = Arrays.asList(55, 58, 39, 18, 90, 160, 150); List<Integer> result = lookScheduling.execute(requests); List<Integer> expectedOrder = Arrays.asList(55, 58, 90, 150, 160, 39, 18); assertEquals(expectedOrder, result); System.out.println("Final LookScheduling Position: " + lookScheduling.getCurrentPosition()); System.out.println("LookScheduling Moving Up: " + lookScheduling.isMovingUp()); System.out.println("Farthest Position Reached: " + lookScheduling.getFarthestPosition()); System.out.println("Request Order: " + 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/stacks/LargestRectangleTest.java
src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java
package com.thealgorithms.stacks; 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 LargestRectangleTest { @ParameterizedTest(name = "Histogram: {0} → Expected area: {1}") @MethodSource("histogramProvider") void testLargestRectangleHistogram(int[] heights, String expected) { assertEquals(expected, LargestRectangle.largestRectangleHistogram(heights)); } static Stream<Arguments> histogramProvider() { return Stream.of(Arguments.of(new int[] {2, 1, 5, 6, 2, 3}, "10"), Arguments.of(new int[] {2, 4}, "4"), Arguments.of(new int[] {4, 4, 4, 4}, "16"), Arguments.of(new int[] {}, "0"), Arguments.of(new int[] {5}, "5"), Arguments.of(new int[] {0, 0, 0}, "0"), Arguments.of(new int[] {6, 2, 5, 4, 5, 1, 6}, "12"), Arguments.of(new int[] {2, 1, 5, 6, 2, 3, 1}, "10"), Arguments.of(createLargeArray(10000, 1), "10000")); } private static int[] createLargeArray(int size, int value) { int[] arr = new int[size]; java.util.Arrays.fill(arr, value); return arr; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java
src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class BalancedBracketsTest { @ParameterizedTest @CsvSource({"(, )", "[, ]", "{, }", "<, >"}) void testIsPairedTrue(char opening, char closing) { assertTrue(BalancedBrackets.isPaired(opening, closing)); } @ParameterizedTest @CsvSource({"(, ]", "[, )", "{, >", "<, )", "a, b", "!, @"}) void testIsPairedFalse(char opening, char closing) { assertFalse(BalancedBrackets.isPaired(opening, closing)); } @ParameterizedTest @CsvSource({"'[()]{}{[()()]()}', true", "'()', true", "'[]', true", "'{}', true", "'<>', true", "'[{<>}]', true", "'', true", "'[(])', false", "'([)]', false", "'{[<]>}', false", "'[', false", "')', false", "'[{', false", "']', false", "'[a+b]', false", "'a+b', false"}) void testIsBalanced(String input, boolean expected) { assertEquals(expected, BalancedBrackets.isBalanced(input)); } @Test void testIsBalancedNull() { assertThrows(IllegalArgumentException.class, () -> BalancedBrackets.isBalanced(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/stacks/PostfixEvaluatorTest.java
src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class PostfixEvaluatorTest { @ParameterizedTest(name = "Expression: \"{0}\" → Result: {1}") @CsvSource({"'5 6 + 2 *', 22", "'7 2 + 3 *', 27", "'10 5 / 1 +', 3", "'8', 8", "'3 4 +', 7"}) @DisplayName("Valid postfix expressions") void testValidExpressions(String expression, int expected) { assertEquals(expected, PostfixEvaluator.evaluatePostfix(expression)); } @Test @DisplayName("Should throw EmptyStackException for incomplete expression") void testInvalidExpression() { assertThrows(EmptyStackException.class, () -> PostfixEvaluator.evaluatePostfix("5 +")); } @Test @DisplayName("Should throw IllegalArgumentException for extra operands") void testExtraOperands() { assertThrows(IllegalArgumentException.class, () -> PostfixEvaluator.evaluatePostfix("5 6 + 2 * 3")); } @Test @DisplayName("Should throw ArithmeticException for division by zero") void testDivisionByZero() { assertThrows(ArithmeticException.class, () -> PostfixEvaluator.evaluatePostfix("1 0 /")); } @Test @DisplayName("Should throw IllegalArgumentException for invalid characters") void testInvalidToken() { assertThrows(IllegalArgumentException.class, () -> PostfixEvaluator.evaluatePostfix("1 a +")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java
src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class InfixToPostfixTest { @ParameterizedTest @MethodSource("provideValidExpressions") void testValidExpressions(String infix, String expectedPostfix) { assertEquals(expectedPostfix, InfixToPostfix.infix2PostFix(infix)); } private static Stream<Arguments> provideValidExpressions() { return Stream.of(Arguments.of("3+2", "32+"), Arguments.of("1+(2+3)", "123++"), Arguments.of("(3+4)*5-6", "34+5*6-")); } @ParameterizedTest @MethodSource("provideInvalidExpressions") void testInvalidExpressions(String infix, String expectedMessage) { Exception exception = assertThrows(Exception.class, () -> InfixToPostfix.infix2PostFix(infix)); assertEquals(expectedMessage, exception.getMessage()); } private static Stream<Arguments> provideInvalidExpressions() { return Stream.of(Arguments.of("((a+b)*c-d", "Invalid expression: unbalanced brackets.")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java
src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class InfixToPrefixTest { @ParameterizedTest @MethodSource("provideValidExpressions") void testValidExpressions(String infix, String expectedPrefix) { assertEquals(expectedPrefix, InfixToPrefix.infix2Prefix(infix)); } @Test void testEmptyString() { // Assuming that an empty string returns an empty prefix or throws an exception assertEquals("", InfixToPrefix.infix2Prefix("")); } @Test void testNullValue() { // Assuming that a null input throws a NullPointerException assertThrows(NullPointerException.class, () -> InfixToPrefix.infix2Prefix(null)); } private static Stream<Arguments> provideValidExpressions() { return Stream.of(Arguments.of("3+2", "+32"), // Simple addition Arguments.of("1+(2+3)", "+1+23"), // Parentheses Arguments.of("(3+4)*5-6", "-*+3456"), // Nested operations Arguments.of("a+b*c", "+a*bc"), // Multiplication precedence Arguments.of("a+b*c/d", "+a/*bcd"), // Division precedence Arguments.of("a+b*c-d", "-+a*bcd"), // Subtraction precedence Arguments.of("a+b*c/d-e", "-+a/*bcde"), // Mixed precedence Arguments.of("a+b*(c-d)", "+a*b-cd"), // Parentheses precedence Arguments.of("a+b*(c-d)/e", "+a/*b-cde") // Mixed precedence with parentheses ); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java
src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java
package com.thealgorithms.stacks; 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; class NextSmallerElementTest { @ParameterizedTest @MethodSource("provideTestCases") void testFindNextSmallerElements(int[] input, int[] expected) { assertArrayEquals(expected, NextSmallerElement.findNextSmallerElements(input)); } static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new int[] {2, 7, 3, 5, 4, 6, 8}, new int[] {-1, 2, 2, 3, 3, 4, 6}), Arguments.of(new int[] {5}, new int[] {-1}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {-1, 1, 2, 3, 4}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {-1, -1, -1, -1, -1}), Arguments.of(new int[] {4, 5, 2, 25}, new int[] {-1, 4, -1, 2}), Arguments.of(new int[] {}, new int[] {})); } @Test void testFindNextSmallerElementsExceptions() { assertThrows(IllegalArgumentException.class, () -> NextSmallerElement.findNextSmallerElements(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/stacks/PrefixEvaluatorTest.java
src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class PrefixEvaluatorTest { @ParameterizedTest(name = "Expression: \"{0}\" → Result: {1}") @CsvSource({"'+ * 2 3 4', 10", "'- + 7 3 5', 5", "'/ * 3 2 1', 6"}) void testValidExpressions(String expression, int expected) { assertEquals(expected, PrefixEvaluator.evaluatePrefix(expression)); } @Test @DisplayName("Should throw EmptyStackException for incomplete expression") void testInvalidExpression() { assertThrows(EmptyStackException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3")); } @Test @DisplayName("Should throw IllegalArgumentException if stack not reduced to one result") void testMoreThanOneStackSizeAfterEvaluation() { assertThrows(IllegalArgumentException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3 4 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/stacks/PalindromeWithStackTest.java
src/test/java/com/thealgorithms/stacks/PalindromeWithStackTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class PalindromeWithStackTest { private PalindromeWithStack palindromeChecker; @BeforeEach public void setUp() { palindromeChecker = new PalindromeWithStack(); } @Test public void testValidOne() { String testString = "Racecar"; assertTrue(palindromeChecker.checkPalindrome(testString)); } @Test public void testInvalidOne() { String testString = "James"; assertFalse(palindromeChecker.checkPalindrome(testString)); } @Test public void testValidTwo() { String testString = "madam"; assertTrue(palindromeChecker.checkPalindrome(testString)); } @Test public void testInvalidTwo() { String testString = "pantry"; assertFalse(palindromeChecker.checkPalindrome(testString)); } @Test public void testValidThree() { String testString = "RaDar"; assertTrue(palindromeChecker.checkPalindrome(testString)); } @Test public void testInvalidThree() { String testString = "Win"; assertFalse(palindromeChecker.checkPalindrome(testString)); } @Test public void testBlankString() { String testString = ""; assertTrue(palindromeChecker.checkPalindrome(testString)); } @Test public void testStringWithNumbers() { String testString = "12321"; assertTrue(palindromeChecker.checkPalindrome(testString)); } @Test public void testStringWithNumbersTwo() { String testString = "12325"; assertFalse(palindromeChecker.checkPalindrome(testString)); } @Test public void testStringWithNumbersAndLetters() { String testString = "po454op"; assertTrue(palindromeChecker.checkPalindrome(testString)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java
src/test/java/com/thealgorithms/stacks/MinStackUsingSingleStackTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; import org.junit.jupiter.api.Test; public class MinStackUsingSingleStackTest { @Test public void testBasicOperations() { MinStackUsingSingleStack minStack = new MinStackUsingSingleStack(); minStack.push(3); minStack.push(5); assertEquals(3, minStack.getMin(), "Minimum should be 3"); minStack.push(2); minStack.push(1); assertEquals(1, minStack.getMin(), "Minimum should be 1"); minStack.pop(); assertEquals(2, minStack.getMin(), "Minimum should be 2"); minStack.pop(); assertEquals(3, minStack.getMin(), "Minimum should be 3"); } @Test public void testTopElement() { MinStackUsingSingleStack minStack = new MinStackUsingSingleStack(); minStack.push(8); minStack.push(10); assertEquals(10, minStack.top(), "Top element should be 10"); minStack.pop(); assertEquals(8, minStack.top(), "Top element should be 8"); } @Test public void testGetMinAfterPops() { MinStackUsingSingleStack minStack = new MinStackUsingSingleStack(); minStack.push(5); minStack.push(3); minStack.push(7); assertEquals(3, minStack.getMin(), "Minimum should be 3"); minStack.pop(); // Popping 7 assertEquals(3, minStack.getMin(), "Minimum should still be 3"); minStack.pop(); // Popping 3 assertEquals(5, minStack.getMin(), "Minimum should now be 5"); } @Test public void testEmptyStack() { MinStackUsingSingleStack minStack = new MinStackUsingSingleStack(); assertThrows(EmptyStackException.class, minStack::top, "Should throw exception on top()"); assertThrows(EmptyStackException.class, minStack::getMin, "Should throw exception on getMin()"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java
src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class StackUsingTwoQueuesTest { private StackUsingTwoQueues stack; @BeforeEach public void setUp() { stack = new StackUsingTwoQueues(); } @Test public void testPushAndPeek() { stack.push(1); stack.push(2); stack.push(3); assertEquals(3, stack.peek()); } @Test public void testPop() { stack.push(1); stack.push(2); stack.push(3); assertEquals(3, stack.pop()); assertEquals(2, stack.pop()); assertEquals(1, stack.pop()); } @Test public void testPeek() { stack.push(10); stack.push(20); assertEquals(20, stack.peek()); stack.pop(); assertEquals(10, stack.peek()); } @Test public void testIsEmpty() { assertTrue(stack.isEmpty()); stack.push(1); assertFalse(stack.isEmpty()); stack.pop(); assertTrue(stack.isEmpty()); } @Test public void testSize() { assertEquals(0, stack.size()); stack.push(1); stack.push(2); assertEquals(2, stack.size()); stack.pop(); assertEquals(1, stack.size()); } @Test public void testPeekEmptyStack() { assertNull(stack.peek()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/ValidParenthesesTest.java
src/test/java/com/thealgorithms/stacks/ValidParenthesesTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class ValidParenthesesTest { @Test void testValidParentheses() { assertTrue(ValidParentheses.isValid("()")); assertTrue(ValidParentheses.isValid("()[]{}")); assertTrue(ValidParentheses.isValid("{[]}")); assertTrue(ValidParentheses.isValid("")); } @Test void testInvalidParentheses() { assertFalse(ValidParentheses.isValid("(]")); assertFalse(ValidParentheses.isValid("([)]")); assertFalse(ValidParentheses.isValid("{{{")); assertFalse(ValidParentheses.isValid("}")); assertFalse(ValidParentheses.isValid("(")); } @Test void testNullAndOddLength() { assertFalse(ValidParentheses.isValid(null)); assertFalse(ValidParentheses.isValid("(()")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java
src/test/java/com/thealgorithms/stacks/SmallestElementConstantTimeTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.NoSuchElementException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SmallestElementConstantTimeTest { private SmallestElementConstantTime sect; @BeforeEach public void setSect() { sect = new SmallestElementConstantTime(); } @Test public void testMinAtFirst() { sect.push(1); sect.push(10); sect.push(20); sect.push(5); assertEquals(1, sect.getMinimumElement()); } @Test public void testMinTwo() { sect.push(5); sect.push(10); sect.push(20); sect.push(1); assertEquals(1, sect.getMinimumElement()); sect.pop(); assertEquals(5, sect.getMinimumElement()); } @Test public void testNullMin() { sect.push(10); sect.push(20); sect.pop(); sect.pop(); assertNull(sect.getMinimumElement()); } @Test public void testBlankHandle() { sect.push(10); sect.push(1); sect.pop(); sect.pop(); assertThrows(NoSuchElementException.class, () -> sect.pop()); } @Test public void testPushPopAfterEmpty() { sect.push(10); sect.push(1); sect.pop(); sect.pop(); sect.push(5); assertEquals(5, sect.getMinimumElement()); sect.push(1); assertEquals(1, sect.getMinimumElement()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java
src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java
package com.thealgorithms.stacks; 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; class NextGreaterElementTest { @ParameterizedTest @MethodSource("provideTestCases") void testFindNextGreaterElements(int[] input, int[] expected) { assertArrayEquals(expected, NextGreaterElement.findNextGreaterElements(input)); } static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new int[] {2, 7, 3, 5, 4, 6, 8}, new int[] {7, 8, 5, 6, 6, 8, 0}), Arguments.of(new int[] {5}, new int[] {0}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {2, 3, 4, 5, 0}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {0, 0, 0, 0, 0}), Arguments.of(new int[] {4, 5, 2, 25}, new int[] {5, 25, 25, 0}), Arguments.of(new int[] {}, new int[] {})); } @Test void testNullInput() { assertThrows(IllegalArgumentException.class, () -> NextGreaterElement.findNextGreaterElements(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/stacks/CelebrityFinderTest.java
src/test/java/com/thealgorithms/stacks/CelebrityFinderTest.java
package com.thealgorithms.stacks; 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 CelebrityFinderTest { @ParameterizedTest @MethodSource("providePartyMatrices") public void testCelebrityFinder(int[][] party, int expected) { assertEquals(expected, CelebrityFinder.findCelebrity(party)); } private static Stream<Arguments> providePartyMatrices() { return Stream.of( // Test case 1: Celebrity exists Arguments.of(new int[][] {{0, 1, 1}, {0, 0, 1}, {0, 0, 0}}, 2), // Test case 2: No celebrity Arguments.of(new int[][] {{0, 1, 0}, {1, 0, 1}, {1, 1, 0}}, -1), // Test case 3: Everyone knows each other, no celebrity Arguments.of(new int[][] {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}, -1), // Test case 4: Single person, they are trivially a celebrity Arguments.of(new int[][] {{0}}, 0), // Test case 5: All know the last person, and they know no one Arguments.of(new int[][] {{0, 1, 1, 1}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}}, 3), // Test case 6: Larger party with no celebrity Arguments.of(new int[][] {{0, 1, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 1, 0}}, -1), // Test case 7: Celebrity at the start of the matrix Arguments.of(new int[][] {{0, 0, 0}, {1, 0, 1}, {1, 1, 0}}, 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/stacks/StackPostfixNotationTest.java
src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class StackPostfixNotationTest { @ParameterizedTest @MethodSource("provideValidTestCases") void testEvaluate(String expression, int expected) { assertEquals(expected, StackPostfixNotation.postfixEvaluate(expression)); } static Stream<Arguments> provideValidTestCases() { return Stream.of(Arguments.of("1 1 +", 2), Arguments.of("2 3 *", 6), Arguments.of("6 2 /", 3), Arguments.of("-5 -2 -", -3), Arguments.of("5 2 + 3 *", 21), Arguments.of("-5", -5)); } @ParameterizedTest @MethodSource("provideInvalidTestCases") void testEvaluateThrowsException(String expression) { assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate(expression)); } static Stream<Arguments> provideInvalidTestCases() { return Stream.of(Arguments.of(""), Arguments.of("3 3 3"), Arguments.of("3 3 !"), Arguments.of("+"), Arguments.of("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/stacks/GreatestElementConstantTimeTest.java
src/test/java/com/thealgorithms/stacks/GreatestElementConstantTimeTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.NoSuchElementException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class GreatestElementConstantTimeTest { private GreatestElementConstantTime constantTime; @BeforeEach public void setConstantTime() { constantTime = new GreatestElementConstantTime(); } @Test public void testMaxAtFirst() { constantTime.push(1); constantTime.push(10); constantTime.push(20); constantTime.push(5); assertEquals(20, constantTime.getMaximumElement()); } @Test public void testMinTwo() { constantTime.push(5); constantTime.push(10); constantTime.push(20); constantTime.push(1); assertEquals(20, constantTime.getMaximumElement()); constantTime.pop(); constantTime.pop(); assertEquals(10, constantTime.getMaximumElement()); } @Test public void testNullMax() { constantTime.push(10); constantTime.push(20); constantTime.pop(); constantTime.pop(); assertNull(constantTime.getMaximumElement()); } @Test public void testBlankHandle() { constantTime.push(10); constantTime.push(1); constantTime.pop(); constantTime.pop(); assertThrows(NoSuchElementException.class, () -> constantTime.pop()); } @Test public void testPushPopAfterEmpty() { constantTime.push(10); constantTime.push(1); constantTime.pop(); constantTime.pop(); constantTime.push(5); assertEquals(5, constantTime.getMaximumElement()); constantTime.push(1); assertEquals(5, constantTime.getMaximumElement()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/MinStackUsingTwoStacksTest.java
src/test/java/com/thealgorithms/stacks/MinStackUsingTwoStacksTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.EmptyStackException; import org.junit.jupiter.api.Test; public class MinStackUsingTwoStacksTest { @Test public void testBasicOperations() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); minStack.push(3); minStack.push(5); assertEquals(3, minStack.getMin(), "Min should be 3"); minStack.push(2); minStack.push(1); assertEquals(1, minStack.getMin(), "Min should be 1"); minStack.pop(); assertEquals(2, minStack.getMin(), "Min should be 2 after popping 1"); assertEquals(2, minStack.top(), "Top should be 2"); } @Test public void testPushDuplicateMins() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); minStack.push(2); minStack.push(2); minStack.push(1); minStack.push(1); assertEquals(1, minStack.getMin(), "Min should be 1"); minStack.pop(); assertEquals(1, minStack.getMin(), "Min should still be 1 after popping one 1"); minStack.pop(); assertEquals(2, minStack.getMin(), "Min should be 2 after popping both 1s"); minStack.pop(); assertEquals(2, minStack.getMin(), "Min should still be 2 after popping one 2"); minStack.pop(); // Now stack is empty, expect exception on getMin assertThrows(EmptyStackException.class, minStack::getMin); } @Test public void testPopOnEmptyStack() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); assertThrows(EmptyStackException.class, minStack::pop); } @Test public void testTopOnEmptyStack() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); assertThrows(EmptyStackException.class, minStack::top); } @Test public void testGetMinOnEmptyStack() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); assertThrows(EmptyStackException.class, minStack::getMin); } @Test public void testSingleElementStack() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); minStack.push(10); assertEquals(10, minStack.getMin()); assertEquals(10, minStack.top()); minStack.pop(); assertThrows(EmptyStackException.class, minStack::getMin); } @Test public void testIncreasingSequence() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); minStack.push(1); minStack.push(2); minStack.push(3); minStack.push(4); assertEquals(1, minStack.getMin()); assertEquals(4, minStack.top()); minStack.pop(); minStack.pop(); assertEquals(1, minStack.getMin()); assertEquals(2, minStack.top()); } @Test public void testDecreasingSequence() { MinStackUsingTwoStacks minStack = new MinStackUsingTwoStacks(); minStack.push(4); minStack.push(3); minStack.push(2); minStack.push(1); assertEquals(1, minStack.getMin()); assertEquals(1, minStack.top()); minStack.pop(); assertEquals(2, minStack.getMin()); assertEquals(2, minStack.top()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/DuplicateBracketsTest.java
src/test/java/com/thealgorithms/stacks/DuplicateBracketsTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.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.CsvSource; import org.junit.jupiter.params.provider.MethodSource; class DuplicateBracketsTest { @ParameterizedTest @CsvSource({"'((a + b) + (c + d))'", "'(a + b)'", "'a + b'", "'('", "''", "'a + (b * c) - d'", "'(x + y) * (z)'", "'(a + (b - c))'"}) void testInputReturnsFalse(String input) { assertFalse(DuplicateBrackets.check(input)); } @ParameterizedTest @CsvSource({"'(a + b) + ((c + d))'", "'((a + b))'", "'((((a + b)))))'", "'((x))'", "'((a + (b)))'", "'(a + ((b)))'", "'(((a)))'", "'(((())))'"}) void testInputReturnsTrue(String input) { assertTrue(DuplicateBrackets.check(input)); } @Test void testInvalidInput() { assertThrows(IllegalArgumentException.class, () -> DuplicateBrackets.check(null)); } @ParameterizedTest(name = "Should be true: \"{0}\"") @MethodSource("provideInputsThatShouldReturnTrue") void testDuplicateBracketsTrueCases(String input) { assertTrue(DuplicateBrackets.check(input)); } static Stream<Arguments> provideInputsThatShouldReturnTrue() { return Stream.of(Arguments.of("()"), Arguments.of("(( ))")); } @ParameterizedTest(name = "Should be false: \"{0}\"") @MethodSource("provideInputsThatShouldReturnFalse") void testDuplicateBracketsFalseCases(String input) { assertFalse(DuplicateBrackets.check(input)); } static Stream<Arguments> provideInputsThatShouldReturnFalse() { return Stream.of(Arguments.of("( )"), // whitespace inside brackets Arguments.of("abc + def"), // no brackets Arguments.of("(a + (b * c)) - (d / e)") // complex, but no duplicates ); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/TrappingRainwaterTest.java
src/test/java/com/thealgorithms/stacks/TrappingRainwaterTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class TrappingRainwaterTest { @Test public void testExampleCase() { int[] height = {4, 2, 0, 3, 2, 5}; assertEquals(9, TrappingRainwater.trap(height)); } @Test public void testNoTrapping() { int[] height = {1, 2, 3, 4, 5}; assertEquals(0, TrappingRainwater.trap(height)); } @Test public void testFlatSurface() { int[] height = {0, 0, 0, 0}; assertEquals(0, TrappingRainwater.trap(height)); } @Test public void testSymmetricPit() { int[] height = {3, 0, 2, 0, 3}; assertEquals(7, TrappingRainwater.trap(height)); } @Test public void testSingleBar() { int[] height = {5}; assertEquals(0, TrappingRainwater.trap(height)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java
src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class PrefixToInfixTest { @ParameterizedTest @MethodSource("provideValidPrefixToInfixTestCases") void testValidPrefixToInfixConversion(String prefix, String expectedInfix) { assertEquals(expectedInfix, PrefixToInfix.getPrefixToInfix(prefix)); } static Stream<Arguments> provideValidPrefixToInfixTestCases() { return Stream.of(Arguments.of("A", "A"), // Single operand Arguments.of("+AB", "(A+B)"), // Addition Arguments.of("*+ABC", "((A+B)*C)"), // Addition and multiplication Arguments.of("-+A*BCD", "((A+(B*C))-D)"), // Mixed operators Arguments.of("/-A*BC+DE", "((A-(B*C))/(D+E))"), // Mixed operators Arguments.of("^+AB*CD", "((A+B)^(C*D))") // Mixed operators ); } @Test void testEmptyPrefixExpression() { assertEquals("", PrefixToInfix.getPrefixToInfix("")); } @Test void testNullPrefixExpression() { assertThrows(NullPointerException.class, () -> PrefixToInfix.getPrefixToInfix(null)); } @Test void testMalformedPrefixExpression() { assertThrows(ArithmeticException.class, () -> PrefixToInfix.getPrefixToInfix("+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/stacks/SortStackTest.java
src/test/java/com/thealgorithms/stacks/SortStackTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Stack; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SortStackTest { private Stack<Integer> stack; @BeforeEach public void setUp() { stack = new Stack<>(); } @Test public void testSortEmptyStack() { SortStack.sortStack(stack); assertTrue(stack.isEmpty()); // An empty stack should remain empty } @Test public void testSortSingleElementStack() { stack.push(10); SortStack.sortStack(stack); assertEquals(1, stack.size()); assertEquals(10, (int) stack.peek()); // Single element should remain unchanged } @Test public void testSortAlreadySortedStack() { stack.push(1); stack.push(2); stack.push(3); stack.push(4); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(4, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } @Test public void testSortUnsortedStack() { stack.push(3); stack.push(1); stack.push(4); stack.push(2); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(4, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } @Test public void testSortWithDuplicateElements() { stack.push(3); stack.push(1); stack.push(3); stack.push(2); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(3, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } @Test public void testSortReverseSortedStack() { // Test worst case scenario - completely reverse sorted stack.push(5); stack.push(4); stack.push(3); stack.push(2); stack.push(1); SortStack.sortStack(stack); assertEquals(5, stack.size()); assertEquals(5, (int) stack.pop()); assertEquals(4, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } @Test public void testSortWithAllSameElements() { // Test stack with all identical elements stack.push(7); stack.push(7); stack.push(7); stack.push(7); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(7, (int) stack.pop()); assertEquals(7, (int) stack.pop()); assertEquals(7, (int) stack.pop()); assertEquals(7, (int) stack.pop()); } @Test public void testSortWithNegativeNumbers() { // Test with negative numbers stack.push(-3); stack.push(1); stack.push(-5); stack.push(2); stack.push(-1); SortStack.sortStack(stack); assertEquals(5, stack.size()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); assertEquals(-1, (int) stack.pop()); assertEquals(-3, (int) stack.pop()); assertEquals(-5, (int) stack.pop()); } @Test public void testSortWithAllNegativeNumbers() { // Test with only negative numbers stack.push(-10); stack.push(-5); stack.push(-15); stack.push(-1); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(-1, (int) stack.pop()); assertEquals(-5, (int) stack.pop()); assertEquals(-10, (int) stack.pop()); assertEquals(-15, (int) stack.pop()); } @Test public void testSortWithZero() { // Test with zero included stack.push(3); stack.push(0); stack.push(-2); stack.push(1); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(3, (int) stack.pop()); assertEquals(1, (int) stack.pop()); assertEquals(0, (int) stack.pop()); assertEquals(-2, (int) stack.pop()); } @Test public void testSortLargerStack() { // Test with a larger number of elements int[] values = {15, 3, 9, 1, 12, 6, 18, 4, 11, 8}; for (int value : values) { stack.push(value); } SortStack.sortStack(stack); assertEquals(10, stack.size()); // Verify sorted order (largest to smallest when popping) int[] expectedOrder = {18, 15, 12, 11, 9, 8, 6, 4, 3, 1}; for (int expected : expectedOrder) { assertEquals(expected, (int) stack.pop()); } } @Test public void testSortTwoElements() { // Test edge case with exactly two elements stack.push(5); stack.push(2); SortStack.sortStack(stack); assertEquals(2, stack.size()); assertEquals(5, (int) stack.pop()); assertEquals(2, (int) stack.pop()); } @Test public void testSortTwoElementsAlreadySorted() { // Test two elements already in correct order stack.push(2); stack.push(5); SortStack.sortStack(stack); assertEquals(2, stack.size()); assertEquals(5, (int) stack.pop()); assertEquals(2, (int) stack.pop()); } @Test public void testSortStackWithMinAndMaxValues() { // Test with Integer.MAX_VALUE and Integer.MIN_VALUE stack.push(0); stack.push(Integer.MAX_VALUE); stack.push(Integer.MIN_VALUE); stack.push(100); SortStack.sortStack(stack); assertEquals(4, stack.size()); assertEquals(Integer.MAX_VALUE, (int) stack.pop()); assertEquals(100, (int) stack.pop()); assertEquals(0, (int) stack.pop()); assertEquals(Integer.MIN_VALUE, (int) stack.pop()); } @Test public void testSortWithManyDuplicates() { // Test with multiple sets of duplicates stack.push(3); stack.push(1); stack.push(3); stack.push(1); stack.push(2); stack.push(2); stack.push(3); SortStack.sortStack(stack); assertEquals(7, stack.size()); assertEquals(3, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } @Test public void testOriginalStackIsModified() { // Verify that the original stack is modified, not a copy Stack<Integer> originalReference = stack; stack.push(3); stack.push(1); stack.push(2); SortStack.sortStack(stack); // Verify it's the same object reference assertTrue(stack == originalReference); assertEquals(3, stack.size()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.pop()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java
src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class PostfixToInfixTest { @ParameterizedTest @MethodSource("provideValidPostfixToInfixTestCases") void testValidPostfixToInfixConversion(String postfix, String expectedInfix) { assertEquals(expectedInfix, PostfixToInfix.getPostfixToInfix(postfix)); } static Stream<Arguments> provideValidPostfixToInfixTestCases() { return Stream.of(Arguments.of("A", "A"), Arguments.of("ABC+/", "(A/(B+C))"), Arguments.of("AB+CD+*", "((A+B)*(C+D))"), Arguments.of("AB+C+D+", "(((A+B)+C)+D)"), Arguments.of("ABCDE^*/-", "(A-(B/(C*(D^E))))"), Arguments.of("AB+CD^/E*FGH+-^", "((((A+B)/(C^D))*E)^(F-(G+H)))")); } @Test void testEmptyPostfixExpression() { assertEquals("", PostfixToInfix.getPostfixToInfix("")); } @Test void testNullPostfixExpression() { assertThrows(NullPointerException.class, () -> PostfixToInfix.getPostfixToInfix(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/stacks/DecimalToAnyUsingStackTest.java
src/test/java/com/thealgorithms/stacks/DecimalToAnyUsingStackTest.java
package com.thealgorithms.stacks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class DecimalToAnyUsingStackTest { @Test void testConvertToBinary() { assertEquals("0", DecimalToAnyUsingStack.convert(0, 2)); assertEquals("11110", DecimalToAnyUsingStack.convert(30, 2)); } @Test void testConvertToOctal() { assertEquals("36", DecimalToAnyUsingStack.convert(30, 8)); } @Test void testConvertToDecimal() { assertEquals("30", DecimalToAnyUsingStack.convert(30, 10)); } @Test void testConvertToHexadecimal() { assertEquals("1E", DecimalToAnyUsingStack.convert(30, 16)); } @Test void testInvalidRadix() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> DecimalToAnyUsingStack.convert(30, 1)); assertEquals("Invalid radix: 1. Radix must be between 2 and 16.", thrown.getMessage()); thrown = assertThrows(IllegalArgumentException.class, () -> DecimalToAnyUsingStack.convert(30, 17)); assertEquals("Invalid radix: 17. Radix must be between 2 and 16.", thrown.getMessage()); } @Test void testNegativeNumber() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> DecimalToAnyUsingStack.convert(-30, 2)); assertEquals("Number must be non-negative.", thrown.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/graph/ZeroOneBfsTest.java
src/test/java/com/thealgorithms/graph/ZeroOneBfsTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; class ZeroOneBfsTest { // Helper to build adjacency list with capacity n private static List<List<int[]>> makeAdj(int n) { List<List<int[]>> adj = new ArrayList<>(n); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } return adj; } @Test void simpleLineGraph() { int n = 4; List<List<int[]>> adj = makeAdj(n); // 0 --0--> 1 --1--> 2 --0--> 3 adj.get(0).add(new int[] {1, 0}); adj.get(1).add(new int[] {2, 1}); adj.get(2).add(new int[] {3, 0}); int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0); assertArrayEquals(new int[] {0, 0, 1, 1}, dist); } @Test void parallelEdgesPreferZero() { int n = 3; List<List<int[]>> adj = makeAdj(n); // Two edges 0->1: weight 1 and weight 0. Algorithm should choose 0. adj.get(0).add(new int[] {1, 1}); adj.get(0).add(new int[] {1, 0}); adj.get(1).add(new int[] {2, 1}); int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0); assertArrayEquals(new int[] {0, 0, 1}, dist); } @Test void unreachableNodes() { int n = 3; List<List<int[]>> adj = makeAdj(n); adj.get(0).add(new int[] {1, 0}); int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0); // node 2 unreachable -> Integer.MAX_VALUE assertArrayEquals(new int[] {0, 0, Integer.MAX_VALUE}, dist); } @Test void invalidArgs() { int n = 2; List<List<int[]>> adj = makeAdj(n); // invalid weight adj.get(0).add(new int[] {1, 2}); assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, 0)); // invalid src assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, -1)); assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, 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/graph/EdmondsKarpTest.java
src/test/java/com/thealgorithms/graph/EdmondsKarpTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class EdmondsKarpTest { @Test @DisplayName("Classic CLRS network yields max flow 23") void clrsExample() { int[][] capacity = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; int maxFlow = EdmondsKarp.maxFlow(capacity, 0, 5); assertEquals(23, maxFlow); } @Test @DisplayName("Disconnected network has zero flow") void disconnectedGraph() { int[][] capacity = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; int maxFlow = EdmondsKarp.maxFlow(capacity, 0, 2); assertEquals(0, maxFlow); } @Test @DisplayName("Source equals sink returns zero") void sourceEqualsSink() { int[][] capacity = {{0, 5}, {0, 0}}; int maxFlow = EdmondsKarp.maxFlow(capacity, 0, 0); assertEquals(0, maxFlow); } @Test @DisplayName("Invalid matrix throws exception") void invalidMatrix() { int[][] capacity = {{0, 1}, {1}}; assertThrows(IllegalArgumentException.class, () -> EdmondsKarp.maxFlow(capacity, 0, 1)); } @Test @DisplayName("Negative capacity is rejected") void negativeCapacity() { int[][] capacity = {{0, -1}, {0, 0}}; assertThrows(IllegalArgumentException.class, () -> EdmondsKarp.maxFlow(capacity, 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/graph/PushRelabelTest.java
src/test/java/com/thealgorithms/graph/PushRelabelTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class PushRelabelTest { @Test @DisplayName("Classic CLRS network yields max flow 23 (PushRelabel)") void clrsExample() { int[][] capacity = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; int maxFlow = PushRelabel.maxFlow(capacity, 0, 5); assertEquals(23, maxFlow); } @Test @DisplayName("Disconnected network has zero flow (PushRelabel)") void disconnectedGraph() { int[][] capacity = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; int maxFlow = PushRelabel.maxFlow(capacity, 0, 2); assertEquals(0, maxFlow); } @Test @DisplayName("Source equals sink returns zero (PushRelabel)") void sourceEqualsSink() { int[][] capacity = {{0, 5}, {0, 0}}; int maxFlow = PushRelabel.maxFlow(capacity, 0, 0); assertEquals(0, maxFlow); } @Test @DisplayName("PushRelabel matches Dinic and EdmondsKarp on random small graphs") void parityWithOtherMaxFlow() { java.util.Random rnd = new java.util.Random(42); for (int n = 3; n <= 7; n++) { for (int it = 0; it < 25; it++) { int[][] cap = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && rnd.nextDouble() < 0.35) { cap[i][j] = rnd.nextInt(10); // capacities 0..9 } } } int s = 0; int t = n - 1; int fPushRelabel = PushRelabel.maxFlow(copyMatrix(cap), s, t); int fDinic = Dinic.maxFlow(copyMatrix(cap), s, t); int fEdmondsKarp = EdmondsKarp.maxFlow(cap, s, t); assertEquals(fDinic, fPushRelabel); assertEquals(fEdmondsKarp, fPushRelabel); } } } private static int[][] copyMatrix(int[][] a) { int[][] b = new int[a.length][a.length]; for (int i = 0; i < a.length; i++) { b[i] = java.util.Arrays.copyOf(a[i], a[i].length); } return b; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/DinicTest.java
src/test/java/com/thealgorithms/graph/DinicTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class DinicTest { @Test @DisplayName("Classic CLRS network yields max flow 23 (Dinic)") void clrsExample() { int[][] capacity = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; int maxFlow = Dinic.maxFlow(capacity, 0, 5); assertEquals(23, maxFlow); } @Test @DisplayName("Disconnected network has zero flow (Dinic)") void disconnectedGraph() { int[][] capacity = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; int maxFlow = Dinic.maxFlow(capacity, 0, 2); assertEquals(0, maxFlow); } @Test @DisplayName("Source equals sink returns zero (Dinic)") void sourceEqualsSink() { int[][] capacity = {{0, 5}, {0, 0}}; int maxFlow = Dinic.maxFlow(capacity, 0, 0); assertEquals(0, maxFlow); } @Test @DisplayName("Invalid matrix throws exception (Dinic)") void invalidMatrix() { int[][] capacity = {{0, 1}, {1}}; assertThrows(IllegalArgumentException.class, () -> Dinic.maxFlow(capacity, 0, 1)); } @Test @DisplayName("Dinic matches Edmonds-Karp on random small graphs") void parityWithEdmondsKarp() { java.util.Random rnd = new java.util.Random(42); for (int n = 3; n <= 7; n++) { for (int it = 0; it < 25; it++) { int[][] cap = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && rnd.nextDouble() < 0.35) { cap[i][j] = rnd.nextInt(10); // capacities 0..9 } } } int s = 0; int t = n - 1; int f1 = Dinic.maxFlow(copyMatrix(cap), s, t); int f2 = EdmondsKarp.maxFlow(cap, s, t); assertEquals(f2, f1); } } } private static int[][] copyMatrix(int[][] a) { int[][] b = new int[a.length][a.length]; for (int i = 0; i < a.length; i++) { b[i] = java.util.Arrays.copyOf(a[i], a[i].length); } return b; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java
src/test/java/com/thealgorithms/graph/StronglyConnectedComponentOptimizedTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class StronglyConnectedComponentOptimizedTest { private StronglyConnectedComponentOptimized sccOptimized; @BeforeEach public void setUp() { sccOptimized = new StronglyConnectedComponentOptimized(); } @Test public void testSingleComponent() { // Create a simple graph with 3 nodes, all forming one SCC HashMap<Integer, List<Integer>> adjList = new HashMap<>(); adjList.put(0, new ArrayList<>(List.of(1))); adjList.put(1, new ArrayList<>(List.of(2))); adjList.put(2, new ArrayList<>(List.of(0))); int result = sccOptimized.getOutput(adjList, 3); // The entire graph is one strongly connected component assertEquals(1, result, "There should be 1 strongly connected component."); } @Test public void testTwoComponents() { // Create a graph with 4 nodes and two SCCs: {0, 1, 2} and {3} HashMap<Integer, List<Integer>> adjList = new HashMap<>(); adjList.put(0, new ArrayList<>(List.of(1))); adjList.put(1, new ArrayList<>(List.of(2))); adjList.put(2, new ArrayList<>(List.of(0))); adjList.put(3, new ArrayList<>()); int result = sccOptimized.getOutput(adjList, 4); // There are 2 SCCs: {0, 1, 2} and {3} assertEquals(2, result, "There should be 2 strongly connected components."); } @Test public void testDisconnectedGraph() { // Create a graph with 4 nodes that are all disconnected HashMap<Integer, List<Integer>> adjList = new HashMap<>(); adjList.put(0, new ArrayList<>()); adjList.put(1, new ArrayList<>()); adjList.put(2, new ArrayList<>()); adjList.put(3, new ArrayList<>()); int result = sccOptimized.getOutput(adjList, 4); // Each node is its own strongly connected component assertEquals(4, result, "There should be 4 strongly connected components."); } @Test public void testComplexGraph() { // Create a more complex graph with multiple SCCs HashMap<Integer, List<Integer>> adjList = new HashMap<>(); adjList.put(0, new ArrayList<>(List.of(1))); adjList.put(1, new ArrayList<>(List.of(2))); adjList.put(2, new ArrayList<>(List.of(0, 3))); adjList.put(3, new ArrayList<>(List.of(4))); adjList.put(4, new ArrayList<>(List.of(5))); adjList.put(5, new ArrayList<>(List.of(3))); int result = sccOptimized.getOutput(adjList, 6); // There are 2 SCCs: {0, 1, 2} and {3, 4, 5} assertEquals(2, result, "There should be 2 strongly connected components."); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/GomoryHuTreeTest.java
src/test/java/com/thealgorithms/graph/GomoryHuTreeTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.random.RandomGenerator; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class GomoryHuTreeTest { @Test @DisplayName("Single node graph") void singleNode() { int[][] cap = {{0}}; int[][] res = GomoryHuTree.buildTree(cap); int[] parent = res[0]; int[] weight = res[1]; assertEquals(-1, parent[0]); assertEquals(0, weight[0]); } @Test @DisplayName("Triangle undirected graph with known min-cuts") void triangleGraph() { // 0-1:3, 1-2:2, 0-2:4 int[][] cap = new int[3][3]; cap[0][1] = 3; cap[1][0] = 3; cap[1][2] = 2; cap[2][1] = 2; cap[0][2] = 4; cap[2][0] = 4; int[][] tree = GomoryHuTree.buildTree(cap); // validate all pairs via path-min-edge equals maxflow validateAllPairs(cap, tree); } @Test @DisplayName("Random small undirected graphs compare to EdmondsKarp") void randomSmallGraphs() { Random rng = new Random(42); for (int n = 2; n <= 6; n++) { for (int iter = 0; iter < 10; iter++) { int[][] cap = randSymmetricMatrix(n, 0, 5, rng); int[][] tree = GomoryHuTree.buildTree(cap); validateAllPairs(cap, tree); } } } private static int[][] randSymmetricMatrix(int n, int lo, int hi, RandomGenerator rng) { int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int w = rng.nextInt(hi - lo + 1) + lo; a[i][j] = w; a[j][i] = w; } } // zero diagonal for (int i = 0; i < n; i++) { a[i][i] = 0; } return a; } private static void validateAllPairs(int[][] cap, int[][] tree) { int n = cap.length; int[] parent = tree[0]; int[] weight = tree[1]; // build adjacency list of tree without generic array creation List<List<int[]>> g = new ArrayList<>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<>()); } for (int v = 1; v < n; v++) { int u = parent[v]; int w = weight[v]; g.get(u).add(new int[] {v, w}); g.get(v).add(new int[] {u, w}); } for (int s = 0; s < n; s++) { for (int t = s + 1; t < n; t++) { int treeVal = minEdgeOnPath(g, s, t); int flowVal = EdmondsKarp.maxFlow(cap, s, t); assertEquals(flowVal, treeVal, "pair (" + s + "," + t + ")"); } } } private static int minEdgeOnPath(List<List<int[]>> g, int s, int t) { // BFS to record parent and edge weight along the path, since it's a tree, unique path exists int n = g.size(); int[] parent = new int[n]; int[] edgeW = new int[n]; Arrays.fill(parent, -1); Queue<Integer> q = new ArrayDeque<>(); q.add(s); parent[s] = s; while (!q.isEmpty()) { int u = q.poll(); if (u == t) { break; } for (int[] e : g.get(u)) { int v = e[0]; int w = e[1]; if (parent[v] == -1) { parent[v] = u; edgeW[v] = w; q.add(v); } } } int cur = t; int ans = Integer.MAX_VALUE; while (cur != s) { ans = Math.min(ans, edgeW[cur]); cur = parent[cur]; } return ans == Integer.MAX_VALUE ? 0 : ans; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/StoerWagnerTest.java
src/test/java/com/thealgorithms/graph/StoerWagnerTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Unit tests for the StoerWagner global minimum cut algorithm. * * These tests verify correctness of the implementation across * several graph configurations: simple, complete, disconnected, * and small edge cases. */ public class StoerWagnerTest { @Test public void testSimpleGraph() { int[][] graph = {{0, 3, 2, 0}, {3, 0, 1, 4}, {2, 1, 0, 5}, {0, 4, 5, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(5, algo.findMinCut(graph)); // Correct minimum cut = 5 } @Test public void testTriangleGraph() { int[][] graph = {{0, 2, 3}, {2, 0, 4}, {3, 4, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(5, algo.findMinCut(graph)); // min cut = 5 } @Test public void testDisconnectedGraph() { int[][] graph = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(0, algo.findMinCut(graph)); // Disconnected graph => cut = 0 } @Test public void testCompleteGraph() { int[][] graph = {{0, 1, 1, 1}, {1, 0, 1, 1}, {1, 1, 0, 1}, {1, 1, 1, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(3, algo.findMinCut(graph)); // Each vertex connected to all others } @Test public void testSingleVertex() { int[][] graph = {{0}}; StoerWagner algo = new StoerWagner(); assertEquals(0, algo.findMinCut(graph)); // Only one vertex } @Test public void testTwoVertices() { int[][] graph = {{0, 7}, {7, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(7, algo.findMinCut(graph)); // Only one edge, cut weight = 7 } @Test public void testSquareGraphWithDiagonal() { int[][] graph = {{0, 2, 0, 2}, {2, 0, 3, 0}, {0, 3, 0, 4}, {2, 0, 4, 0}}; StoerWagner algo = new StoerWagner(); assertEquals(4, algo.findMinCut(graph)); // verified manually } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/HungarianAlgorithmTest.java
src/test/java/com/thealgorithms/graph/HungarianAlgorithmTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class HungarianAlgorithmTest { @Test @DisplayName("Classic 3x3 example: minimal cost 5 with assignment [1,0,2]") void classicSquareExample() { int[][] cost = {{4, 1, 3}, {2, 0, 5}, {3, 2, 2}}; HungarianAlgorithm.Result res = HungarianAlgorithm.solve(cost); assertEquals(5, res.minCost); assertArrayEquals(new int[] {1, 0, 2}, res.assignment); } @Test @DisplayName("Rectangular (more rows than cols): pads to square and returns -1 for unassigned rows") void rectangularMoreRows() { int[][] cost = {{7, 3}, {2, 8}, {5, 1}}; // Optimal selects any 2 rows: choose row1->col0 (2) and row2->col1 (1) => total 3 HungarianAlgorithm.Result res = HungarianAlgorithm.solve(cost); assertEquals(3, res.minCost); // Two rows assigned to 2 columns; one row remains -1. int assigned = 0; for (int a : res.assignment) { if (a >= 0) { assigned++; } } assertEquals(2, assigned); } @Test @DisplayName("Zero diagonal yields zero total cost") void zeroDiagonal() { int[][] cost = {{0, 5, 9}, {4, 0, 7}, {3, 6, 0}}; HungarianAlgorithm.Result res = HungarianAlgorithm.solve(cost); assertEquals(0, res.minCost); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/HopcroftKarpTest.java
src/test/java/com/thealgorithms/graph/HopcroftKarpTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for Hopcroft–Karp algorithm. * * @author ptzecher */ class HopcroftKarpTest { private static List<List<Integer>> adj(int nLeft) { List<List<Integer>> g = new ArrayList<>(nLeft); for (int i = 0; i < nLeft; i++) { // braces required by Checkstyle g.add(new ArrayList<>()); } return g; } @Test @DisplayName("Empty graph has matching 0") void emptyGraph() { List<List<Integer>> g = adj(3); HopcroftKarp hk = new HopcroftKarp(3, 4, g); assertEquals(0, hk.maxMatching()); } @Test @DisplayName("Single edge gives matching 1") void singleEdge() { List<List<Integer>> g = adj(1); g.get(0).add(0); HopcroftKarp hk = new HopcroftKarp(1, 1, g); assertEquals(1, hk.maxMatching()); int[] leftMatch = hk.getLeftMatches(); int[] rightMatch = hk.getRightMatches(); assertEquals(0, leftMatch[0]); assertEquals(0, rightMatch[0]); } @Test @DisplayName("Disjoint edges match perfectly") void disjointEdges() { // L0-R0, L1-R1, L2-R2 List<List<Integer>> g = adj(3); g.get(0).add(0); g.get(1).add(1); g.get(2).add(2); HopcroftKarp hk = new HopcroftKarp(3, 3, g); assertEquals(3, hk.maxMatching()); int[] leftMatch = hk.getLeftMatches(); int[] rightMatch = hk.getRightMatches(); for (int i = 0; i < 3; i++) { assertEquals(i, leftMatch[i]); assertEquals(i, rightMatch[i]); } } @Test @DisplayName("Complete bipartite K(3,4) matches min(3,4)=3") void completeK34() { int nLeft = 3; int nRight = 4; // split declarations List<List<Integer>> g = adj(nLeft); for (int u = 0; u < nLeft; u++) { g.get(u).addAll(Arrays.asList(0, 1, 2, 3)); } HopcroftKarp hk = new HopcroftKarp(nLeft, nRight, g); assertEquals(3, hk.maxMatching()); // sanity: no two left vertices share the same matched right vertex int[] leftMatch = hk.getLeftMatches(); boolean[] used = new boolean[nRight]; for (int u = 0; u < nLeft; u++) { int v = leftMatch[u]; if (v != -1) { assertFalse(used[v]); used[v] = true; } } } @Test @DisplayName("Rectangular, sparse graph") void rectangularSparse() { // Left: 5, Right: 2 // edges: L0-R0, L1-R1, L2-R0, L3-R1 (max matching = 2) List<List<Integer>> g = adj(5); g.get(0).add(0); g.get(1).add(1); g.get(2).add(0); g.get(3).add(1); // L4 isolated HopcroftKarp hk = new HopcroftKarp(5, 2, g); assertEquals(2, hk.maxMatching()); int[] leftMatch = hk.getLeftMatches(); int[] rightMatch = hk.getRightMatches(); // Check consistency: if leftMatch[u]=v then rightMatch[v]=u for (int u = 0; u < 5; u++) { int v = leftMatch[u]; if (v != -1) { assertEquals(u, rightMatch[v]); } } } @Test @DisplayName("Layering advantage case (short augmenting paths)") void layeringAdvantage() { // Left 4, Right 4 List<List<Integer>> g = adj(4); g.get(0).addAll(Arrays.asList(0, 1)); g.get(1).addAll(Arrays.asList(1, 2)); g.get(2).addAll(Arrays.asList(2, 3)); g.get(3).addAll(Arrays.asList(0, 3)); HopcroftKarp hk = new HopcroftKarp(4, 4, g); assertEquals(4, hk.maxMatching()); // perfect matching exists } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/HierholzerAlgorithmTest.java
src/test/java/com/thealgorithms/graph/HierholzerAlgorithmTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; public class HierholzerAlgorithmTest { @Test public void testFindsEulerianCircuitInSimpleTriangleGraph() { Map<Integer, LinkedList<Integer>> graph = new HashMap<>(); graph.put(0, new LinkedList<>(Arrays.asList(1, 2))); graph.put(1, new LinkedList<>(Arrays.asList(0, 2))); graph.put(2, new LinkedList<>(Arrays.asList(0, 1))); HierholzerAlgorithm algorithm = new HierholzerAlgorithm(graph); assertTrue(algorithm.hasEulerianCircuit()); List<Integer> circuit = algorithm.findEulerianCircuit(); assertEquals(4, circuit.size()); assertEquals(circuit.get(0), circuit.get(circuit.size() - 1)); } @Test public void testFailsForGraphWithOddDegreeVertices() { Map<Integer, LinkedList<Integer>> graph = new HashMap<>(); graph.put(0, new LinkedList<>(Collections.singletonList(1))); graph.put(1, new LinkedList<>(Collections.singletonList(0))); HierholzerAlgorithm algorithm = new HierholzerAlgorithm(graph); assertFalse(algorithm.hasEulerianCircuit()); assertTrue(algorithm.findEulerianCircuit().isEmpty()); } @Test public void testFailsForDisconnectedGraph() { Map<Integer, LinkedList<Integer>> graph = new HashMap<>(); graph.put(0, new LinkedList<>(Arrays.asList(1, 2))); graph.put(1, new LinkedList<>(Arrays.asList(0, 2))); graph.put(2, new LinkedList<>(Arrays.asList(0, 1))); graph.put(3, new LinkedList<>(Arrays.asList(4, 5))); graph.put(4, new LinkedList<>(Arrays.asList(3, 5))); graph.put(5, new LinkedList<>(Arrays.asList(3, 4))); HierholzerAlgorithm algorithm = new HierholzerAlgorithm(graph); assertFalse(algorithm.hasEulerianCircuit()); } @Test public void testHandlesEmptyGraph() { Map<Integer, LinkedList<Integer>> graph = new HashMap<>(); HierholzerAlgorithm algorithm = new HierholzerAlgorithm(graph); assertTrue(algorithm.hasEulerianCircuit()); assertTrue(algorithm.findEulerianCircuit().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/graph/ConstrainedShortestPathTest.java
src/test/java/com/thealgorithms/graph/ConstrainedShortestPathTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.graph.ConstrainedShortestPath.Graph; import org.junit.jupiter.api.Test; public class ConstrainedShortestPathTest { /** * Tests a simple linear graph to verify if the solver calculates the shortest path correctly. * Expected: The minimal path cost from node 0 to node 2 should be 5 while not exceeding the resource limit. */ @Test public void testSimpleGraph() { Graph graph = new Graph(3); graph.addEdge(0, 1, 2, 3); graph.addEdge(1, 2, 3, 2); int maxResource = 5; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(5, solver.solve(0, 2)); } /** * Tests a graph where no valid path exists due to resource constraints. * Expected: The solver should return -1, indicating no path is feasible. */ @Test public void testNoPath() { Graph graph = new Graph(3); graph.addEdge(0, 1, 2, 6); graph.addEdge(1, 2, 3, 6); int maxResource = 5; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(-1, solver.solve(0, 2)); } /** * Tests a graph with multiple paths between source and destination. * Expected: The solver should choose the path with the minimal cost of 5, considering the resource limit. */ @Test public void testMultiplePaths() { Graph graph = new Graph(4); graph.addEdge(0, 1, 1, 1); graph.addEdge(1, 3, 5, 2); graph.addEdge(0, 2, 2, 1); graph.addEdge(2, 3, 3, 2); int maxResource = 3; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(5, solver.solve(0, 3)); } /** * Verifies that the solver allows a path exactly matching the resource limit. * Expected: The path is valid with a total cost of 5. */ @Test public void testExactResourceLimit() { Graph graph = new Graph(3); graph.addEdge(0, 1, 2, 3); graph.addEdge(1, 2, 3, 2); int maxResource = 5; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(5, solver.solve(0, 2)); } /** * Tests a disconnected graph where the destination node cannot be reached. * Expected: The solver should return -1, as the destination is unreachable. */ @Test public void testDisconnectedGraph() { Graph graph = new Graph(4); graph.addEdge(0, 1, 2, 2); graph.addEdge(2, 3, 3, 2); int maxResource = 5; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(-1, solver.solve(0, 3)); } /** * Tests a graph with cycles to ensure the solver does not fall into infinite loops and correctly calculates costs. * Expected: The solver should compute the minimal path cost of 6. */ @Test public void testGraphWithCycles() { Graph graph = new Graph(4); graph.addEdge(0, 1, 2, 1); graph.addEdge(1, 2, 3, 1); graph.addEdge(2, 0, 1, 1); graph.addEdge(1, 3, 4, 2); int maxResource = 3; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(6, solver.solve(0, 3)); } /** * Tests the solver's performance and correctness on a large linear graph with 1000 nodes. * Expected: The solver should efficiently calculate the shortest path with a cost of 999. */ @Test public void testLargeGraphPerformance() { int nodeCount = 1000; Graph graph = new Graph(nodeCount); for (int i = 0; i < nodeCount - 1; i++) { graph.addEdge(i, i + 1, 1, 1); } int maxResource = 1000; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(999, solver.solve(0, nodeCount - 1)); } /** * Tests a graph with isolated nodes to ensure the solver recognizes unreachable destinations. * Expected: The solver should return -1 for unreachable nodes. */ @Test public void testIsolatedNodes() { Graph graph = new Graph(5); graph.addEdge(0, 1, 2, 1); graph.addEdge(1, 2, 3, 1); int maxResource = 5; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(-1, solver.solve(0, 3)); } /** * Tests a cyclic large graph with multiple overlapping paths. * Expected: The solver should calculate the shortest path cost of 5. */ @Test public void testCyclicLargeGraph() { Graph graph = new Graph(10); for (int i = 0; i < 9; i++) { graph.addEdge(i, (i + 1) % 10, 1, 1); } graph.addEdge(0, 5, 5, 3); int maxResource = 10; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(5, solver.solve(0, 5)); } /** * Tests a large complex graph with multiple paths and varying resource constraints. * Expected: The solver should identify the optimal path with a cost of 19 within the resource limit. */ @Test public void testLargeComplexGraph() { Graph graph = new Graph(10); graph.addEdge(0, 1, 4, 2); graph.addEdge(0, 2, 3, 3); graph.addEdge(1, 3, 2, 1); graph.addEdge(2, 3, 5, 2); graph.addEdge(2, 4, 8, 4); graph.addEdge(3, 5, 7, 3); graph.addEdge(3, 6, 6, 2); graph.addEdge(4, 6, 3, 2); graph.addEdge(5, 7, 1, 1); graph.addEdge(6, 7, 2, 2); graph.addEdge(7, 8, 3, 1); graph.addEdge(8, 9, 2, 1); int maxResource = 10; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(19, solver.solve(0, 9)); } /** * Edge case test where the graph has only one node and no edges. * Expected: The minimal path cost is 0, as the start and destination are the same. */ @Test public void testSingleNodeGraph() { Graph graph = new Graph(1); int maxResource = 0; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(0, solver.solve(0, 0)); } /** * Tests a graph with multiple paths but a tight resource constraint. * Expected: The solver should return -1 if no path can be found within the resource limit. */ @Test public void testTightResourceConstraint() { Graph graph = new Graph(4); graph.addEdge(0, 1, 3, 4); graph.addEdge(1, 2, 1, 2); graph.addEdge(0, 2, 2, 2); int maxResource = 3; ConstrainedShortestPath solver = new ConstrainedShortestPath(graph, maxResource); assertEquals(2, solver.solve(0, 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/graph/TravelingSalesmanTest.java
src/test/java/com/thealgorithms/graph/TravelingSalesmanTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class TravelingSalesmanTest { // Test Case 1: A simple distance matrix with 4 cities @Test public void testBruteForceSimple() { int[][] distanceMatrix = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}}; int expectedMinDistance = 80; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingSimple() { int[][] distanceMatrix = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}}; int expectedMinDistance = 80; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 2: A distance matrix with 3 cities @Test public void testBruteForceThreeCities() { int[][] distanceMatrix = {{0, 10, 15}, {10, 0, 35}, {15, 35, 0}}; int expectedMinDistance = 60; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingThreeCities() { int[][] distanceMatrix = {{0, 10, 15}, {10, 0, 35}, {15, 35, 0}}; int expectedMinDistance = 60; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 3: A distance matrix with 5 cities (larger input) @Test public void testBruteForceFiveCities() { int[][] distanceMatrix = {{0, 2, 9, 10, 1}, {2, 0, 6, 5, 8}, {9, 6, 0, 4, 3}, {10, 5, 4, 0, 7}, {1, 8, 3, 7, 0}}; int expectedMinDistance = 15; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingFiveCities() { int[][] distanceMatrix = {{0, 2, 9, 10, 1}, {2, 0, 6, 5, 8}, {9, 6, 0, 4, 3}, {10, 5, 4, 0, 7}, {1, 8, 3, 7, 0}}; int expectedMinDistance = 15; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 4: A distance matrix with 2 cities (simple case) @Test public void testBruteForceTwoCities() { int[][] distanceMatrix = {{0, 1}, {1, 0}}; int expectedMinDistance = 2; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingTwoCities() { int[][] distanceMatrix = {{0, 1}, {1, 0}}; int expectedMinDistance = 2; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 5: A distance matrix with identical distances @Test public void testBruteForceEqualDistances() { int[][] distanceMatrix = {{0, 10, 10, 10}, {10, 0, 10, 10}, {10, 10, 0, 10}, {10, 10, 10, 0}}; int expectedMinDistance = 40; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingEqualDistances() { int[][] distanceMatrix = {{0, 10, 10, 10}, {10, 0, 10, 10}, {10, 10, 0, 10}, {10, 10, 10, 0}}; int expectedMinDistance = 40; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 6: A distance matrix with only one city @Test public void testBruteForceOneCity() { int[][] distanceMatrix = {{0}}; int expectedMinDistance = 0; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingOneCity() { int[][] distanceMatrix = {{0}}; int expectedMinDistance = 0; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, result); } // Test Case 7: Distance matrix with large numbers @Test public void testBruteForceLargeNumbers() { int[][] distanceMatrix = {{0, 1000000, 2000000}, {1000000, 0, 1500000}, {2000000, 1500000, 0}}; int expectedMinDistance = 4500000; int result = TravelingSalesman.bruteForce(distanceMatrix); assertEquals(expectedMinDistance, result); } @Test public void testDynamicProgrammingLargeNumbers() { int[][] distanceMatrix = {{0, 1000000, 2000000}, {1000000, 0, 1500000}, {2000000, 1500000, 0}}; int expectedMinDistance = 4500000; int result = TravelingSalesman.dynamicProgramming(distanceMatrix); assertEquals(expectedMinDistance, 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/graph/PredecessorConstrainedDfsTest.java
src/test/java/com/thealgorithms/graph/PredecessorConstrainedDfsTest.java
package com.thealgorithms.graph; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import com.thealgorithms.graph.PredecessorConstrainedDfs.TraversalEvent; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; class PredecessorConstrainedDfsTest { // A -> B, A -> C, B -> D, C -> D (classic diamond) private static Map<String, List<String>> diamond() { Map<String, List<String>> g = new LinkedHashMap<>(); g.put("A", List.of("B", "C")); g.put("B", List.of("D")); g.put("C", List.of("D")); g.put("D", List.of()); return g; } @Test void dfsRecursiveOrderEmitsSkipUntilAllParentsVisited() { List<TraversalEvent<String>> events = PredecessorConstrainedDfs.dfsRecursiveOrder(diamond(), "A"); // Expect visits in order and a skip for first time we meet D (via B) before C is visited. var visits = events.stream().filter(TraversalEvent::isVisit).toList(); var skips = events.stream().filter(TraversalEvent::isSkip).toList(); // Visits should be A(0), B(1), C(2), D(3) in some deterministic order given adjacency assertThat(visits).hasSize(4); assertThat(visits.get(0).node()).isEqualTo("A"); assertThat(visits.get(0).order()).isEqualTo(0); assertThat(visits.get(1).node()).isEqualTo("B"); assertThat(visits.get(1).order()).isEqualTo(1); assertThat(visits.get(2).node()).isEqualTo("C"); assertThat(visits.get(2).order()).isEqualTo(2); assertThat(visits.get(3).node()).isEqualTo("D"); assertThat(visits.get(3).order()).isEqualTo(3); // One skip when we first encountered D from B (before C was visited) assertThat(skips).hasSize(1); assertThat(skips.get(0).node()).isEqualTo("D"); assertThat(skips.get(0).note()).contains("not all parents"); } @Test void returnsEmptyWhenStartNotInGraph() { Map<Integer, List<Integer>> graph = Map.of(1, List.of(2), 2, List.of(1)); assertThat(PredecessorConstrainedDfs.dfsRecursiveOrder(graph, 99)).isEmpty(); } @Test void nullSuccessorsThrows() { assertThrows(IllegalArgumentException.class, () -> PredecessorConstrainedDfs.dfsRecursiveOrder(null, "A")); } @Test void worksWithExplicitPredecessors() { Map<Integer, List<Integer>> successors = new HashMap<>(); successors.put(10, List.of(20)); successors.put(20, List.of(30)); successors.put(30, List.of()); Map<Integer, List<Integer>> predecessors = new HashMap<>(); predecessors.put(10, List.of()); predecessors.put(20, List.of(10)); predecessors.put(30, List.of(20)); var events = PredecessorConstrainedDfs.dfsRecursiveOrder(successors, predecessors, 10); var visitNodes = events.stream().filter(TraversalEvent::isVisit).map(TraversalEvent::node).toList(); assertThat(visitNodes).containsExactly(10, 20, 30); } @Test void cycleProducesSkipsButNoInfiniteRecursion() { Map<String, List<String>> successors = new LinkedHashMap<>(); successors.put("X", List.of("Y")); successors.put("Y", List.of("X")); // 2-cycle var events = PredecessorConstrainedDfs.dfsRecursiveOrder(successors, "X"); // Only X is visited; encountering Y from X causes skip because Y's parent X is visited, // but when recursing to Y we'd hit back to X (already visited) and stop; no infinite loop. assertThat(events.stream().anyMatch(TraversalEvent::isVisit)).isTrue(); assertThat(events.stream().filter(TraversalEvent::isVisit).map(TraversalEvent::node)).contains("X"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/BronKerboschTest.java
src/test/java/com/thealgorithms/graph/BronKerboschTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class BronKerboschTest { @Test @DisplayName("Complete graph returns single clique") void completeGraph() { List<Set<Integer>> adjacency = buildGraph(4); addUndirectedEdge(adjacency, 0, 1); addUndirectedEdge(adjacency, 0, 2); addUndirectedEdge(adjacency, 0, 3); addUndirectedEdge(adjacency, 1, 2); addUndirectedEdge(adjacency, 1, 3); addUndirectedEdge(adjacency, 2, 3); List<Set<Integer>> cliques = BronKerbosch.findMaximalCliques(adjacency); assertEquals(1, cliques.size()); assertEquals(Set.of(0, 1, 2, 3), cliques.get(0)); } @Test @DisplayName("Path graph produces individual edges") void pathGraph() { List<Set<Integer>> adjacency = buildGraph(3); addUndirectedEdge(adjacency, 0, 1); addUndirectedEdge(adjacency, 1, 2); List<Set<Integer>> cliques = BronKerbosch.findMaximalCliques(adjacency); Set<Set<Integer>> result = new HashSet<>(cliques); Set<Set<Integer>> expected = Set.of(Set.of(0, 1), Set.of(1, 2)); assertEquals(expected, result); } @Test @DisplayName("Disconnected graph finds cliques per component") void disconnectedGraph() { List<Set<Integer>> adjacency = buildGraph(5); addUndirectedEdge(adjacency, 0, 1); addUndirectedEdge(adjacency, 0, 2); addUndirectedEdge(adjacency, 1, 2); addUndirectedEdge(adjacency, 3, 4); List<Set<Integer>> cliques = BronKerbosch.findMaximalCliques(adjacency); Set<Set<Integer>> result = new HashSet<>(cliques); Set<Set<Integer>> expected = Set.of(Set.of(0, 1, 2), Set.of(3, 4)); assertEquals(expected, result); } @Test @DisplayName("Null neighbor set triggers exception") void nullNeighborSet() { List<Set<Integer>> adjacency = new ArrayList<>(); adjacency.add(null); assertThrows(IllegalArgumentException.class, () -> BronKerbosch.findMaximalCliques(adjacency)); } private static List<Set<Integer>> buildGraph(int n) { List<Set<Integer>> graph = new ArrayList<>(n); for (int i = 0; i < n; i++) { graph.add(new HashSet<>()); } return graph; } private static void addUndirectedEdge(List<Set<Integer>> graph, int u, int v) { graph.get(u).add(v); graph.get(v).add(u); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/EdmondsTest.java
src/test/java/com/thealgorithms/graph/EdmondsTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; class EdmondsTest { @Test void testSimpleGraphNoCycle() { int n = 4; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); edges.add(new Edmonds.Edge(0, 1, 10)); edges.add(new Edmonds.Edge(0, 2, 1)); edges.add(new Edmonds.Edge(2, 1, 2)); edges.add(new Edmonds.Edge(2, 3, 5)); // Expected arborescence edges: (0,2), (2,1), (2,3) // Weights: 1 + 2 + 5 = 8 long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(8, result); } @Test void testGraphWithOneCycle() { int n = 4; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); edges.add(new Edmonds.Edge(0, 1, 10)); edges.add(new Edmonds.Edge(2, 1, 4)); edges.add(new Edmonds.Edge(1, 2, 5)); edges.add(new Edmonds.Edge(2, 3, 6)); // Min edges: (2,1, w=4), (1,2, w=5), (2,3, w=6) // Cycle: 1 -> 2 -> 1, cost = 4 + 5 = 9 // Contract {1,2} to C. // New edge (0,C) with w = 10 - min_in(1) = 10 - 4 = 6 // New edge (C,3) with w = 6 // Contracted MSA cost = 6 + 6 = 12 // Total cost = cycle_cost + contracted_msa_cost = 9 + 12 = 21 long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(21, result); } @Test void testComplexGraphWithCycle() { int n = 6; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); edges.add(new Edmonds.Edge(0, 1, 10)); edges.add(new Edmonds.Edge(0, 2, 20)); edges.add(new Edmonds.Edge(1, 2, 5)); edges.add(new Edmonds.Edge(2, 3, 10)); edges.add(new Edmonds.Edge(3, 1, 3)); edges.add(new Edmonds.Edge(1, 4, 7)); edges.add(new Edmonds.Edge(3, 4, 2)); edges.add(new Edmonds.Edge(4, 5, 5)); // Min edges: (3,1,3), (1,2,5), (2,3,10), (3,4,2), (4,5,5) // Cycle: 1->2->3->1, cost = 5+10+3=18 // Contract {1,2,3} to C. // Edge (0,1,10) -> (0,C), w = 10-3=7 // Edge (0,2,20) -> (0,C), w = 20-5=15. Min is 7. // Edge (1,4,7) -> (C,4,7) // Edge (3,4,2) -> (C,4,2). Min is 2. // Edge (4,5,5) -> (4,5,5) // Contracted MSA: (0,C,7), (C,4,2), (4,5,5). Cost = 7+2+5=14 // Total cost = 18 + 14 = 32 long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(32, result); } @Test void testUnreachableNode() { int n = 4; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); edges.add(new Edmonds.Edge(0, 1, 10)); edges.add(new Edmonds.Edge(2, 3, 5)); // Node 2 and 3 are unreachable from root 0 long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(-1, result); } @Test void testNoEdgesToNonRootNodes() { int n = 3; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); edges.add(new Edmonds.Edge(0, 1, 10)); // Node 2 is unreachable long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(-1, result); } @Test void testSingleNode() { int n = 1; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(0, result); } @Test void testInvalidInputThrowsException() { List<Edmonds.Edge> edges = new ArrayList<>(); assertThrows(IllegalArgumentException.class, () -> Edmonds.findMinimumSpanningArborescence(0, edges, 0)); assertThrows(IllegalArgumentException.class, () -> Edmonds.findMinimumSpanningArborescence(5, edges, -1)); assertThrows(IllegalArgumentException.class, () -> Edmonds.findMinimumSpanningArborescence(5, edges, 5)); } @Test void testCoverageForEdgeSelectionLogic() { int n = 3; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); // This will cover the `edge.weight < minWeightEdge[edge.to]` being false. edges.add(new Edmonds.Edge(0, 1, 10)); edges.add(new Edmonds.Edge(2, 1, 20)); // This will cover the `edge.to != root` being false. edges.add(new Edmonds.Edge(1, 0, 100)); // A regular edge to make the graph complete edges.add(new Edmonds.Edge(0, 2, 5)); // Expected MSA: (0,1, w=10) and (0,2, w=5). Total weight = 15. long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(15, result); } @Test void testCoverageForContractedSelfLoop() { int n = 4; int root = 0; List<Edmonds.Edge> edges = new ArrayList<>(); // Connect root to the cycle components edges.add(new Edmonds.Edge(0, 1, 20)); // Create a cycle 1 -> 2 -> 1 edges.add(new Edmonds.Edge(1, 2, 5)); edges.add(new Edmonds.Edge(2, 1, 5)); // This is the CRITICAL edge for coverage: // It connects two nodes (1 and 2) that are part of the SAME cycle. // After contracting cycle {1, 2} into a supernode C, this edge becomes (C, C), // which means newU == newV. This will trigger the `false` branch of the `if`. edges.add(new Edmonds.Edge(1, 1, 100)); // Also a self-loop on a cycle node. // Add another edge to ensure node 3 is reachable edges.add(new Edmonds.Edge(1, 3, 10)); // Cycle {1,2} has cost 5+5=10. // Contract {1,2} to supernode C. // Edge (0,1,20) becomes (0,C, w=20-5=15). // Edge (1,3,10) becomes (C,3, w=10). // Edge (1,1,100) is discarded because newU == newV. // Cost of contracted graph = 15 + 10 = 25. // Total cost = cycle cost + contracted cost = 10 + 25 = 35. long result = Edmonds.findMinimumSpanningArborescence(n, edges, root); assertEquals(35, result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false