Shuu12121/CodeModernBERT-Crow-v3-len1024
Fill-Mask • 0.1B • Updated
• 58
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 |