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/graph/HierholzerEulerianPathTest.java
src/test/java/com/thealgorithms/graph/HierholzerEulerianPathTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; /** * Unit tests for {@link HierholzerEulerianPath}. * * This test suite validates Hierholzer's Algorithm implementation * for finding Eulerian Paths and Circuits in directed graphs. * * <p>Coverage includes: * <ul> * <li>Basic Eulerian Circuit</li> * <li>Eulerian Path</li> * <li>Disconnected graphs</li> * <li>Single-node graphs</li> * <li>Graphs with no edges</li> * <li>Graphs that do not have any Eulerian Path/Circuit</li> * </ul> * </p> */ class HierholzerEulerianPathTest { @Test void testSimpleEulerianCircuit() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(3); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 0); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Eulerian Circuit: [0, 1, 2, 0] List<Integer> expected = Arrays.asList(0, 1, 2, 0); assertEquals(expected, result); } @Test void testEulerianPathDifferentStartEnd() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(4); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 1); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Eulerian Path: [0, 1, 2, 3, 1] List<Integer> expected = Arrays.asList(0, 1, 2, 3, 1); assertEquals(expected, result); } @Test void testNoEulerianPathExists() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(3); graph.addEdge(0, 1); graph.addEdge(1, 2); // Edge 2->0 missing, so it's not Eulerian Circuit HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); assertEquals(result, Arrays.asList(0, 1, 2)); } @Test void testDisconnectedGraph() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(4); graph.addEdge(0, 1); graph.addEdge(2, 3); // disconnected component HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Disconnected graph cannot have an Eulerian path assertTrue(result.isEmpty()); } @Test void testGraphWithSelfLoop() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(3); graph.addEdge(0, 0); // self loop graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 0); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Eulerian Circuit with self-loop included: [0, 0, 1, 2, 0] assertEquals(Arrays.asList(0, 0, 1, 2, 0), result); } @Test void testSingleNodeNoEdges() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(1); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Only one vertex and no edges assertEquals(Collections.singletonList(0), result); } @Test void testSingleNodeWithLoop() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(1); graph.addEdge(0, 0); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Eulerian circuit on a single node with a self-loop assertEquals(Arrays.asList(0, 0), result); } @Test void testComplexEulerianCircuit() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(5); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.addEdge(4, 0); graph.addEdge(1, 3); graph.addEdge(3, 1); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Verify all edges are used int totalEdges = 7; assertEquals(totalEdges + 1, result.size(), "Path must contain all edges + 1 vertices"); assertEquals(result.get(0), result.get(result.size() - 1), "Must form a circuit"); } @Test void testMultipleEdgesBetweenSameNodes() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(3); graph.addEdge(0, 1); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 0); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Hava a Eulerian Path but not a Eulerian Circuit assertEquals(result, Arrays.asList(0, 1, 2, 0, 1)); } @Test void testCoverageForEmptyGraph() { HierholzerEulerianPath.Graph graph = new HierholzerEulerianPath.Graph(0); HierholzerEulerianPath solver = new HierholzerEulerianPath(graph); List<Integer> result = solver.findEulerianPath(); // Empty graph has no vertices or path assertTrue(result.isEmpty()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/graph/YensKShortestPathsTest.java
src/test/java/com/thealgorithms/graph/YensKShortestPathsTest.java
package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class YensKShortestPathsTest { @Test @DisplayName("Basic K-shortest paths on small directed graph") void basicKPaths() { // Graph (directed) with non-negative weights, -1 = no edge // 0 -> 1 (1), 0 -> 2 (2), 1 -> 3 (1), 2 -> 3 (1), 0 -> 3 (5), 1 -> 2 (1) int n = 4; int[][] w = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { w[i][j] = -1; } } w[0][1] = 1; w[0][2] = 2; w[1][3] = 1; w[2][3] = 1; w[0][3] = 5; w[1][2] = 1; List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, 0, 3, 3); // Expected K=3 loopless shortest paths from 0 to 3, ordered by total cost: // 1) 0-1-3 (cost 2) // 2) 0-2-3 (cost 3) // 3) 0-1-2-3 (cost 3) -> tie with 0-2-3; tie-broken lexicographically by nodes assertEquals(3, paths.size()); assertEquals(List.of(0, 1, 3), paths.get(0)); assertEquals(List.of(0, 1, 2, 3), paths.get(1)); // lexicographically before [0,2,3] assertEquals(List.of(0, 2, 3), paths.get(2)); } @Test @DisplayName("K larger than available paths returns only existing ones") void kLargerThanAvailable() { int[][] w = {{-1, 1, -1}, {-1, -1, 1}, {-1, -1, -1}}; // Only one simple path 0->1->2 List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, 0, 2, 5); assertEquals(1, paths.size()); assertEquals(List.of(0, 1, 2), paths.get(0)); } @Test @DisplayName("No path returns empty list") void noPath() { int[][] w = {{-1, -1}, {-1, -1}}; List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, 0, 1, 3); assertEquals(0, paths.size()); } @Test @DisplayName("Source equals destination returns trivial path") void sourceEqualsDestination() { int[][] w = {{-1, 1}, {-1, -1}}; List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, 0, 0, 2); // First path is [0] assertEquals(1, paths.size()); assertEquals(List.of(0), paths.get(0)); } @Test @DisplayName("Negative weight entries (other than -1) are rejected") void negativeWeightsRejected() { int[][] w = {{-1, -2}, {-1, -1}}; assertThrows(IllegalArgumentException.class, () -> YensKShortestPaths.kShortestPaths(w, 0, 1, 2)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java
src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Collections; import org.junit.jupiter.api.Test; public class JobSequencingTest { @Test public void testJobSequencingWithExampleCase() { ArrayList<JobSequencing.Job> jobs = new ArrayList<>(); jobs.add(new JobSequencing.Job('a', 2, 100)); jobs.add(new JobSequencing.Job('b', 1, 19)); jobs.add(new JobSequencing.Job('c', 2, 27)); jobs.add(new JobSequencing.Job('d', 1, 25)); jobs.add(new JobSequencing.Job('e', 3, 15)); Collections.sort(jobs); String jobSequence = JobSequencing.findJobSequence(jobs, jobs.size()); assertEquals("Job Sequence: c -> a -> e", jobSequence); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java
src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java
package com.thealgorithms.greedyalgorithms; 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 CoinChangeTest { @Test public void testCoinChangeProblemWithValidAmount() { ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(500, 50, 20, 20, 1)); ArrayList<Integer> coins = CoinChange.coinChangeProblem(591); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithLargeAmount() { List<Integer> expected = singletonList(2000); ArrayList<Integer> coins = CoinChange.coinChangeProblem(2000); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithPartialCoins2() { ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(500, 50, 20)); ArrayList<Integer> coins = CoinChange.coinChangeProblem(570); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithSmallAmount() { ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(2, 1)); ArrayList<Integer> coins = CoinChange.coinChangeProblem(3); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithLargeAmountAndMultipleDenominations() { ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(2000, 2000, 2000, 2000, 500, 500, 500, 100, 100, 100, 100, 50, 20, 20, 5, 2, 2)); ArrayList<Integer> coins = CoinChange.coinChangeProblem(9999); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithAllDenominations() { ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(2000, 500, 100, 100, 100, 50, 20, 10, 5, 2, 1)); ArrayList<Integer> coins = CoinChange.coinChangeProblem(2888); assertEquals(expected, coins); } @Test public void testCoinChangeProblemWithZeroAmount() { ArrayList<Integer> expected = new ArrayList<>(); ArrayList<Integer> coins = CoinChange.coinChangeProblem(0); assertEquals(expected, coins); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java
src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java
package com.thealgorithms.greedyalgorithms; 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 BandwidthAllocationTest { @ParameterizedTest @MethodSource("bandwidthProvider") public void testMaxValue(int capacity, int[] bandwidths, int[] values, int expected) { assertEquals(expected, BandwidthAllocation.maxValue(capacity, bandwidths, values)); } private static Stream<Arguments> bandwidthProvider() { return Stream.of(Arguments.of(50, new int[] {20, 10, 30}, new int[] {40, 20, 30}, 80), Arguments.of(0, new int[] {5, 10}, new int[] {10, 20}, 0), Arguments.of(5, new int[] {5, 10}, new int[] {10, 20}, 10), Arguments.of(15, new int[] {10, 20}, new int[] {10, 25}, 18), Arguments.of(25, new int[] {10, 15, 20}, new int[] {10, 30, 50}, 60)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java
src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; 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 EgyptianFractionTest { @ParameterizedTest @MethodSource("fractionProvider") public void testGetEgyptianFraction(int numerator, int denominator, List<String> expected) { assertEquals(expected, EgyptianFraction.getEgyptianFraction(numerator, denominator)); } private static Stream<Arguments> fractionProvider() { return Stream.of(Arguments.of(2, 3, List.of("1/2", "1/6")), Arguments.of(3, 10, List.of("1/4", "1/20")), Arguments.of(1, 3, List.of("1/3")), Arguments.of(1, 2, List.of("1/2")), Arguments.of(4, 13, List.of("1/4", "1/18", "1/468"))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java
src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class BinaryAdditionTest { BinaryAddition binaryAddition = new BinaryAddition(); @Test public void testEqualLengthNoCarry() { String a = "1010"; String b = "1101"; String expected = "10111"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testEqualLengthWithCarry() { String a = "1111"; String b = "1111"; String expected = "11110"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testDifferentLengths() { String a = "101"; String b = "11"; String expected = "1000"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testAllZeros() { String a = "0"; String b = "0"; String expected = "0"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testAllOnes() { String a = "1111"; String b = "1111"; String expected = "11110"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testOneZeroString() { String a = "0"; String b = "10101"; String expected = "10101"; assertEquals(expected, binaryAddition.addBinary(a, b)); // Test the other way around a = "10101"; b = "0"; expected = "10101"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testLargeBinaryNumbers() { String a = "101010101010101010101010101010"; String b = "110110110110110110110110110110"; String expected = "1100001100001100001100001100000"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testOneMuchLonger() { String a = "1"; String b = "11111111"; String expected = "100000000"; assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testEmptyStrings() { String a = ""; String b = ""; String expected = ""; // Adding two empty strings should return 0 assertEquals(expected, binaryAddition.addBinary(a, b)); } @Test public void testAlternatingBits() { String a = "10101010"; String b = "01010101"; String expected = "11111111"; assertEquals(expected, binaryAddition.addBinary(a, b)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java
src/test/java/com/thealgorithms/greedyalgorithms/OptimalFileMergingTest.java
package com.thealgorithms.greedyalgorithms; 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 OptimalFileMergingTest { @ParameterizedTest @MethodSource("fileMergingProvider") public void testMinMergeCost(int[] files, int expected) { assertEquals(expected, OptimalFileMerging.minMergeCost(files)); } private static Stream<Arguments> fileMergingProvider() { return Stream.of(Arguments.of(new int[] {4, 3, 2, 6}, 29), Arguments.of(new int[] {5}, 0), Arguments.of(new int[] {2, 2, 2}, 10), Arguments.of(new int[] {10, 5, 3, 2}, 35), Arguments.of(new int[] {1, 1, 1, 1}, 8), Arguments.of(new int[] {1, 2, 3, 4, 5}, 33), Arguments.of(new int[] {1, 2, 3, 4, 5, 6}, 51), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7}, 74), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8}, 102), Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, 135)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java
src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class FractionalKnapsackTest { @Test public void testFractionalKnapsackWithExampleCase() { int[] weight = {10, 20, 30}; int[] value = {60, 100, 120}; int capacity = 50; assertEquals(240, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); } @Test public void testFractionalKnapsackWithZeroCapacity() { int[] weight = {10, 20, 30}; int[] value = {60, 100, 120}; int capacity = 0; assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); } @Test public void testFractionalKnapsackWithEmptyItems() { int[] weight = {}; int[] value = {}; int capacity = 50; assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java
src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class KCentersTest { @Test public void testFindKCenters() { int[][] distances = {{0, 2, 3, 4}, {2, 0, 5, 1}, {3, 5, 0, 7}, {4, 1, 7, 0}}; assertEquals(4, KCenters.findKCenters(distances, 2)); assertEquals(2, KCenters.findKCenters(distances, 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/greedyalgorithms/DigitSeparationTest.java
src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; public class DigitSeparationTest { @Test public void testDigitSeparationReverseOrderSingleDigit() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationReverseOrder(5); assertEquals(List.of(5L), result); } @Test public void testDigitSeparationReverseOrderMultipleDigits() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationReverseOrder(123); assertEquals(List.of(3L, 2L, 1L), result); } @Test public void testDigitSeparationReverseOrderLargeNumber() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationReverseOrder(123456789); assertEquals(List.of(9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L), result); } @Test public void testDigitSeparationReverseOrderZero() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationReverseOrder(0); assertEquals(List.of(0L), result); } @Test public void testDigitSeparationReverseOrderNegativeNumbers() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationReverseOrder(-123); assertEquals(List.of(3L, 2L, 1L), result); } @Test public void testDigitSeparationForwardOrderSingleDigit() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationForwardOrder(5); assertEquals(List.of(5L), result); } @Test public void testDigitSeparationForwardOrderMultipleDigits() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationForwardOrder(123); assertEquals(List.of(1L, 2L, 3L), result); } @Test public void testDigitSeparationForwardOrderLargeNumber() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationForwardOrder(123456789); assertEquals(List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L), result); } @Test public void testDigitSeparationForwardOrderZero() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationForwardOrder(0); assertEquals(List.of(0L), result); } @Test public void testDigitSeparationForwardOrderNegativeNumber() { DigitSeparation digitSeparation = new DigitSeparation(); List<Long> result = digitSeparation.digitSeparationForwardOrder(-123); assertEquals(List.of(1L, 2L, 3L), 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/greedyalgorithms/MinimumWaitingTimeTest.java
src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java
package com.thealgorithms.greedyalgorithms; 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 MinimumWaitingTimeTest { @ParameterizedTest @MethodSource("provideTestCases") public void testMinimumWaitingTime(int[] queries, int expected) { assertEquals(expected, MinimumWaitingTime.minimumWaitingTime(queries)); } private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new int[] {3, 2, 1, 2, 6}, 17), Arguments.of(new int[] {3, 2, 1}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 10), Arguments.of(new int[] {5, 5, 5, 5}, 30), Arguments.of(new int[] {}, 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/greedyalgorithms/MinimizingLatenessTest.java
src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.greedyalgorithms.MinimizingLateness.Job; import org.junit.jupiter.api.Test; public class MinimizingLatenessTest { @Test void testCalculateLateness() { // Test case with three jobs Job job1 = new Job("Job1", 4, 6); Job job2 = new Job("Job2", 2, 8); Job job3 = new Job("Job3", 1, 9); Job job4 = new Job("Job4", 5, 9); Job job5 = new Job("Job5", 4, 10); Job job6 = new Job("Job6", 3, 5); MinimizingLateness.calculateLateness(job1, job2, job3, job4, job5, job6); // Check lateness for each job assertEquals(6, job4.lateness); assertEquals(0, job6.lateness); assertEquals(1, job2.lateness); } @Test void testCheckStartTime() { Job job1 = new Job("Job1", 2, 5); Job job2 = new Job("Job2", 1, 7); Job job3 = new Job("Job3", 3, 8); Job job4 = new Job("Job4", 2, 4); Job job5 = new Job("Job5", 4, 10); MinimizingLateness.calculateLateness(job1, job2, job3, job4, job5); assertEquals(2, job1.startTime); assertEquals(5, job3.startTime); assertEquals(8, job5.startTime); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java
src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java
package com.thealgorithms.greedyalgorithms; 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 ActivitySelectionTest { @Test public void testActivitySelection() { int[] start = {1, 3, 0, 5, 8, 5}; int[] end = {2, 4, 6, 7, 9, 9}; ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(0, 1, 3, 4)); assertEquals(expected, result); } @Test public void testSingleActivity() { int[] start = {1}; int[] end = {2}; ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); List<Integer> expected = singletonList(0); assertEquals(expected, result); } @Test public void testNoOverlap() { int[] start = {1, 2, 3}; int[] end = {2, 3, 4}; ArrayList<Integer> result = ActivitySelection.activitySelection(start, end); ArrayList<Integer> expected = new ArrayList<>(Arrays.asList(0, 1, 2)); 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/greedyalgorithms/StockProfitCalculatorTest.java
src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java
package com.thealgorithms.greedyalgorithms; 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 StockProfitCalculatorTest { @ParameterizedTest @MethodSource("provideTestCases") public void testMaxProfit(int[] prices, int expected) { assertEquals(expected, StockProfitCalculator.maxProfit(prices)); } private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new int[] {7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[] {7, 6, 4, 3, 1}, 0), Arguments.of(new int[] {5, 5, 5, 5, 5}, 0), Arguments.of(new int[] {10}, 0), Arguments.of(new int[] {1, 5}, 4), Arguments.of(new int[] {2, 4, 1, 3, 7, 5}, 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/greedyalgorithms/MergeIntervalsTest.java
src/test/java/com/thealgorithms/greedyalgorithms/MergeIntervalsTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class MergeIntervalsTest { @Test public void testMergeIntervalsWithOverlappingIntervals() { // Test case where some intervals overlap and should be merged int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}}; int[][] expected = {{1, 6}, {8, 10}, {15, 18}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithNoOverlap() { // Test case where intervals do not overlap int[][] intervals = {{1, 2}, {3, 4}, {5, 6}}; int[][] expected = {{1, 2}, {3, 4}, {5, 6}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithCompleteOverlap() { // Test case where intervals completely overlap int[][] intervals = {{1, 5}, {2, 4}, {3, 6}}; int[][] expected = {{1, 6}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithSingleInterval() { // Test case where only one interval is given int[][] intervals = {{1, 2}}; int[][] expected = {{1, 2}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithEmptyArray() { // Test case where the input array is empty int[][] intervals = {}; int[][] expected = {}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithIdenticalIntervals() { // Test case where multiple identical intervals are given int[][] intervals = {{1, 3}, {1, 3}, {1, 3}}; int[][] expected = {{1, 3}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } @Test public void testMergeIntervalsWithRandomIntervals() { // Test case with a mix of overlapping and non-overlapping intervals int[][] intervals = {{1, 4}, {5, 7}, {2, 6}, {8, 10}}; int[][] expected = {{1, 7}, {8, 10}}; int[][] result = MergeIntervals.merge(intervals); assertArrayEquals(expected, result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java
src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java
package com.thealgorithms.greedyalgorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; public class GaleShapleyTest { @Test public void testStableMatch() { Map<String, LinkedList<String>> womenPrefs = new HashMap<>(); womenPrefs.put("A", new LinkedList<>(List.of("X", "Y", "Z"))); womenPrefs.put("B", new LinkedList<>(List.of("Y", "X", "Z"))); womenPrefs.put("C", new LinkedList<>(List.of("X", "Y", "Z"))); Map<String, LinkedList<String>> menPrefs = new HashMap<>(); menPrefs.put("X", new LinkedList<>(List.of("A", "B", "C"))); menPrefs.put("Y", new LinkedList<>(List.of("B", "A", "C"))); menPrefs.put("Z", new LinkedList<>(List.of("A", "B", "C"))); Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs); Map<String, String> expected = new HashMap<>(); expected.put("A", "X"); expected.put("B", "Y"); expected.put("C", "Z"); assertEquals(expected, result); } @Test public void testSinglePair() { Map<String, LinkedList<String>> womenPrefs = new HashMap<>(); womenPrefs.put("A", new LinkedList<>(List.of("X"))); Map<String, LinkedList<String>> menPrefs = new HashMap<>(); menPrefs.put("X", new LinkedList<>(List.of("A"))); Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs); Map<String, String> expected = new HashMap<>(); expected.put("A", "X"); assertEquals(expected, result); } @Test public void testEqualPreferences() { Map<String, LinkedList<String>> womenPrefs = new HashMap<>(); womenPrefs.put("A", new LinkedList<>(List.of("X", "Y", "Z"))); womenPrefs.put("B", new LinkedList<>(List.of("X", "Y", "Z"))); womenPrefs.put("C", new LinkedList<>(List.of("X", "Y", "Z"))); Map<String, LinkedList<String>> menPrefs = new HashMap<>(); menPrefs.put("X", new LinkedList<>(List.of("A", "B", "C"))); menPrefs.put("Y", new LinkedList<>(List.of("A", "B", "C"))); menPrefs.put("Z", new LinkedList<>(List.of("A", "B", "C"))); Map<String, String> result = GaleShapley.stableMatch(womenPrefs, menPrefs); Map<String, String> expected = new HashMap<>(); expected.put("A", "X"); expected.put("B", "Y"); expected.put("C", "Z"); 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/matrix/MatrixRankTest.java
src/test/java/com/thealgorithms/matrix/MatrixRankTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; 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 MatrixRankTest { private static Stream<Arguments> validInputStream() { return Stream.of(Arguments.of(3, new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(0, new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}), Arguments.of(1, new double[][] {{1}}), Arguments.of(2, new double[][] {{1, 2}, {3, 4}}), Arguments.of(2, new double[][] {{3, -1, 2}, {-3, 1, 2}, {-6, 2, 4}}), Arguments.of(3, new double[][] {{2, 3, 0, 1}, {1, 0, 1, 2}, {-1, 1, 1, -2}, {1, 5, 3, -1}}), Arguments.of(1, new double[][] {{1, 2, 3}, {3, 6, 9}}), Arguments.of(2, new double[][] {{0.25, 0.5, 0.75, 2}, {1.5, 3, 4.5, 6}, {1, 2, 3, 4}})); } private static Stream<Arguments> invalidInputStream() { return Stream.of(Arguments.of((Object) new double[][] {{1, 2}, {10}, {100, 200, 300}}), // jagged array Arguments.of((Object) new double[][] {}), // empty matrix Arguments.of((Object) new double[][] {{}, {}}), // empty row Arguments.of((Object) null), // null matrix Arguments.of((Object) new double[][] {{1, 2}, null}) // null row ); } @ParameterizedTest @MethodSource("validInputStream") void computeRankTests(int expectedRank, double[][] matrix) { int originalHashCode = Arrays.deepHashCode(matrix); int rank = MatrixRank.computeRank(matrix); int newHashCode = Arrays.deepHashCode(matrix); assertEquals(expectedRank, rank); assertEquals(originalHashCode, newHashCode); } @ParameterizedTest @MethodSource("invalidInputStream") void computeRankWithInvalidMatrix(double[][] matrix) { assertThrows(IllegalArgumentException.class, () -> MatrixRank.computeRank(matrix)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/SolveSystemTest.java
src/test/java/com/thealgorithms/matrix/SolveSystemTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class SolveSystemTest { @ParameterizedTest @MethodSource({"matrixGenerator"}) void solveSystem(double[][] matrix, double[] constants, double[] solution) { double[] expected = SolveSystem.solveSystem(matrix, constants); assertArrayEquals(expected, solution, 1.0E-10, "Solution does not match expected"); } private static Stream<Arguments> matrixGenerator() { return Stream.of(Arguments.of(new double[][] {{-5, 8, -4}, {0, 6, 3}, {0, 0, -4}}, new double[] {38, -9, 20}, new double[] {-2, 1, -5}), Arguments.of(new double[][] {{-2, -1, -1}, {3, 4, 1}, {3, 6, 5}}, new double[] {-11, 19, 43}, new double[] {2, 2, 5})); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/StochasticMatrixTest.java
src/test/java/com/thealgorithms/matrix/StochasticMatrixTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class StochasticMatrixTest { @Test void testRowStochasticMatrix() { double[][] matrix = {{0.2, 0.5, 0.3}, {0.1, 0.6, 0.3}}; assertTrue(StochasticMatrix.isRowStochastic(matrix)); assertFalse(StochasticMatrix.isColumnStochastic(matrix)); } @Test void testColumnStochasticMatrix() { double[][] matrix = {{0.4, 0.2}, {0.6, 0.8}}; assertTrue(StochasticMatrix.isColumnStochastic(matrix)); } @Test void testInvalidMatrix() { double[][] matrix = {{0.5, -0.5}, {0.5, 1.5}}; assertFalse(StochasticMatrix.isRowStochastic(matrix)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/MatrixUtilTest.java
src/test/java/com/thealgorithms/matrix/MatrixUtilTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.matrix.utils.MatrixUtil; import java.math.BigDecimal; import java.util.Objects; import org.junit.jupiter.api.Test; class MatrixUtilTest { @Test void add() { final BigDecimal[][] matrix1 = { {new BigDecimal(3), BigDecimal.TWO}, {BigDecimal.ZERO, BigDecimal.ONE}, }; final BigDecimal[][] matrix2 = { {BigDecimal.ONE, new BigDecimal(3)}, {BigDecimal.TWO, BigDecimal.ZERO}, }; final BigDecimal[][] actual = MatrixUtil.add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { {new BigDecimal(4), new BigDecimal(5)}, {BigDecimal.TWO, BigDecimal.ONE}, }; assertTrue(Objects.deepEquals(actual, expected)); } @Test void subtract() { final BigDecimal[][] matrix1 = { {BigDecimal.ONE, new BigDecimal(4)}, {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] matrix2 = { {BigDecimal.TWO, BigDecimal.ZERO}, {new BigDecimal(-2), new BigDecimal(-3)}, }; final BigDecimal[][] actual = MatrixUtil.subtract(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { {new BigDecimal(-1), new BigDecimal(4)}, {new BigDecimal(7), new BigDecimal(9)}, }; assertTrue(Objects.deepEquals(actual, expected)); } @Test void multiply() { final BigDecimal[][] matrix1 = { {BigDecimal.ONE, BigDecimal.TWO, new BigDecimal(3)}, {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}, }; final BigDecimal[][] matrix2 = { {BigDecimal.ONE, BigDecimal.TWO}, {new BigDecimal(3), new BigDecimal(4)}, {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] actual = MatrixUtil.multiply(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { {new BigDecimal(22), new BigDecimal(28)}, {new BigDecimal(49), new BigDecimal(64)}, {new BigDecimal(76), new BigDecimal(100)}, }; assertTrue(Objects.deepEquals(actual, 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/matrix/MatrixTransposeTest.java
src/test/java/com/thealgorithms/matrix/MatrixTransposeTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class MatrixTransposeTest { private static Stream<Arguments> provideValidMatrixTestCases() { return Stream.of(Arguments.of(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, new int[][] {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}, "Transpose of square matrix"), Arguments.of(new int[][] {{1, 2}, {3, 4}, {5, 6}}, new int[][] {{1, 3, 5}, {2, 4, 6}}, "Transpose of rectangular matrix"), Arguments.of(new int[][] {{1, 2, 3}}, new int[][] {{1}, {2}, {3}}, "Transpose of single-row matrix"), Arguments.of(new int[][] {{1}, {2}, {3}}, new int[][] {{1, 2, 3}}, "Transpose of single-column matrix")); } private static Stream<Arguments> provideInvalidMatrixTestCases() { return Stream.of(Arguments.of(new int[0][0], "Empty matrix should throw IllegalArgumentException"), Arguments.of(null, "Null matrix should throw IllegalArgumentException")); } @ParameterizedTest(name = "Test case {index}: {2}") @MethodSource("provideValidMatrixTestCases") void testValidMatrixTranspose(int[][] input, int[][] expected, String description) { assertArrayEquals(expected, MatrixTranspose.transpose(input), description); } @ParameterizedTest(name = "Test case {index}: {1}") @MethodSource("provideInvalidMatrixTestCases") void testInvalidMatrixTranspose(int[][] input, String description) { assertThrows(IllegalArgumentException.class, () -> MatrixTranspose.transpose(input), description); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/LUDecompositionTest.java
src/test/java/com/thealgorithms/matrix/LUDecompositionTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class LUDecompositionTest { @Test public void testLUDecomposition() { double[][] a = {{4, 3}, {6, 3}}; // Perform LU decomposition LUDecomposition.LU lu = LUDecomposition.decompose(a); double[][] l = lu.l; double[][] u = lu.u; // Reconstruct a from l and u double[][] reconstructed = multiplyMatrices(l, u); // Assert that reconstructed matrix matches original a for (int i = 0; i < a.length; i++) { assertArrayEquals(a[i], reconstructed[i], 1e-9); } } // Helper method to multiply two matrices private double[][] multiplyMatrices(double[][] a, double[][] b) { int n = a.length; double[][] c = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return 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/matrix/MedianOfMatrixTest.java
src/test/java/com/thealgorithms/matrix/MedianOfMatrixTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; public class MedianOfMatrixTest { @Test public void testMedianWithOddNumberOfElements() { List<List<Integer>> matrix = new ArrayList<>(); matrix.add(Arrays.asList(1, 3, 5)); matrix.add(Arrays.asList(2, 4, 6)); matrix.add(Arrays.asList(7, 8, 9)); int result = MedianOfMatrix.median(matrix); assertEquals(5, result); } @Test public void testMedianWithEvenNumberOfElements() { List<List<Integer>> matrix = new ArrayList<>(); matrix.add(Arrays.asList(2, 4)); matrix.add(Arrays.asList(1, 3)); int result = MedianOfMatrix.median(matrix); assertEquals(2, result); } @Test public void testMedianSingleElement() { List<List<Integer>> matrix = new ArrayList<>(); matrix.add(List.of(1)); assertEquals(1, MedianOfMatrix.median(matrix)); } @Test void testEmptyMatrixThrowsException() { Iterable<List<Integer>> emptyMatrix = Collections.emptyList(); assertThrows(IllegalArgumentException.class, () -> MedianOfMatrix.median(emptyMatrix), "Expected median() to throw, but it didn't"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrderTest.java
src/test/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrderTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; class PrintAMatrixInSpiralOrderTest { private final PrintAMatrixInSpiralOrder spiralPrinter = new PrintAMatrixInSpiralOrder(); @Test void testSquareMatrix() { int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; List<Integer> expected = Arrays.asList(1, 2, 3, 6, 9, 8, 7, 4, 5); assertEquals(expected, spiralPrinter.print(matrix, 3, 3)); } @Test void testRectangularMatrixMoreRows() { int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; List<Integer> expected = Arrays.asList(1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8); assertEquals(expected, spiralPrinter.print(matrix, 4, 3)); } @Test void testRectangularMatrixMoreCols() { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; List<Integer> expected = Arrays.asList(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7); assertEquals(expected, spiralPrinter.print(matrix, 3, 4)); } @Test void testSingleRow() { int[][] matrix = {{1, 2, 3, 4}}; List<Integer> expected = Arrays.asList(1, 2, 3, 4); assertEquals(expected, spiralPrinter.print(matrix, 1, 4)); } @Test void testSingleColumn() { int[][] matrix = {{1}, {2}, {3}}; List<Integer> expected = Arrays.asList(1, 2, 3); assertEquals(expected, spiralPrinter.print(matrix, 3, 1)); } @Test void testEmptyMatrix() { int[][] matrix = new int[0][0]; List<Integer> expected = Collections.emptyList(); assertEquals(expected, spiralPrinter.print(matrix, 0, 0)); } @Test void testOneElementMatrix() { int[][] matrix = {{42}}; List<Integer> expected = Collections.singletonList(42); assertEquals(expected, spiralPrinter.print(matrix, 1, 1)); } @Test void testMatrixWithNegativeNumbers() { int[][] matrix = {{-1, -2}, {-3, -4}}; List<Integer> expected = Arrays.asList(-1, -2, -4, -3); assertEquals(expected, spiralPrinter.print(matrix, 2, 2)); } @Test void testLargeSquareMatrix() { int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; List<Integer> expected = Arrays.asList(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, 10, 11, 17, 26, 25, 24, 15, 16); assertEquals(expected, spiralPrinter.print(matrix, 5, 5)); } @Test void testSingleRowWithTwoElements() { int[][] matrix = {{2, 2}}; List<Integer> expected = Arrays.asList(2, 2); assertEquals(expected, spiralPrinter.print(matrix, 1, 2)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/InverseOfMatrixTest.java
src/test/java/com/thealgorithms/matrix/InverseOfMatrixTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class InverseOfMatrixTest { @ParameterizedTest @MethodSource("provideTestCases") void testInvert(double[][] matrix, double[][] expectedInverse) { double[][] result = InverseOfMatrix.invert(matrix); assertMatrixEquals(expectedInverse, result); } private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(new double[][] {{4, 7}, {2, 6}}, new double[][] {{0.6, -0.7}, {-0.2, 0.4}})); } private void assertMatrixEquals(double[][] expected, double[][] actual) { for (int i = 0; i < expected.length; i++) { assertArrayEquals(expected[i], actual[i], 1.0E-10, "Row " + i + " is not equal"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/MatrixMultiplicationTest.java
src/test/java/com/thealgorithms/matrix/MatrixMultiplicationTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class MatrixMultiplicationTest { private static final double EPSILON = 1e-9; // for floating point comparison @Test void testMultiply1by1() { double[][] matrixA = {{1.0}}; double[][] matrixB = {{2.0}}; double[][] expected = {{2.0}}; double[][] result = MatrixMultiplication.multiply(matrixA, matrixB); assertMatrixEquals(expected, result); } @Test void testMultiply2by2() { double[][] matrixA = {{1.0, 2.0}, {3.0, 4.0}}; double[][] matrixB = {{5.0, 6.0}, {7.0, 8.0}}; double[][] expected = {{19.0, 22.0}, {43.0, 50.0}}; double[][] result = MatrixMultiplication.multiply(matrixA, matrixB); assertMatrixEquals(expected, result); // Use custom method due to floating point issues } @Test void testMultiply3by2and2by1() { double[][] matrixA = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}}; double[][] matrixB = {{7.0}, {8.0}}; double[][] expected = {{23.0}, {53.0}, {83.0}}; double[][] result = MatrixMultiplication.multiply(matrixA, matrixB); assertMatrixEquals(expected, result); } @Test void testMultiplyNonRectangularMatrices() { double[][] matrixA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}}; double[][] matrixB = {{7.0, 8.0}, {9.0, 10.0}, {11.0, 12.0}}; double[][] expected = {{58.0, 64.0}, {139.0, 154.0}}; double[][] result = MatrixMultiplication.multiply(matrixA, matrixB); assertMatrixEquals(expected, result); } @Test void testNullMatrixA() { double[][] b = {{1, 2}, {3, 4}}; assertThrows(IllegalArgumentException.class, () -> MatrixMultiplication.multiply(null, b)); } @Test void testNullMatrixB() { double[][] a = {{1, 2}, {3, 4}}; assertThrows(IllegalArgumentException.class, () -> MatrixMultiplication.multiply(a, null)); } @Test void testMultiplyNull() { double[][] matrixA = {{1.0, 2.0}, {3.0, 4.0}}; double[][] matrixB = null; Exception exception = assertThrows(IllegalArgumentException.class, () -> MatrixMultiplication.multiply(matrixA, matrixB)); String expectedMessage = "Input matrices cannot be null"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void testIncompatibleDimensions() { double[][] a = {{1.0, 2.0}}; double[][] b = {{1.0, 2.0}}; assertThrows(IllegalArgumentException.class, () -> MatrixMultiplication.multiply(a, b)); } @Test void testEmptyMatrices() { double[][] a = new double[0][0]; double[][] b = new double[0][0]; assertThrows(IllegalArgumentException.class, () -> MatrixMultiplication.multiply(a, b)); } private void assertMatrixEquals(double[][] expected, double[][] actual) { assertEquals(expected.length, actual.length, "Row count mismatch"); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i].length, actual[i].length, "Column count mismatch at row " + i); for (int j = 0; j < expected[i].length; j++) { assertEquals(expected[i][j], actual[i][j], EPSILON, "Mismatch at (" + i + "," + j + ")"); } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/matrix/MirrorOfMatrixTest.java
src/test/java/com/thealgorithms/matrix/MirrorOfMatrixTest.java
package com.thealgorithms.matrix; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class MirrorOfMatrixTest { @Test void testMirrorMatrixRegularMatrix() { double[][] originalMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; double[][] expectedMirrorMatrix = {{3, 2, 1}, {6, 5, 4}, {9, 8, 7}}; double[][] mirroredMatrix = MirrorOfMatrix.mirrorMatrix(originalMatrix); assertArrayEquals(expectedMirrorMatrix, mirroredMatrix); } @Test void testMirrorMatrixEmptyMatrix() { double[][] originalMatrix = {}; Exception e = assertThrows(IllegalArgumentException.class, () -> MirrorOfMatrix.mirrorMatrix(originalMatrix)); assertEquals("The input matrix cannot be empty", e.getMessage()); } @Test void testMirrorMatrixSingleElementMatrix() { double[][] originalMatrix = {{42}}; double[][] expectedMirrorMatrix = {{42}}; double[][] mirroredMatrix = MirrorOfMatrix.mirrorMatrix(originalMatrix); assertArrayEquals(expectedMirrorMatrix, mirroredMatrix); } @Test void testMirrorMatrixMultipleRowsOneColumnMatrix() { double[][] originalMatrix = {{1}, {2}, {3}, {4}}; double[][] expectedMirrorMatrix = {{1}, {2}, {3}, {4}}; double[][] mirroredMatrix = MirrorOfMatrix.mirrorMatrix(originalMatrix); assertArrayEquals(expectedMirrorMatrix, mirroredMatrix); } @Test void testMirrorMatrixNullInput() { double[][] originalMatrix = null; Exception e = assertThrows(IllegalArgumentException.class, () -> MirrorOfMatrix.mirrorMatrix(originalMatrix)); assertEquals("The input matrix cannot be null", e.getMessage()); } @Test void testMirrorMatrixThrows() { assertThrows(IllegalArgumentException.class, () -> MirrorOfMatrix.mirrorMatrix(new double[][] {{1}, {2, 3}})); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/ConvexHullTest.java
src/test/java/com/thealgorithms/geometry/ConvexHullTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class ConvexHullTest { @Test void testConvexHullBruteForce() { // Test 1: Triangle with intermediate point List<Point> points = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 1)); List<Point> expected = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 1)); assertEquals(expected, ConvexHull.convexHullBruteForce(points)); // Test 2: Collinear points points = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 0)); expected = Arrays.asList(new Point(0, 0), new Point(10, 0)); assertEquals(expected, ConvexHull.convexHullBruteForce(points)); // Test 3: Complex polygon points = Arrays.asList(new Point(0, 3), new Point(2, 2), new Point(1, 1), new Point(2, 1), new Point(3, 0), new Point(0, 0), new Point(3, 3), new Point(2, -1), new Point(2, -4), new Point(1, -3)); expected = Arrays.asList(new Point(2, -4), new Point(1, -3), new Point(0, 0), new Point(3, 0), new Point(0, 3), new Point(3, 3)); assertEquals(expected, ConvexHull.convexHullBruteForce(points)); } @Test void testConvexHullRecursive() { // Test 1: Triangle - CCW order starting from bottom-left // The algorithm includes (1,0) as it's detected as an extreme point List<Point> points = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 1)); List<Point> result = ConvexHull.convexHullRecursive(points); List<Point> expected = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 1)); assertEquals(expected, result); assertTrue(isCounterClockwise(result), "Points should be in counter-clockwise order"); // Test 2: Collinear points points = Arrays.asList(new Point(0, 0), new Point(1, 0), new Point(10, 0)); result = ConvexHull.convexHullRecursive(points); expected = Arrays.asList(new Point(0, 0), new Point(10, 0)); assertEquals(expected, result); // Test 3: Complex polygon // Convex hull vertices in CCW order from bottom-most point (2,-4): // (2,-4) -> (3,0) -> (3,3) -> (0,3) -> (0,0) -> (1,-3) -> back to (2,-4) points = Arrays.asList(new Point(0, 3), new Point(2, 2), new Point(1, 1), new Point(2, 1), new Point(3, 0), new Point(0, 0), new Point(3, 3), new Point(2, -1), new Point(2, -4), new Point(1, -3)); result = ConvexHull.convexHullRecursive(points); expected = Arrays.asList(new Point(2, -4), new Point(3, 0), new Point(3, 3), new Point(0, 3), new Point(0, 0), new Point(1, -3)); assertEquals(expected, result); assertTrue(isCounterClockwise(result), "Points should be in counter-clockwise order"); } @Test void testConvexHullRecursiveAdditionalCases() { // Test 4: Square (all corners on hull) List<Point> points = Arrays.asList(new Point(0, 0), new Point(2, 0), new Point(2, 2), new Point(0, 2)); List<Point> result = ConvexHull.convexHullRecursive(points); List<Point> expected = Arrays.asList(new Point(0, 0), new Point(2, 0), new Point(2, 2), new Point(0, 2)); assertEquals(expected, result); assertTrue(isCounterClockwise(result), "Square points should be in CCW order"); // Test 5: Pentagon with interior point points = Arrays.asList(new Point(0, 0), new Point(4, 0), new Point(5, 3), new Point(2, 5), new Point(-1, 3), new Point(2, 2) // (2,2) is interior ); result = ConvexHull.convexHullRecursive(points); // CCW from (0,0): (0,0) -> (4,0) -> (5,3) -> (2,5) -> (-1,3) expected = Arrays.asList(new Point(0, 0), new Point(4, 0), new Point(5, 3), new Point(2, 5), new Point(-1, 3)); assertEquals(expected, result); assertTrue(isCounterClockwise(result), "Pentagon points should be in CCW order"); // Test 6: Simple triangle (clearly convex) points = Arrays.asList(new Point(0, 0), new Point(4, 0), new Point(2, 3)); result = ConvexHull.convexHullRecursive(points); expected = Arrays.asList(new Point(0, 0), new Point(4, 0), new Point(2, 3)); assertEquals(expected, result); assertTrue(isCounterClockwise(result), "Triangle points should be in CCW order"); } /** * Helper method to verify if points are in counter-clockwise order. * Uses the signed area method: positive area means CCW. */ private boolean isCounterClockwise(List<Point> points) { if (points.size() < 3) { return true; // Less than 3 points, trivially true } long signedArea = 0; for (int i = 0; i < points.size(); i++) { Point p1 = points.get(i); Point p2 = points.get((i + 1) % points.size()); signedArea += (long) p1.x() * p2.y() - (long) p2.x() * p1.y(); } return signedArea > 0; // Positive signed area means counter-clockwise } @Test void testRecursiveHullForCoverage() { // 1. Test the base cases of the convexHullRecursive method (covering scenarios with < 3 input points). // Test Case: 0 points List<Point> pointsEmpty = new ArrayList<>(); List<Point> resultEmpty = ConvexHull.convexHullRecursive(pointsEmpty); assertTrue(resultEmpty.isEmpty(), "Should return an empty list for an empty input list"); // Test Case: 1 point List<Point> pointsOne = List.of(new Point(5, 5)); // Pass a new ArrayList because the original method modifies the input list. List<Point> resultOne = ConvexHull.convexHullRecursive(new ArrayList<>(pointsOne)); List<Point> expectedOne = List.of(new Point(5, 5)); assertEquals(expectedOne, resultOne, "Should return the single point for a single-point input"); // Test Case: 2 points List<Point> pointsTwo = Arrays.asList(new Point(10, 1), new Point(0, 0)); List<Point> resultTwo = ConvexHull.convexHullRecursive(new ArrayList<>(pointsTwo)); List<Point> expectedTwo = Arrays.asList(new Point(0, 0), new Point(10, 1)); // Should return the two points, sorted. assertEquals(expectedTwo, resultTwo, "Should return the two sorted points for a two-point input"); // 2. Test the logic for handling collinear points in the sortCounterClockwise method. // Construct a scenario where multiple collinear points lie on an edge of the convex hull. // The expected convex hull vertices are (0,0), (10,0), and (5,5). // When (0,0) is used as the pivot for polar angle sorting, (5,0) and (10,0) are collinear. // This will trigger the crossProduct == 0 branch in the sortCounterClockwise method. List<Point> pointsWithCollinearOnHull = Arrays.asList(new Point(0, 0), new Point(5, 0), new Point(10, 0), new Point(5, 5), new Point(2, 2)); List<Point> resultCollinear = ConvexHull.convexHullRecursive(new ArrayList<>(pointsWithCollinearOnHull)); List<Point> expectedCollinear = Arrays.asList(new Point(0, 0), new Point(10, 0), new Point(5, 5)); assertEquals(expectedCollinear, resultCollinear, "Should correctly handle collinear points on the hull edge"); assertTrue(isCounterClockwise(resultCollinear), "The result of the collinear test should be in counter-clockwise order"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java
src/test/java/com/thealgorithms/geometry/BresenhamLineTest.java
package com.thealgorithms.geometry; import java.awt.Point; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * The {@code BresenhamLineTest} class contains unit tests for the * {@code BresenhamLine} class, specifically testing the * {@code findLine} method. * * <p>This class uses parameterized tests to validate the output of * Bresenham's line algorithm for various input points.</p> */ class BresenhamLineTest { /** * Provides test cases for the parameterized test. * * <p>Each test case includes starting coordinates, ending coordinates, * and the expected collection of points that should be generated by the * {@code findLine} method.</p> * * @return a stream of arguments containing test cases */ static Stream<Arguments> linePointsProvider() { return Stream.of(Arguments.of(0, 0, 5, 5, List.of(new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4), new Point(5, 5))), Arguments.of(0, 0, 5, 0, List.of(new Point(0, 0), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(4, 0), new Point(5, 0))), Arguments.of(0, 0, 0, 5, List.of(new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(0, 3), new Point(0, 4), new Point(0, 5))), Arguments.of(-2, -2, -5, -5, List.of(new Point(-2, -2), new Point(-3, -3), new Point(-4, -4), new Point(-5, -5))), Arguments.of(-1, -1, 2, 2, List.of(new Point(-1, -1), new Point(0, 0), new Point(1, 1), new Point(2, 2))), Arguments.of(2, -1, -1, -4, List.of(new Point(2, -1), new Point(1, -2), new Point(0, -3), new Point(-1, -4)))); } /** * Tests the {@code findLine} method of the {@code BresenhamLine} class. * * <p>This parameterized test runs multiple times with different sets of * starting and ending coordinates to validate that the generated points * match the expected output.</p> * * @param x0 the x-coordinate of the starting point * @param y0 the y-coordinate of the starting point * @param x1 the x-coordinate of the ending point * @param y1 the y-coordinate of the ending point * @param expected a collection of expected points that should form a line */ @ParameterizedTest @MethodSource("linePointsProvider") void testFindLine(int x0, int y0, int x1, int y1, Collection<Point> expected) { List<Point> actual = BresenhamLine.findLine(x0, y0, x1, y1); Assertions.assertEquals(expected.size(), actual.size(), "The size of the points list should match."); Assertions.assertTrue(expected.containsAll(actual) && actual.containsAll(expected), "The points generated should match the expected points."); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java
src/test/java/com/thealgorithms/geometry/MidpointEllipseTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * The {@code MidpointEllipseTest} class contains unit tests for the * {@code MidpointEllipse} class, specifically testing the * {@code drawEllipse} method. * * <p>This class uses parameterized tests to validate the output of * Midpoint Ellipse algorithm for various input points.</p> */ class MidpointEllipseTest { /** * Provides test cases for the drawEllipse method. * Each argument contains: centerX, centerY, a, b, and expected points. * * @return a stream of arguments for parameterized testing */ static Stream<Arguments> ellipseTestProvider() { return Stream.of( Arguments.of(0, 0, 5, 3, new int[][] {{0, 3}, {0, 3}, {0, -3}, {0, -3}, {1, 3}, {-1, 3}, {1, -3}, {-1, -3}, {2, 3}, {-2, 3}, {2, -3}, {-2, -3}, {3, 2}, {-3, 2}, {3, -2}, {-3, -2}, {4, 2}, {-4, 2}, {4, -2}, {-4, -2}, {5, 1}, {-5, 1}, {5, -1}, {-5, -1}, {5, 0}, {-5, 0}, {5, 0}, {-5, 0}}), Arguments.of(0, 0, 0, 5, new int[][] { {0, -5}, {0, -4}, {0, -3}, {0, -2}, {0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5} // Only vertical line points and center }), Arguments.of(0, 0, 5, 0, new int[][] { {-5, 0}, {-4, 0}, {-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0} // Only horizontal line points and center }), Arguments.of(0, 0, 0, 0, new int[][] { {0, 0} // Only center point }), Arguments.of(0, 0, 4, 4, new int[][] { {0, 4}, {0, 4}, {0, -4}, {0, -4}, {1, 4}, {-1, 4}, {1, -4}, {-1, -4}, {2, 3}, {-2, 3}, {2, -3}, {-2, -3}, {3, 3}, {-3, 3}, {3, -3}, {-3, -3}, {3, 2}, {-3, 2}, {3, -2}, {-3, -2}, {4, 1}, {-4, 1}, {4, -1}, {-4, -1}, {4, 0}, {-4, 0}, {4, 0}, {-4, 0}, })); } /** * Tests the drawEllipse method with various parameters. * * @param centerX the x-coordinate of the center of the ellipse * @param centerY the y-coordinate of the center of the ellipse * @param a the length of the semi-major axis * @param b the length of the semi-minor axis * @param expectedPoints the expected points forming the ellipse */ @ParameterizedTest @MethodSource("ellipseTestProvider") @DisplayName("Test drawing ellipses with various parameters") void testDrawEllipse(int centerX, int centerY, int a, int b, int[][] expectedPoints) { List<int[]> points = MidpointEllipse.drawEllipse(centerX, centerY, a, b); // Validate the number of points and the specific points assertEquals(expectedPoints.length, points.size(), "Number of points should match expected."); for (int i = 0; i < expectedPoints.length; i++) { assertArrayEquals(expectedPoints[i], points.get(i), "Point mismatch at index " + i); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/HaversineTest.java
src/test/java/com/thealgorithms/geometry/HaversineTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Unit tests for the Haversine formula implementation. * This class uses parameterized tests to verify the distance calculation * between various geographical coordinates. */ final class HaversineTest { // A small tolerance for comparing double values, since floating-point // arithmetic is not always exact. A 1km tolerance is reasonable for these distances. private static final double DELTA = 1.0; /** * Provides test cases for the haversine distance calculation. * Each argument contains: lat1, lon1, lat2, lon2, and the expected distance in kilometers. * * @return a stream of arguments for the parameterized test. */ static Stream<Arguments> haversineTestProvider() { return Stream.of( // Case 1: Distance between Paris, France and Tokyo, Japan Arguments.of(48.8566, 2.3522, 35.6895, 139.6917, 9712.0), // Case 2: Distance between New York, USA and London, UK Arguments.of(40.7128, -74.0060, 51.5074, -0.1278, 5570.0), // Case 3: Zero distance (same point) Arguments.of(52.5200, 13.4050, 52.5200, 13.4050, 0.0), // Case 4: Antipodal points (opposite sides of the Earth) // Should be approximately half the Earth's circumference (PI * radius) Arguments.of(0.0, 0.0, 0.0, 180.0, 20015.0)); } /** * Tests the haversine method with various sets of coordinates. * * @param lat1 Latitude of the first point. * @param lon1 Longitude of the first point. * @param lat2 Latitude of the second point. * @param lon2 Longitude of the second point. * @param expectedDistance The expected distance in kilometers. */ @ParameterizedTest @MethodSource("haversineTestProvider") @DisplayName("Test Haversine distance calculation for various coordinates") void testHaversine(double lat1, double lon1, double lat2, double lon2, double expectedDistance) { double actualDistance = Haversine.haversine(lat1, lon1, lat2, lon2); assertEquals(expectedDistance, actualDistance, 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/geometry/WusLineTest.java
src/test/java/com/thealgorithms/geometry/WusLineTest.java
package com.thealgorithms.geometry; 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; /** * Unit tests for the {@link WusLine} class. */ class WusLineTest { @Test void testSimpleLineProducesPixels() { List<WusLine.Pixel> pixels = WusLine.drawLine(2, 2, 6, 4); assertFalse(pixels.isEmpty(), "Line should produce non-empty pixel list"); } @Test void testEndpointsIncluded() { List<WusLine.Pixel> pixels = WusLine.drawLine(0, 0, 5, 3); boolean hasStart = pixels.stream().anyMatch(p -> p.point.equals(new java.awt.Point(0, 0))); boolean hasEnd = pixels.stream().anyMatch(p -> p.point.equals(new java.awt.Point(5, 3))); assertTrue(hasStart, "Start point should be represented in the pixel list"); assertTrue(hasEnd, "End point should be represented in the pixel list"); } @Test void testIntensityInRange() { List<WusLine.Pixel> pixels = WusLine.drawLine(1, 1, 8, 5); for (WusLine.Pixel pixel : pixels) { assertTrue(pixel.intensity >= 0.0 && pixel.intensity <= 1.0, "Intensity must be clamped between 0.0 and 1.0"); } } @Test void testReversedEndpointsProducesSameLine() { List<WusLine.Pixel> forward = WusLine.drawLine(2, 2, 10, 5); List<WusLine.Pixel> backward = WusLine.drawLine(10, 5, 2, 2); // They should cover same coordinates (ignoring order) var forwardPoints = forward.stream().map(p -> p.point).collect(java.util.stream.Collectors.toSet()); var backwardPoints = backward.stream().map(p -> p.point).collect(java.util.stream.Collectors.toSet()); assertEquals(forwardPoints, backwardPoints, "Reversing endpoints should yield same line pixels"); } @Test void testSteepLineHasProperCoverage() { // Steep line: Δy > Δx List<WusLine.Pixel> pixels = WusLine.drawLine(3, 2, 5, 10); assertFalse(pixels.isEmpty()); // Expect increasing y values long increasing = 0; for (int i = 1; i < pixels.size(); i++) { if (pixels.get(i).point.y >= pixels.get(i - 1).point.y) { increasing++; } } assertTrue(increasing > pixels.size() / 2, "Steep line should have increasing y coordinates"); } @Test void testZeroLengthLineUsesDefaultGradient() { // same start and end -> dx == 0 -> gradient should take the (dx == 0) ? 1.0 branch List<WusLine.Pixel> pixels = WusLine.drawLine(3, 3, 3, 3); // sanity checks: we produced pixels and the exact point is present assertFalse(pixels.isEmpty(), "Zero-length line should produce at least one pixel"); assertTrue(pixels.stream().anyMatch(p -> p.point.equals(new java.awt.Point(3, 3))), "Pixel list should include the single-point coordinate (3,3)"); } @Test void testHorizontalLineIntensityStable() { List<WusLine.Pixel> pixels = WusLine.drawLine(1, 5, 8, 5); // For each x, take the max intensity among pixels with that x (the visible intensity for the column) java.util.Map<Integer, Double> maxIntensityByX = pixels.stream() .collect(java.util.stream.Collectors.groupingBy(p -> p.point.x, java.util.stream.Collectors.mapping(p -> p.intensity, java.util.stream.Collectors.maxBy(Double::compareTo)))) .entrySet() .stream() .collect(java.util.stream.Collectors.toMap(java.util.Map.Entry::getKey, e -> e.getValue().orElse(0.0))); double avgMaxIntensity = maxIntensityByX.values().stream().mapToDouble(Double::doubleValue).average().orElse(0.0); assertTrue(avgMaxIntensity > 0.5, "Average of the maximum per-x intensities should be > 0.5 for a horizontal line"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/BentleyOttmannTest.java
src/test/java/com/thealgorithms/geometry/BentleyOttmannTest.java
package com.thealgorithms.geometry; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Comprehensive unit tests for {@link BentleyOttmann}. * * <p>This test suite validates the correctness of the Bentley–Ottmann algorithm * implementation by checking intersection points between multiple line segment configurations.</p> * * <p>Test cases include typical, edge, degenerate geometrical setups, and performance tests.</p> */ public class BentleyOttmannTest { private static final double EPS = 1e-6; @Test void testSingleIntersection() { List<BentleyOttmann.Segment> segments = List.of(newSegment(1, 1, 5, 5), newSegment(1, 5, 5, 1)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(1, intersections.size()); Assertions.assertTrue(containsPoint(intersections, 3.0, 3.0)); } @Test void testVerticalIntersection() { List<BentleyOttmann.Segment> segments = List.of(newSegment(3, 0, 3, 6), newSegment(1, 1, 5, 5)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(1, intersections.size()); Assertions.assertTrue(containsPoint(intersections, 3.0, 3.0)); } @Test void testNoIntersection() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 1, 1), newSegment(2, 2, 3, 3)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(intersections.isEmpty()); } @Test void testCoincidentSegments() { List<BentleyOttmann.Segment> segments = List.of(newSegment(1, 1, 5, 5), newSegment(1, 1, 5, 5)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(2, intersections.size(), "Two identical segments should report 2 intersection points (both endpoints)"); Assertions.assertTrue(containsPoint(intersections, 1.0, 1.0)); Assertions.assertTrue(containsPoint(intersections, 5.0, 5.0)); } @Test void testHorizontalIntersection() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 2, 4, 2), newSegment(2, 0, 2, 4)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0)); } @Test void testEmptyList() { List<BentleyOttmann.Segment> segments = List.of(); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(intersections.isEmpty()); } @Test void testSingleSegment() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 5, 5)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(intersections.isEmpty()); } @Test void testNullListThrowsException() { Assertions.assertThrows(IllegalArgumentException.class, () -> BentleyOttmann.findIntersections(null)); } @Test void testParallelSegments() { // Test 1: Parallel diagonal segments List<BentleyOttmann.Segment> diagonalSegments = List.of(newSegment(0, 0, 4, 4), newSegment(1, 0, 5, 4), newSegment(2, 0, 6, 4)); Assertions.assertTrue(BentleyOttmann.findIntersections(diagonalSegments).isEmpty()); // Test 2: Parallel vertical segments List<BentleyOttmann.Segment> verticalSegments = List.of(newSegment(1, 0, 1, 5), newSegment(2, 0, 2, 5), newSegment(3, 0, 3, 5)); Assertions.assertTrue(BentleyOttmann.findIntersections(verticalSegments).isEmpty()); // Test 3: Parallel horizontal segments List<BentleyOttmann.Segment> horizontalSegments = List.of(newSegment(0, 1, 5, 1), newSegment(0, 2, 5, 2), newSegment(0, 3, 5, 3)); Assertions.assertTrue(BentleyOttmann.findIntersections(horizontalSegments).isEmpty()); } @Test void testTouchingEndpoints() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 2, 2), newSegment(2, 2, 4, 0)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(1, intersections.size()); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0)); } @Test void testOverlappingCollinearSegments() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 4, 4), newSegment(2, 2, 6, 6)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Overlapping collinear segments share the point (2,2) where second starts // and (4,4) where first ends - at least one should be detected Assertions.assertFalse(intersections.isEmpty(), "Should find at least one overlap point"); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0) || containsPoint(intersections, 4.0, 4.0), "Should contain either (2,2) or (4,4)"); } @Test void testMultipleSegmentsAtOnePoint() { // Star pattern: 4 segments meeting at (2, 2) List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 2, 4, 2), // horizontal newSegment(2, 0, 2, 4), // vertical newSegment(0, 0, 4, 4), // diagonal / newSegment(0, 4, 4, 0) // diagonal \ ); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0)); // All segments meet at (2, 2), so should be reported once Assertions.assertEquals(1, intersections.size()); } @Test void testGridPattern() { // 3x3 grid: should have 9 intersection points List<BentleyOttmann.Segment> segments = new ArrayList<>(); // Vertical lines at x = 0, 1, 2 for (int i = 0; i <= 2; i++) { segments.add(newSegment(i, 0, i, 2)); } // Horizontal lines at y = 0, 1, 2 for (int i = 0; i <= 2; i++) { segments.add(newSegment(0, i, 2, i)); } Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Each vertical line crosses each horizontal line // 3 vertical × 3 horizontal = 9 intersections Assertions.assertEquals(9, intersections.size(), "3x3 grid should have 9 intersections"); // Verify all grid points are present for (int x = 0; x <= 2; x++) { for (int y = 0; y <= 2; y++) { Assertions.assertTrue(containsPoint(intersections, x, y), String.format("Grid point (%d, %d) should be present", x, y)); } } } @Test void testTriangleIntersections() { // Three segments forming a triangle List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 4, 0), // base newSegment(0, 0, 2, 3), // left side newSegment(4, 0, 2, 3) // right side ); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Triangle vertices are intersections Assertions.assertTrue(containsPoint(intersections, 0.0, 0.0)); Assertions.assertTrue(containsPoint(intersections, 4.0, 0.0)); Assertions.assertTrue(containsPoint(intersections, 2.0, 3.0)); Assertions.assertEquals(3, intersections.size()); } @Test void testCrossingDiagonals() { // X pattern with multiple crossings List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 10, 10), newSegment(0, 10, 10, 0), newSegment(5, 0, 5, 10), newSegment(0, 5, 10, 5)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(containsPoint(intersections, 5.0, 5.0), "Center point should be present"); Assertions.assertEquals(1, intersections.size()); } @Test void testVerySmallSegments() { List<BentleyOttmann.Segment> segments = List.of(newSegment(0.001, 0.001, 0.002, 0.002), newSegment(0.001, 0.002, 0.002, 0.001)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(1, intersections.size()); Assertions.assertTrue(containsPoint(intersections, 0.0015, 0.0015)); } @Test void testSegmentsShareCommonPoint() { List<BentleyOttmann.Segment> segmentsSameStart = List.of(newSegment(0, 0, 4, 4), newSegment(0, 0, 4, -4), newSegment(0, 0, -4, 4)); Set<Point2D.Double> intersectionsSameStart = BentleyOttmann.findIntersections(segmentsSameStart); Assertions.assertTrue(containsPoint(intersectionsSameStart, 0.0, 0.0)); List<BentleyOttmann.Segment> segmentsSameEnd = List.of(newSegment(0, 0, 4, 4), newSegment(8, 4, 4, 4), newSegment(4, 8, 4, 4)); Set<Point2D.Double> intersectionsSameEnd = BentleyOttmann.findIntersections(segmentsSameEnd); Assertions.assertTrue(containsPoint(intersectionsSameEnd, 4.0, 4.0)); } @Test void testSegmentsAtAngles() { // Segments at 45, 90, 135 degrees List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 2, 4, 2), // horizontal newSegment(2, 0, 2, 4), // vertical newSegment(0, 0, 4, 4), // 45 degrees newSegment(0, 4, 4, 0) // 135 degrees ); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0)); } @Test void testPerformanceWithManySegments() { // Generate 100 random segments Random random = new Random(42); // Fixed seed for reproducibility List<BentleyOttmann.Segment> segments = new ArrayList<>(); for (int i = 0; i < 100; i++) { double x1 = random.nextDouble() * 100; double y1 = random.nextDouble() * 100; double x2 = random.nextDouble() * 100; double y2 = random.nextDouble() * 100; segments.add(newSegment(x1, y1, x2, y2)); } long startTime = System.currentTimeMillis(); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; // Should complete in reasonable time (< 1 second for 100 segments) Assertions.assertTrue(duration < 1000, "Algorithm should complete in less than 1 second for 100 segments. Took: " + duration + "ms"); // Just verify it returns a valid result Assertions.assertNotNull(intersections); System.out.println("Performance test: 100 segments processed in " + duration + "ms, found " + intersections.size() + " intersections"); } @Test void testIssueExample() { // Example from the GitHub issue List<BentleyOttmann.Segment> segments = List.of(newSegment(1, 1, 5, 5), // Segment A newSegment(1, 5, 5, 1), // Segment B newSegment(3, 0, 3, 6) // Segment C ); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Expected output: [(3, 3)] Assertions.assertEquals(1, intersections.size(), "Should find exactly one intersection"); Assertions.assertTrue(containsPoint(intersections, 3.0, 3.0), "Intersection should be at (3, 3)"); } @Test void testEventTypeOrdering() { // Multiple events at the same point with different types List<BentleyOttmann.Segment> segments = List.of(newSegment(2, 2, 6, 2), // ends at (2,2) newSegment(0, 2, 2, 2), // ends at (2,2) newSegment(2, 2, 2, 6), // starts at (2,2) newSegment(2, 0, 2, 2) // ends at (2,2) ); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0)); } @Test void testCollinearOverlapWithInteriorPoint() { // Test collinear segments where one segment's interior overlaps another List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 6, 6), newSegment(2, 2, 4, 4)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Should find at least one overlap point (where segments touch/overlap) Assertions.assertFalse(intersections.isEmpty(), "Should find overlap points for collinear segments"); Assertions.assertTrue(containsPoint(intersections, 2.0, 2.0) || containsPoint(intersections, 4.0, 4.0), "Should contain overlap boundary point"); } @Test void testCollinearTouchingAtBothEndpoints() { // Test collinear segments that touch at both endpoints // This triggers the "endpoint of both" logic (line 354-355) List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 4, 4), newSegment(4, 4, 8, 8)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); Assertions.assertEquals(1, intersections.size()); Assertions.assertTrue(containsPoint(intersections, 4.0, 4.0), "Should find touching point"); } @Test void testCollinearOverlapPartialInterior() { // Test case where segments overlap but one point is inside, one is endpoint List<BentleyOttmann.Segment> segments = List.of(newSegment(0, 0, 5, 5), newSegment(3, 3, 7, 7)); Set<Point2D.Double> intersections = BentleyOttmann.findIntersections(segments); // Should detect the overlap region Assertions.assertFalse(intersections.isEmpty()); // The algorithm should return at least one of the boundary points Assertions.assertTrue(containsPoint(intersections, 3.0, 3.0) || containsPoint(intersections, 5.0, 5.0)); } private static BentleyOttmann.Segment newSegment(double x1, double y1, double x2, double y2) { return new BentleyOttmann.Segment(new Point2D.Double(x1, y1), new Point2D.Double(x2, y2)); } private static boolean containsPoint(Set<Point2D.Double> points, double x, double y) { return points.stream().anyMatch(p -> Math.abs(p.x - x) < EPS && Math.abs(p.y - y) < EPS); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java
src/test/java/com/thealgorithms/geometry/GrahamScanTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class GrahamScanTest { @Test void testGrahamScan() { Point[] points = {new Point(0, 3), new Point(1, 1), new Point(2, 2), new Point(4, 4), new Point(0, 0), new Point(1, 2), new Point(3, 1), new Point(3, 3)}; String expectedResult = "[(0, 0), (3, 1), (4, 4), (0, 3)]"; GrahamScan graham = new GrahamScan(points); assertEquals(expectedResult, graham.hull().toString()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java
src/test/java/com/thealgorithms/geometry/MidpointCircleTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; /** * Test class for the {@code MidpointCircle} class */ class MidpointCircleTest { /** * Parameterized test to check the generated points for different circles. * The points are checked based on the expected center and radius. * * @param centerX The x-coordinate of the circle's center. * @param centerY The y-coordinate of the circle's center. * @param radius The radius of the circle. */ @ParameterizedTest @CsvSource({ "0, 0, 3", // Circle centered at (0, 0) with radius 3 "10, 10, 2" // Circle centered at (10, 10) with radius 2 }) void testGenerateCirclePoints(int centerX, int centerY, int radius) { List<int[]> points = MidpointCircle.generateCirclePoints(centerX, centerY, radius); // Ensure that all points satisfy the circle equation (x - centerX)^2 + (y - centerY)^2 = radius^2 for (int[] point : points) { int x = point[0]; int y = point[1]; int dx = x - centerX; int dy = y - centerY; int distanceSquared = dx * dx + dy * dy; assertTrue(Math.abs(distanceSquared - radius * radius) <= 1, "Point (" + x + ", " + y + ") does not satisfy the circle equation."); } } /** * Test to ensure the algorithm generates points for a zero-radius circle. */ @Test void testZeroRadiusCircle() { List<int[]> points = MidpointCircle.generateCirclePoints(0, 0, 0); // A zero-radius circle should only have one point: (0, 0) assertTrue(points.size() == 1 && points.get(0)[0] == 0 && points.get(0)[1] == 0, "Zero-radius circle did not generate the correct point."); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/geometry/PointTest.java
src/test/java/com/thealgorithms/geometry/PointTest.java
package com.thealgorithms.geometry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class PointTest { @Test void testCompareTo() { Point p1 = new Point(1, 2); Point p2 = new Point(5, -1); Point p3 = new Point(3, 9); Point p4 = new Point(3, 9); assertEquals(1, p1.compareTo(p2)); assertEquals(-1, p2.compareTo(p3)); assertEquals(0, p3.compareTo(p4)); } @Test void testToString() { Point p = new Point(-3, 5); assertEquals("(-3, 5)", p.toString()); } @Test void testPolarOrder() { Point p = new Point(0, 0); assertNotNull(p.polarOrder()); } @Test void testOrientation() { // setup points Point pA = new Point(0, 0); Point pB = new Point(1, 0); Point pC = new Point(1, 1); // test for left curve assertEquals(1, Point.orientation(pA, pB, pC)); // test for right curve pB = new Point(0, 1); assertEquals(-1, Point.orientation(pA, pB, pC)); // test for left curve pC = new Point(-1, 1); assertEquals(1, Point.orientation(pA, pB, pC)); // test for right curve pB = new Point(1, 0); pC = new Point(1, -1); assertEquals(-1, Point.orientation(pA, pB, pC)); // test for collinearity pB = new Point(1, 1); pC = new Point(2, 2); assertEquals(0, Point.orientation(pA, pB, pC)); } @Test void testPolarOrderCompare() { Point ref = new Point(0, 0); Point pA = new Point(1, 1); Point pB = new Point(1, -1); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(3, 0); pB = new Point(2, 0); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(0, 1); pB = new Point(-1, 1); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(1, 1); pB = new Point(2, 2); assertEquals(0, ref.polarOrder().compare(pA, pB)); pA = new Point(1, 2); pB = new Point(2, 1); assertTrue(ref.polarOrder().compare(pA, pB) > 0); pA = new Point(2, 1); pB = new Point(1, 2); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(-1, 0); pB = new Point(-2, 0); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(2, 3); pB = new Point(2, 3); assertEquals(0, ref.polarOrder().compare(pA, pB)); pA = new Point(0, 1); pB = new Point(0, -1); assertTrue(ref.polarOrder().compare(pA, pB) < 0); ref = new Point(1, 1); pA = new Point(1, 2); pB = new Point(2, 2); assertTrue(ref.polarOrder().compare(pA, pB) > 0); pA = new Point(2, 1); pB = new Point(2, 0); assertTrue(ref.polarOrder().compare(pA, pB) < 0); pA = new Point(0, 1); pB = new Point(1, 0); assertTrue(ref.polarOrder().compare(pA, pB) < 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/geometry/DDALineTest.java
src/test/java/com/thealgorithms/geometry/DDALineTest.java
package com.thealgorithms.geometry; import java.awt.Point; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * The {@code DDALineTest} class contains unit tests for the * {@code DDALine} class, specifically testing the {@code findLine} method. */ class DDALineTest { static Stream<Arguments> linePointsProvider() { return Stream.of(Arguments.of(0, 0, 5, 5, List.of(new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4), new Point(5, 5))), Arguments.of(0, 0, 5, 0, List.of(new Point(0, 0), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(4, 0), new Point(5, 0))), Arguments.of(0, 0, 0, 5, List.of(new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(0, 3), new Point(0, 4), new Point(0, 5))), Arguments.of(-2, -2, -5, -5, List.of(new Point(-2, -2), new Point(-3, -3), new Point(-4, -4), new Point(-5, -5))), Arguments.of(1, 1, 1, 1, List.of(new Point(1, 1))), Arguments.of(0, 0, 1, 5, List.of(new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(1, 3), new Point(1, 4), new Point(1, 5)))); } @ParameterizedTest @MethodSource("linePointsProvider") void testFindLine(int x0, int y0, int x1, int y1, List<Point> expected) { List<Point> actual = DDALine.findLine(x0, y0, x1, y1); Assertions.assertEquals(expected, actual, "The DDA algorithm should generate the expected ordered points."); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java
src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class IntegerToRomanTest { @Test public void testIntegerToRoman() { assertEquals("MCMXCIV", IntegerToRoman.integerToRoman(1994)); assertEquals("LVIII", IntegerToRoman.integerToRoman(58)); assertEquals("IV", IntegerToRoman.integerToRoman(4)); assertEquals("IX", IntegerToRoman.integerToRoman(9)); assertEquals("MMM", IntegerToRoman.integerToRoman(3000)); } @Test public void testSmallNumbers() { assertEquals("I", IntegerToRoman.integerToRoman(1)); assertEquals("II", IntegerToRoman.integerToRoman(2)); assertEquals("III", IntegerToRoman.integerToRoman(3)); } @Test public void testRoundNumbers() { assertEquals("X", IntegerToRoman.integerToRoman(10)); assertEquals("L", IntegerToRoman.integerToRoman(50)); assertEquals("C", IntegerToRoman.integerToRoman(100)); assertEquals("D", IntegerToRoman.integerToRoman(500)); assertEquals("M", IntegerToRoman.integerToRoman(1000)); } @Test public void testEdgeCases() { assertEquals("", IntegerToRoman.integerToRoman(0)); // Non-positive number case assertEquals("", IntegerToRoman.integerToRoman(-5)); // Negative number case } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/DecimalToHexadecimalTest.java
src/test/java/com/thealgorithms/conversions/DecimalToHexadecimalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class DecimalToHexadecimalTest { @ParameterizedTest @CsvSource({"0, 0", "1, 1", "10, a", "15, f", "16, 10", "255, ff", "190, be", "1800, 708"}) void testDecToHex(int decimal, String expectedHex) { assertEquals(expectedHex, DecimalToHexadecimal.decToHex(decimal)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java
src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class BinaryToHexadecimalTest { @ParameterizedTest @CsvSource({"0, 0", "1, 1", "10, 2", "1111, F", "1101010, 6A", "1100, C"}) void testBinToHex(int binary, String expectedHex) { assertEquals(expectedHex, BinaryToHexadecimal.binToHex(binary)); } @ParameterizedTest @CsvSource({"2", "1234", "11112"}) void testInvalidBinaryInput(int binary) { assertThrows(IllegalArgumentException.class, () -> BinaryToHexadecimal.binToHex(binary)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/IPConverterTest.java
src/test/java/com/thealgorithms/conversions/IPConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class IPConverterTest { private static String generateTestIP(int a, int b, int c, int d) { return String.format("%d.%d.%d.%d", a, b, c, d); } private static String generateTestBinary(int a, int b, int c, int d) { return String.format("%8s.%8s.%8s.%8s", Integer.toBinaryString(a), Integer.toBinaryString(b), Integer.toBinaryString(c), Integer.toBinaryString(d)).replace(' ', '0'); } @Test public void testIpToBinary() { assertEquals(generateTestBinary(192, 168, 1, 1), IPConverter.ipToBinary(generateTestIP(192, 168, 1, 1))); assertEquals(generateTestBinary(127, 3, 4, 5), IPConverter.ipToBinary(generateTestIP(127, 3, 4, 5))); assertEquals(generateTestBinary(0, 0, 0, 0), IPConverter.ipToBinary(generateTestIP(0, 0, 0, 0))); } @Test public void testBinaryToIP() { assertEquals(generateTestIP(192, 168, 1, 1), IPConverter.binaryToIP(generateTestBinary(192, 168, 1, 1))); assertEquals(generateTestIP(127, 3, 4, 5), IPConverter.binaryToIP(generateTestBinary(127, 3, 4, 5))); assertEquals(generateTestIP(0, 0, 0, 0), IPConverter.binaryToIP(generateTestBinary(0, 0, 0, 0))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/DecimalToAnyBaseTest.java
src/test/java/com/thealgorithms/conversions/DecimalToAnyBaseTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class DecimalToAnyBaseTest { @ParameterizedTest @CsvSource({"0, 2, 0", "0, 16, 0", "0, 36, 0", "10, 2, 1010", "255, 16, FF", "100, 8, 144", "42, 2, 101010", "1234, 16, 4D2", "1234, 36, YA"}) void testConvertToAnyBase(int decimal, int base, String expected) { assertEquals(expected, DecimalToAnyBase.convertToAnyBase(decimal, base)); } @Test void testBaseOutOfRange() { assertThrows(IllegalArgumentException.class, () -> DecimalToAnyBase.convertToAnyBase(10, 1)); assertThrows(IllegalArgumentException.class, () -> DecimalToAnyBase.convertToAnyBase(10, 37)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java
src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.UnknownHostException; import org.junit.jupiter.api.Test; public class IPv6ConverterTest { private static final String VALID_IPV4 = "192." + "0." + "2." + "128"; private static final String EXPECTED_IPV6_MAPPED = ":" + ":ff" + "ff" + ":19" + "2." + "0." + "2.128"; private static final String INVALID_IPV6_MAPPED = "2001:" + "db8" + ":" + ":1"; private static final String INVALID_IPV4 = "999." + "999." + "999." + "999"; private static final String INVALID_IPV6_FORMAT = "invalid:ipv6" + "::address"; private static final String EMPTY_STRING = ""; @Test public void testIpv4ToIpv6ValidInput() throws UnknownHostException { String actualIpv6 = IPv6Converter.ipv4ToIpv6(VALID_IPV4); assertEquals(EXPECTED_IPV6_MAPPED, actualIpv6); } @Test public void testIpv6ToIpv4InvalidIPv6MappedAddress() { assertThrows(IllegalArgumentException.class, () -> IPv6Converter.ipv6ToIpv4(INVALID_IPV6_MAPPED)); } @Test public void testIpv4ToIpv6InvalidIPv4Address() { assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv4ToIpv6(INVALID_IPV4)); } @Test public void testIpv6ToIpv4InvalidFormat() { assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv6ToIpv4(INVALID_IPV6_FORMAT)); } @Test public void testIpv4ToIpv6EmptyString() { assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv4ToIpv6(EMPTY_STRING)); } @Test public void testIpv6ToIpv4EmptyString() { assertThrows(IllegalArgumentException.class, () -> IPv6Converter.ipv6ToIpv4(EMPTY_STRING)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/AffineConverterTest.java
src/test/java/com/thealgorithms/conversions/AffineConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class AffineConverterTest { private AffineConverter converter; @BeforeEach void setUp() { converter = new AffineConverter(2.0, 3.0); } @Test void testConstructorWithValidValues() { assertEquals(3.0, converter.convert(0.0), "Expected value when input is 0.0"); assertEquals(5.0, converter.convert(1.0), "Expected value when input is 1.0"); } @Test void testConstructorWithInvalidValues() { assertThrows(IllegalArgumentException.class, () -> new AffineConverter(Double.NaN, 3.0), "Constructor should throw IllegalArgumentException for NaN slope"); } @Test void testConvertWithNegativeValues() { assertEquals(-1.0, converter.convert(-2.0), "Negative input should convert correctly"); assertEquals(-3.0, new AffineConverter(-1.0, -1.0).convert(2.0), "Slope and intercept can be negative"); } @Test void testConvertWithFloatingPointPrecision() { double result = new AffineConverter(1.3333, 0.6667).convert(3.0); assertEquals(4.6666, result, 1e-4, "Conversion should maintain floating-point precision"); } @Test void testInvert() { AffineConverter inverted = converter.invert(); assertEquals(0.0, inverted.convert(3.0), "Inverted should return 0.0 for input 3.0"); assertEquals(1.0, inverted.convert(5.0), "Inverted should return 1.0 for input 5.0"); } @Test void testInvertWithZeroSlope() { AffineConverter zeroSlopeConverter = new AffineConverter(0.0, 3.0); assertThrows(AssertionError.class, zeroSlopeConverter::invert, "Invert should throw AssertionError when slope is zero"); } @Test void testCompose() { AffineConverter otherConverter = new AffineConverter(1.0, 2.0); AffineConverter composed = converter.compose(otherConverter); assertEquals(7.0, composed.convert(0.0), "Expected composed conversion at 0.0"); assertEquals(9.0, composed.convert(1.0), "Expected composed conversion at 1.0"); } @Test void testMultipleCompositions() { AffineConverter c1 = new AffineConverter(2.0, 1.0); AffineConverter c2 = new AffineConverter(3.0, -2.0); AffineConverter c3 = c1.compose(c2); // (2x + 1) ∘ (3x - 2) => 6x - 1 assertEquals(-3.0, c3.convert(0.0), "Composed transformation should return -3.0 at 0.0"); assertEquals(3.0, c3.convert(1.0), "Composed transformation should return 3.0 at 1.0"); } @Test void testIdentityComposition() { AffineConverter identity = new AffineConverter(1.0, 0.0); AffineConverter composed = converter.compose(identity); assertEquals(3.0, composed.convert(0.0), "Identity composition should not change the transformation"); assertEquals(7.0, composed.convert(2.0), "Identity composition should behave like the original"); } @Test void testLargeInputs() { double largeValue = 1e6; assertEquals(2.0 * largeValue + 3.0, converter.convert(largeValue), "Should handle large input values without overflow"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java
src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class BinaryToDecimalTest { @Test // Test converting binary to decimal public void testBinaryToDecimal() { // zeros at the starting should be removed assertEquals(0, BinaryToDecimal.binaryToDecimal(0)); assertEquals(1, BinaryToDecimal.binaryToDecimal(1)); assertEquals(5, BinaryToDecimal.binaryToDecimal(101)); assertEquals(63, BinaryToDecimal.binaryToDecimal(111111)); assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000)); assertEquals(0, BinaryToDecimal.binaryStringToDecimal("0")); assertEquals(1, BinaryToDecimal.binaryStringToDecimal("1")); assertEquals(5, BinaryToDecimal.binaryStringToDecimal("101")); assertEquals(63, BinaryToDecimal.binaryStringToDecimal("111111")); assertEquals(512, BinaryToDecimal.binaryStringToDecimal("1000000000")); } @Test // Test converting negative binary numbers public void testNegativeBinaryToDecimal() { assertEquals(-1, BinaryToDecimal.binaryToDecimal(-1)); assertEquals(-42, BinaryToDecimal.binaryToDecimal(-101010)); assertEquals(-1, BinaryToDecimal.binaryStringToDecimal("-1")); assertEquals(-42, BinaryToDecimal.binaryStringToDecimal("-101010")); } @Test // Test converting binary numbers with large values public void testLargeBinaryToDecimal() { assertEquals(262144L, BinaryToDecimal.binaryToDecimal(1000000000000000000L)); assertEquals(524287L, BinaryToDecimal.binaryToDecimal(1111111111111111111L)); assertEquals(262144L, BinaryToDecimal.binaryStringToDecimal("1000000000000000000")); assertEquals(524287L, BinaryToDecimal.binaryStringToDecimal("1111111111111111111")); } @ParameterizedTest @CsvSource({"2", "1234", "11112", "101021"}) void testNotCorrectBinaryInput(long binaryNumber) { assertThrows(IllegalArgumentException.class, () -> BinaryToDecimal.binaryToDecimal(binaryNumber)); assertThrows(IllegalArgumentException.class, () -> BinaryToDecimal.binaryStringToDecimal(Long.toString(binaryNumber))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java
src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class HexaDecimalToDecimalTest { @ParameterizedTest @CsvSource({ "A1, 161", // Simple case with two characters "1AC, 428", // Mixed-case input "0, 0", // Single zero "F, 15", // Single digit "10, 16", // Power of 16 "FFFF, 65535", // Max 4-character hex "7FFFFFFF, 2147483647" // Max positive int value }) public void testValidHexaToDecimal(String hexInput, int expectedDecimal) { assertEquals(expectedDecimal, HexaDecimalToDecimal.getHexaToDec(hexInput)); } @ParameterizedTest @CsvSource({ "G", // Invalid character "1Z", // Mixed invalid input "123G", // Valid prefix with invalid character "#$%" // Non-hexadecimal symbols }) public void testInvalidHexaToDecimal(String invalidHex) { assertThrows(IllegalArgumentException.class, () -> HexaDecimalToDecimal.getHexaToDec(invalidHex)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java
src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class RomanToIntegerTest { @Test public void testValidRomanToInteger() { assertEquals(1994, RomanToInteger.romanToInt("MCMXCIV")); assertEquals(58, RomanToInteger.romanToInt("LVIII")); assertEquals(1804, RomanToInteger.romanToInt("MDCCCIV")); assertEquals(9, RomanToInteger.romanToInt("IX")); assertEquals(4, RomanToInteger.romanToInt("IV")); assertEquals(3000, RomanToInteger.romanToInt("MMM")); } @Test public void testLowercaseInput() { assertEquals(1994, RomanToInteger.romanToInt("mcmxciv")); assertEquals(58, RomanToInteger.romanToInt("lviii")); } @Test public void testInvalidRomanNumerals() { assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("Z")); assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MZI")); assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MMMO")); } @Test public void testEmptyAndNullInput() { assertEquals(0, RomanToInteger.romanToInt("")); // Empty string case assertThrows(NullPointerException.class, () -> RomanToInteger.romanToInt(null)); // Null input case } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java
src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java
package com.thealgorithms.conversions; import static java.util.Map.entry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Test; public class UnitsConverterTest { @Test void testConvertThrowsForSameUnits() { final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("A", "B"), new AffineConverter(10.0, -20.0)))); assertThrows(IllegalArgumentException.class, () -> someConverter.convert("A", "A", 20.0)); assertThrows(IllegalArgumentException.class, () -> someConverter.convert("B", "B", 20.0)); } @Test void testConvertThrowsForUnknownUnits() { final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("A", "B"), new AffineConverter(10.0, -20.0)))); assertThrows(NoSuchElementException.class, () -> someConverter.convert("A", "X", 20.0)); assertThrows(NoSuchElementException.class, () -> someConverter.convert("X", "A", 20.0)); assertThrows(NoSuchElementException.class, () -> someConverter.convert("X", "Y", 20.0)); } @Test void testAvailableUnits() { final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)), entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)))); assertEquals(Set.of("Celsius", "Fahrenheit", "Kelvin"), someConverter.availableUnits()); } @Test void testInvertConversion() { final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("A", "B"), new AffineConverter(2.0, 5.0)))); // Check conversion from A -> B assertEquals(25.0, someConverter.convert("A", "B", 10.0), 0.0001); // Check inverse conversion from B -> A assertEquals(10.0, someConverter.convert("B", "A", 25.0), 0.0001); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/DecimalToBinaryTest.java
src/test/java/com/thealgorithms/conversions/DecimalToBinaryTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class DecimalToBinaryTest { @ParameterizedTest @CsvSource({"0, 0", "1, 1", "2, 10", "5, 101", "10, 1010", "15, 1111", "100, 1100100"}) void testConvertUsingConventionalAlgorithm(int decimal, int expectedBinary) { assertEquals(expectedBinary, DecimalToBinary.convertUsingConventionalAlgorithm(decimal)); } @ParameterizedTest @CsvSource({"0, 0", "1, 1", "2, 10", "5, 101", "10, 1010", "15, 1111", "100, 1100100"}) void testConvertUsingBitwiseAlgorithm(int decimal, int expectedBinary) { assertEquals(expectedBinary, DecimalToBinary.convertUsingBitwiseAlgorithm(decimal)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java
src/test/java/com/thealgorithms/conversions/PhoneticAlphabetConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class PhoneticAlphabetConverterTest { @ParameterizedTest @CsvSource({ "'AB', 'Alpha Bravo'", "'ABC', 'Alpha Bravo Charlie'", "'A1B2C3', 'Alpha One Bravo Two Charlie Three'", "'Hello', 'Hotel Echo Lima Lima Oscar'", "'123', 'One Two Three'", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", "'abcdefghijklmnopqrstuvwxyz0123456789', 'Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu Zero One Two Three Four Five Six Seven Eight Nine'", "'', ''", // Empty string case "'A B C', 'Alpha Bravo Charlie'", // String with spaces "'A@B#C', 'Alpha @ Bravo # Charlie'", // Special characters "'A B C 123', 'Alpha Bravo Charlie One Two Three'", // Mixed letters, digits, and spaces "'a b c', 'Alpha Bravo Charlie'", // Lowercase letters with spaces "'123!@#', 'One Two Three ! @ #'", // Numbers with special characters "'HELLO WORLD', 'Hotel Echo Lima Lima Oscar Whiskey Oscar Romeo Lima Delta'" // Words with space }) public void testTextToPhonetic(String input, String expectedOutput) { assertEquals(expectedOutput, PhoneticAlphabetConverter.textToPhonetic(input)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java
src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; /** * Unit tests for the {@link EndianConverter} class. */ public class HexaDecimalToBinaryTest { /** * Parameterized test to validate the conversion from little-endian to big-endian. * Hexadecimal values are passed as strings and converted to integers during the test. */ @ParameterizedTest @CsvSource({ "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement "0x0000007F, 0x7F000000" // Positive boundary case }) public void testLittleToBigEndian(String inputHex, String expectedHex) { int input = (int) Long.parseLong(inputHex.substring(2), 16); // Convert hex string to int int expected = (int) Long.parseLong(expectedHex.substring(2), 16); // Convert hex string to int assertEquals(expected, EndianConverter.littleToBigEndian(input)); } /** * Parameterized test to validate the conversion from big-endian to little-endian. */ @ParameterizedTest @CsvSource({ "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement "0x7F000000, 0x0000007F" // Positive boundary case }) public void testBigToLittleEndian(String inputHex, String expectedHex) { int input = (int) Long.parseLong(inputHex.substring(2), 16); // Convert hex string to int int expected = (int) Long.parseLong(expectedHex.substring(2), 16); // Convert hex string to int assertEquals(expected, EndianConverter.bigToLittleEndian(input)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class OctalToBinaryTest { @Test public void testConvertOctalToBinary() { assertEquals(101, OctalToBinary.convertOctalToBinary(5)); assertEquals(1001, OctalToBinary.convertOctalToBinary(11)); assertEquals(101010, OctalToBinary.convertOctalToBinary(52)); assertEquals(110, OctalToBinary.convertOctalToBinary(6)); } @Test public void testConvertOctalToBinarySingleDigit() { assertEquals(0, OctalToBinary.convertOctalToBinary(0)); assertEquals(1, OctalToBinary.convertOctalToBinary(1)); assertEquals(111, OctalToBinary.convertOctalToBinary(7)); } @Test public void testConvertOctalToBinaryMultipleDigits() { assertEquals(100110111, OctalToBinary.convertOctalToBinary(467)); assertEquals(111101, OctalToBinary.convertOctalToBinary(75)); assertEquals(111100101, OctalToBinary.convertOctalToBinary(745)); } @Test public void testConvertOctalToBinaryWithZeroPadding() { assertEquals(100001010, OctalToBinary.convertOctalToBinary(412)); assertEquals(101101110, OctalToBinary.convertOctalToBinary(556)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java
src/test/java/com/thealgorithms/conversions/TurkishToLatinConversionTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class TurkishToLatinConversionTest { @ParameterizedTest @CsvSource({ "'çalışma', 'calisma'", // Turkish to Latin conversion for lowercase "'ÇALIŞMA', 'CALISMA'", // Turkish to Latin conversion for uppercase "'İSTANBUL', 'ISTANBUL'", // Special case of 'İ' to 'I' "'istanbul', 'istanbul'", // Special case of 'ı' to 'i' "'GÜL', 'GUL'", // Special case of 'Ü' to 'U' "'gül', 'gul'", // Special case of 'ü' to 'u' "'ÖĞRENME', 'OGRENME'", // Special case of 'Ö' to 'O' and 'Ğ' to 'G' "'öğrenme', 'ogrenme'", // Special case of 'ö' to 'o' and 'ğ' to 'g' "'ŞEHIR', 'SEHIR'", // Special case of 'Ş' to 'S' "'şehir', 'sehir'", // Special case of 'ş' to 's' "'HELLO', 'HELLO'", // String with no Turkish characters, should remain unchanged "'Merhaba Dünya!', 'Merhaba Dunya!'", // Mixed Turkish and Latin characters with punctuation "'Çift kişilik yataklı odalar', 'Cift kisilik yatakli odalar'", // Full sentence conversion "'', ''" // Empty string case }) public void testConvertTurkishToLatin(String input, String expectedOutput) { assertEquals(expectedOutput, TurkishToLatinConversion.convertTurkishToLatin(input)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java
src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java
package com.thealgorithms.conversions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class OctalToDecimalTest { @ParameterizedTest @CsvSource({"10, 8", "7, 7", "77, 63", "123, 83", "0, 0", "777, 511", "2671, 1465", "275, 189"}) void testConvertOctalToDecimal(String inputOctal, int expectedDecimal) { Assertions.assertEquals(expectedDecimal, OctalToDecimal.convertOctalToDecimal(inputOctal)); } @ParameterizedTest @CsvSource({"'', Input cannot be null or empty", "'8', Incorrect input: Expecting an octal number (digits 0-7)", "'19', Incorrect input: Expecting an octal number (digits 0-7)"}) void testIncorrectInput(String inputOctal, String expectedMessage) { IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> OctalToDecimal.convertOctalToDecimal(inputOctal)); Assertions.assertEquals(expectedMessage, exception.getMessage()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/DecimalToOctalTest.java
src/test/java/com/thealgorithms/conversions/DecimalToOctalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class DecimalToOctalTest { @ParameterizedTest @CsvSource({"0, 0", "7, 7", "8, 10", "10, 12", "64, 100", "83, 123", "7026, 15562"}) void testConvertToOctal(int decimal, int expectedOctal) { assertEquals(expectedOctal, DecimalToOctal.convertToOctal(decimal)); } @Test void testConvertToOctalNegativeNumber() { assertThrows(IllegalArgumentException.class, () -> DecimalToOctal.convertToOctal(-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/conversions/NumberToWordsTest.java
src/test/java/com/thealgorithms/conversions/NumberToWordsTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import java.math.BigDecimal; import org.junit.jupiter.api.Test; public class NumberToWordsTest { @Test void testNullInput() { assertEquals("Invalid Input", NumberToWords.convert(null), "Null input should return 'Invalid Input'"); } @Test void testZeroInput() { assertEquals("Zero", NumberToWords.convert(BigDecimal.ZERO), "Zero input should return 'Zero'"); } @Test void testPositiveWholeNumbers() { assertEquals("One", NumberToWords.convert(BigDecimal.ONE), "1 should convert to 'One'"); assertEquals("One Thousand", NumberToWords.convert(new BigDecimal("1000")), "1000 should convert to 'One Thousand'"); assertEquals("One Million", NumberToWords.convert(new BigDecimal("1000000")), "1000000 should convert to 'One Million'"); } @Test void testNegativeWholeNumbers() { assertEquals("Negative One", NumberToWords.convert(new BigDecimal("-1")), "-1 should convert to 'Negative One'"); assertEquals("Negative One Thousand", NumberToWords.convert(new BigDecimal("-1000")), "-1000 should convert to 'Negative One Thousand'"); } @Test void testFractionalNumbers() { assertEquals("Zero Point One Two Three", NumberToWords.convert(new BigDecimal("0.123")), "0.123 should convert to 'Zero Point One Two Three'"); assertEquals("Negative Zero Point Four Five Six", NumberToWords.convert(new BigDecimal("-0.456")), "-0.456 should convert to 'Negative Zero Point Four Five Six'"); } @Test void testLargeNumbers() { assertEquals("Nine Hundred Ninety Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine", NumberToWords.convert(new BigDecimal("999999999")), "999999999 should convert correctly"); assertEquals("One Trillion", NumberToWords.convert(new BigDecimal("1000000000000")), "1000000000000 should convert to 'One Trillion'"); } @Test void testNegativeLargeNumbers() { assertEquals("Negative Nine Trillion Eight Hundred Seventy Six Billion Five Hundred Forty Three Million Two Hundred Ten Thousand Nine Hundred Eighty Seven", NumberToWords.convert(new BigDecimal("-9876543210987")), "-9876543210987 should convert correctly"); } @Test void testFloatingPointPrecision() { assertEquals("One Million Point Zero Zero One", NumberToWords.convert(new BigDecimal("1000000.001")), "1000000.001 should convert to 'One Million Point Zero Zero One'"); } @Test void testEdgeCases() { assertEquals("Zero", NumberToWords.convert(new BigDecimal("-0.0")), "-0.0 should convert to 'Zero'"); assertEquals("Zero Point Zero Zero Zero Zero Zero Zero One", NumberToWords.convert(new BigDecimal("1E-7")), "1E-7 should convert to 'Zero Point Zero Zero Zero Zero Zero Zero One'"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java
src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class BinaryToOctalTest { @ParameterizedTest @CsvSource({"0, 0", "1, 1", "10, 2", "111, 7", "1000, 10", "1111, 17", "110101, 65", "1010101, 125", "110110011, 663", "111111111, 777", "10010110, 226", "1011101, 135"}) void testConvertBinaryToOctal(int binary, String expectedOctal) { assertEquals(expectedOctal, BinaryToOctal.convertBinaryToOctal(binary)); } @Test void testIncorrectInput() { assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(1234)); assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(102)); assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(-1010)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/WordsToNumberTest.java
src/test/java/com/thealgorithms/conversions/WordsToNumberTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigDecimal; import org.junit.jupiter.api.Test; public class WordsToNumberTest { @Test void testNullInput() { WordsToNumberException exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert(null)); assertEquals(WordsToNumberException.ErrorType.NULL_INPUT, exception.getErrorType(), "Exception should be of type NULL_INPUT"); } @Test void testStandardCases() { assertEquals("0", WordsToNumber.convert("zero"), "'zero' should convert to '0'"); assertEquals("5", WordsToNumber.convert("five"), "'five' should convert to '5'"); assertEquals("21", WordsToNumber.convert("twenty one"), "'twenty one' should convert to '21'"); assertEquals("101", WordsToNumber.convert("one hundred one"), "'one hundred' should convert to '101'"); assertEquals("342", WordsToNumber.convert("three hundred and forty two"), "'three hundred and forty two' should convert to '342'"); } @Test void testLargeNumbers() { assertEquals("1000000", WordsToNumber.convert("one million"), "'one million' should convert to '1000000'"); assertEquals("1000000000", WordsToNumber.convert("one billion"), "'one billion' should convert to '1000000000'"); assertEquals("1000000000000", WordsToNumber.convert("one trillion"), "'one trillion' should convert to '1000000000000'"); assertEquals("999000000900999", WordsToNumber.convert("nine hundred ninety nine trillion nine hundred thousand nine hundred and ninety nine"), "'nine hundred ninety nine trillion nine hundred thousand nine hundred and ninety nine' should convert to '999000000900999'"); } @Test void testNegativeNumbers() { assertEquals("-5", WordsToNumber.convert("negative five"), "'negative five' should convert to '-5'"); assertEquals("-120", WordsToNumber.convert("negative one hundred and twenty"), "'negative one hundred and twenty' should convert correctly"); } @Test void testNegativeLargeNumbers() { assertEquals("-1000000000000", WordsToNumber.convert("negative one trillion"), "'negative one trillion' should convert to '-1000000000000'"); assertEquals("-9876543210987", WordsToNumber.convert("Negative Nine Trillion Eight Hundred Seventy Six Billion Five Hundred Forty Three Million Two Hundred Ten Thousand Nine Hundred Eighty Seven"), ""); } @Test void testDecimalNumbers() { assertEquals("3.1415", WordsToNumber.convert("three point one four one five"), "'three point one four one five' should convert to '3.1415'"); assertEquals("-2.718", WordsToNumber.convert("negative two point seven one eight"), "'negative two point seven one eight' should convert to '-2.718'"); assertEquals("-1E-7", WordsToNumber.convert("negative zero point zero zero zero zero zero zero one"), "'negative zero point zero zero zero zero zero zero one' should convert to '-1E-7'"); } @Test void testLargeDecimalNumbers() { assertEquals("1000000000.0000000001", WordsToNumber.convert("one billion point zero zero zero zero zero zero zero zero zero one"), "Tests a large whole number with a tiny fractional part"); assertEquals("999999999999999.9999999999999", WordsToNumber.convert("nine hundred ninety nine trillion nine hundred ninety nine billion nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine point nine nine nine nine nine nine nine nine nine nine nine nine nine"), "Tests maximum scale handling for large decimal numbers"); assertEquals("0.505", WordsToNumber.convert("zero point five zero five"), "Tests a decimal with an internal zero, ensuring correct parsing"); assertEquals("42.00000000000001", WordsToNumber.convert("forty two point zero zero zero zero zero zero zero zero zero zero zero zero zero one"), "Tests a decimal with leading zeros before a significant figure"); assertEquals("7.89E-7", WordsToNumber.convert("zero point zero zero zero zero zero zero seven eight nine"), "Tests scientific notation for a small decimal with multiple digits"); assertEquals("0.999999", WordsToNumber.convert("zero point nine nine nine nine nine nine"), "Tests a decimal close to one with multiple repeated digits"); } @Test void testCaseInsensitivity() { assertEquals("21", WordsToNumber.convert("TWENTY-ONE"), "Uppercase should still convert correctly"); assertEquals("-100.0001", WordsToNumber.convert("negAtiVe OnE HuNdReD, point ZeRO Zero zERo ONE"), "Mixed case should still convert correctly"); assertEquals("-225647.00019", WordsToNumber.convert("nEgative twO HundRed, and twenty-Five thOusaNd, six huNdred Forty-Seven, Point zero zero zero One nInE")); } @Test void testInvalidInputs() { WordsToNumberException exception; exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("negative one hundred AlPha")); assertEquals(WordsToNumberException.ErrorType.UNKNOWN_WORD, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("twenty thirteen")); assertEquals(WordsToNumberException.ErrorType.UNEXPECTED_WORD, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("negative negative ten")); assertEquals(WordsToNumberException.ErrorType.MULTIPLE_NEGATIVES, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("one hundred hundred")); assertEquals(WordsToNumberException.ErrorType.UNEXPECTED_WORD, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("one thousand and hundred")); assertEquals(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("one thousand hundred")); assertEquals(WordsToNumberException.ErrorType.UNEXPECTED_WORD, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("nine hundred and nine hundred")); assertEquals(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("forty two point")); assertEquals(WordsToNumberException.ErrorType.MISSING_DECIMAL_NUMBERS, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("sixty seven point hello")); assertEquals(WordsToNumberException.ErrorType.UNEXPECTED_WORD_AFTER_POINT, exception.getErrorType()); exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convert("one negative")); assertEquals(WordsToNumberException.ErrorType.INVALID_NEGATIVE, exception.getErrorType()); } @Test void testConvertToBigDecimal() { assertEquals(new BigDecimal("-100000000000000.056"), WordsToNumber.convertToBigDecimal("negative one hundred trillion point zero five six"), "should convert to appropriate BigDecimal value"); WordsToNumberException exception = assertThrows(WordsToNumberException.class, () -> WordsToNumber.convertToBigDecimal(null)); assertEquals(WordsToNumberException.ErrorType.NULL_INPUT, exception.getErrorType(), "Exception should be of type NULL_INPUT"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/HexToOctTest.java
src/test/java/com/thealgorithms/conversions/HexToOctTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class HexToOctTest { @Test public void testHexToDecimal() { assertEquals(255, HexToOct.hexToDecimal("FF")); assertEquals(16, HexToOct.hexToDecimal("10")); assertEquals(0, HexToOct.hexToDecimal("0")); assertEquals(4095, HexToOct.hexToDecimal("FFF")); } @Test public void testDecimalToOctal() { assertEquals(110, HexToOct.decimalToOctal(HexToOct.hexToDecimal("48"))); assertEquals(255, HexToOct.decimalToOctal(HexToOct.hexToDecimal("AD"))); assertEquals(377, HexToOct.decimalToOctal(255)); assertEquals(20, HexToOct.decimalToOctal(16)); assertEquals(0, HexToOct.decimalToOctal(0)); assertEquals(7777, HexToOct.decimalToOctal(4095)); } @Test public void testHexToOctal() { assertEquals(377, HexToOct.hexToOctal("FF")); assertEquals(20, HexToOct.hexToOctal("10")); assertEquals(0, HexToOct.hexToOctal("0")); assertEquals(7777, HexToOct.hexToOctal("FFF")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java
src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java
package com.thealgorithms.conversions; import static java.util.Map.entry; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; import java.util.Set; 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 UnitConversionsTest { private static void addData(Stream.Builder<Arguments> builder, Map<String, Double> values) { for (var first : values.entrySet()) { for (var second : values.entrySet()) { if (!first.getKey().equals(second.getKey())) { builder.add(Arguments.of(first.getKey(), second.getKey(), first.getValue(), second.getValue())); } } } } private static Stream<Arguments> temperatureData() { final Map<String, Double> boilingPointOfWater = Map.ofEntries(entry("Celsius", 99.9839), entry("Fahrenheit", 211.97102), entry("Kelvin", 373.1339), entry("Réaumur", 79.98712), entry("Delisle", 0.02415), entry("Rankine", 671.64102)); final Map<String, Double> freezingPointOfWater = Map.ofEntries(entry("Celsius", 0.0), entry("Fahrenheit", 32.0), entry("Kelvin", 273.15), entry("Réaumur", 0.0), entry("Delisle", 150.0), entry("Rankine", 491.67)); Stream.Builder<Arguments> builder = Stream.builder(); addData(builder, boilingPointOfWater); addData(builder, freezingPointOfWater); return builder.build(); } @ParameterizedTest @MethodSource("temperatureData") void testTemperature(String inputUnit, String outputUnit, double value, double expected) { final double result = UnitConversions.TEMPERATURE.convert(inputUnit, outputUnit, value); assertEquals(expected, result, 0.00001); } @Test void testTemperatureUnits() { final Set<String> expectedUnits = Set.of("Celsius", "Fahrenheit", "Kelvin", "Réaumur", "Rankine", "Delisle"); assertEquals(expectedUnits, UnitConversions.TEMPERATURE.availableUnits()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/CoordinateConverterTest.java
src/test/java/com/thealgorithms/conversions/CoordinateConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class CoordinateConverterTest { @ParameterizedTest @CsvSource({"0, 0, 0, 0", "1, 0, 1, 0", "0, 1, 1, 90", "-1, 0, 1, 180", "0, -1, 1, -90", "3, 4, 5, 53.13010235415599"}) void testCartesianToPolar(double x, double y, double expectedR, double expectedTheta) { assertArrayEquals(new double[] {expectedR, expectedTheta}, CoordinateConverter.cartesianToPolar(x, y), 1e-9); } @ParameterizedTest @CsvSource({"1, 0, 1, 0", "1, 90, 0, 1", "1, 180, -1, 0", "1, -90, 0, -1", "5, 53.13010235415599, 3, 4"}) void testPolarToCartesian(double r, double theta, double expectedX, double expectedY) { assertArrayEquals(new double[] {expectedX, expectedY}, CoordinateConverter.polarToCartesian(r, theta), 1e-9); } @ParameterizedTest @CsvSource({"NaN, 1", "1, NaN", "Infinity, 1", "1, Infinity", "-Infinity, 1", "1, -Infinity"}) void testCartesianToPolarInvalidInputs(double x, double y) { assertThrows(IllegalArgumentException.class, () -> CoordinateConverter.cartesianToPolar(x, y)); } @ParameterizedTest @CsvSource({"-1, 0", "1, NaN", "1, Infinity", "1, -Infinity"}) void testPolarToCartesianInvalidInputs(double r, double theta) { assertThrows(IllegalArgumentException.class, () -> CoordinateConverter.polarToCartesian(r, theta)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java
src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java
package com.thealgorithms.conversions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class OctalToHexadecimalTest { @ParameterizedTest @CsvSource({"0, 0", "7, 7", "10, 8", "17, F", "20, 10", "777, 1FF", "1234, 29C", "752, 1EA", "536, 15E"}) void testCorrectInputs(String inputOctal, String expectedHex) { int decimal = OctalToHexadecimal.octalToDecimal(inputOctal); String hex = OctalToHexadecimal.decimalToHexadecimal(decimal); Assertions.assertEquals(expectedHex, hex); } @ParameterizedTest @CsvSource({"'', Input cannot be null or empty", "'8', Incorrect octal digit: 8", "'19', Incorrect octal digit: 9"}) void testIncorrectInputs(String inputOctal, String expectedMessage) { IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> OctalToHexadecimal.octalToDecimal(inputOctal)); Assertions.assertEquals(expectedMessage, exception.getMessage()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/TemperatureConverterTest.java
src/test/java/com/thealgorithms/conversions/TemperatureConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class TemperatureConverterTest { private static final double DELTA = 0.01; @Test void testCelsiusToFahrenheit() { assertEquals(32.0, TemperatureConverter.celsiusToFahrenheit(0.0), DELTA); assertEquals(212.0, TemperatureConverter.celsiusToFahrenheit(100.0), DELTA); assertEquals(-40.0, TemperatureConverter.celsiusToFahrenheit(-40.0), DELTA); assertEquals(98.6, TemperatureConverter.celsiusToFahrenheit(37.0), DELTA); } @Test void testCelsiusToKelvin() { assertEquals(273.15, TemperatureConverter.celsiusToKelvin(0.0), DELTA); assertEquals(373.15, TemperatureConverter.celsiusToKelvin(100.0), DELTA); assertEquals(233.15, TemperatureConverter.celsiusToKelvin(-40.0), DELTA); } @Test void testFahrenheitToCelsius() { assertEquals(0.0, TemperatureConverter.fahrenheitToCelsius(32.0), DELTA); assertEquals(100.0, TemperatureConverter.fahrenheitToCelsius(212.0), DELTA); assertEquals(-40.0, TemperatureConverter.fahrenheitToCelsius(-40.0), DELTA); assertEquals(37.0, TemperatureConverter.fahrenheitToCelsius(98.6), DELTA); } @Test void testFahrenheitToKelvin() { assertEquals(273.15, TemperatureConverter.fahrenheitToKelvin(32.0), DELTA); assertEquals(373.15, TemperatureConverter.fahrenheitToKelvin(212.0), DELTA); assertEquals(233.15, TemperatureConverter.fahrenheitToKelvin(-40.0), DELTA); } @Test void testKelvinToCelsius() { assertEquals(0.0, TemperatureConverter.kelvinToCelsius(273.15), DELTA); assertEquals(100.0, TemperatureConverter.kelvinToCelsius(373.15), DELTA); assertEquals(-273.15, TemperatureConverter.kelvinToCelsius(0.0), DELTA); } @Test void testKelvinToFahrenheit() { assertEquals(32.0, TemperatureConverter.kelvinToFahrenheit(273.15), DELTA); assertEquals(212.0, TemperatureConverter.kelvinToFahrenheit(373.15), DELTA); assertEquals(-40.0, TemperatureConverter.kelvinToFahrenheit(233.15), 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/conversions/MorseCodeConverterTest.java
src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MorseCodeConverterTest { @Test public void testTextToMorse() { assertEquals(".- -...", MorseCodeConverter.textToMorse("AB")); assertEquals(".... . .-.. .-.. --- | .-- --- .-. .-.. -..", MorseCodeConverter.textToMorse("HELLO WORLD")); } @Test public void testMorseToText() { assertEquals("AB", MorseCodeConverter.morseToText(".- -...")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/AnyBaseToDecimalTest.java
src/test/java/com/thealgorithms/conversions/AnyBaseToDecimalTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class AnyBaseToDecimalTest { @ParameterizedTest @CsvSource({"1010, 2, 10", "777, 8, 511", "999, 10, 999", "ABCDEF, 16, 11259375", "XYZ, 36, 44027", "0, 2, 0", "A, 16, 10", "Z, 36, 35"}) void testConvertToDecimal(String input, int radix, int expected) { assertEquals(expected, AnyBaseToDecimal.convertToDecimal(input, radix)); } @Test void testIncorrectInput() { assertThrows(NumberFormatException.class, () -> AnyBaseToDecimal.convertToDecimal("G", 16)); assertThrows(NumberFormatException.class, () -> AnyBaseToDecimal.convertToDecimal("XYZ", 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/conversions/AnytoAnyTest.java
src/test/java/com/thealgorithms/conversions/AnytoAnyTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class AnytoAnyTest { @Test void testValidConversions() { assertEquals(101, AnytoAny.convertBase(5, 10, 2), "Decimal 5 should convert to binary 101"); assertEquals(2, AnytoAny.convertBase(2, 2, 10), "Binary 10 should convert to decimal 2"); assertEquals(6, AnytoAny.convertBase(110, 2, 8), "Binary 110 should convert to octal 6"); assertEquals(111, AnytoAny.convertBase(7, 10, 2), "Decimal 7 should convert to binary 111"); } @Test void testDecimalToBinary() { assertEquals(1101, AnytoAny.convertBase(13, 10, 2), "Decimal 13 should convert to binary 1101"); assertEquals(0, AnytoAny.convertBase(0, 10, 2), "Decimal 0 should convert to binary 0"); } @Test void testBinaryToDecimal() { assertEquals(13, AnytoAny.convertBase(1101, 2, 10), "Binary 1101 should convert to decimal 13"); assertEquals(0, AnytoAny.convertBase(0, 2, 10), "Binary 0 should convert to decimal 0"); } @Test void testOctalToDecimal() { assertEquals(8, AnytoAny.convertBase(10, 8, 10), "Octal 10 should convert to decimal 8"); assertEquals(65, AnytoAny.convertBase(101, 8, 10), "Octal 101 should convert to decimal 65"); } @Test void testInvalidBases() { assertThrows(IllegalArgumentException.class, () -> AnytoAny.convertBase(5, 1, 10), "Source base less than 2 should throw IllegalArgumentException"); assertThrows(IllegalArgumentException.class, () -> AnytoAny.convertBase(5, 10, 11), "Destination base greater than 10 should throw IllegalArgumentException"); } @Test void testLargeNumberConversion() { assertEquals(1111101000, AnytoAny.convertBase(1000, 10, 2), "Decimal 1000 should convert to binary 1111101000"); assertEquals(1750, AnytoAny.convertBase(1000, 10, 8), "Decimal 1000 should convert to octal 1750"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/TimeConverterTest.java
src/test/java/com/thealgorithms/conversions/TimeConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; class TimeConverterTest { @ParameterizedTest(name = "{0} {1} -> {2} {3}") @CsvSource({"60, seconds, minutes, 1", "120, seconds, minutes, 2", "2, minutes, seconds, 120", "2, hours, minutes, 120", "1, days, hours, 24", "1, weeks, days, 7", "1, months, days, 30.438", "1, years, days, 365.25", "3600, seconds, hours, 1", "86400, seconds, days, 1", "604800, seconds, weeks, 1", "31557600, seconds, years, 1"}) void testValidConversions(double value, String from, String to, double expected) { assertEquals(expected, TimeConverter.convertTime(value, from, to)); } @Test @DisplayName("Zero conversion returns zero") void testZeroValue() { assertEquals(0.0, TimeConverter.convertTime(0, "seconds", "hours")); } @Test @DisplayName("Same-unit conversion returns original value") void testSameUnitConversion() { assertEquals(123.456, TimeConverter.convertTime(123.456, "minutes", "minutes")); } @Test @DisplayName("Negative value throws exception") void testNegativeValue() { assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(-5, "seconds", "minutes")); } @ParameterizedTest @CsvSource({"lightyears, seconds", "minutes, centuries"}) void testInvalidUnits(String from, String to) { assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, from, to)); } @Test @DisplayName("Null unit throws exception") void testNullUnit() { assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, null, "seconds")); assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, "minutes", null)); assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, null, null)); } static Stream<org.junit.jupiter.params.provider.Arguments> roundTripCases() { return Stream.of(org.junit.jupiter.params.provider.Arguments.of(1.0, "hours", "minutes"), org.junit.jupiter.params.provider.Arguments.of(2.5, "days", "hours"), org.junit.jupiter.params.provider.Arguments.of(1000, "seconds", "minutes")); } @ParameterizedTest @MethodSource("roundTripCases") @DisplayName("Round-trip conversion returns original value") void testRoundTripConversion(double value, String from, String to) { double converted = TimeConverter.convertTime(value, from, to); double roundTrip = TimeConverter.convertTime(converted, to, from); assertEquals(Math.round(value * 1000.0) / 1000.0, Math.round(roundTrip * 1000.0) / 1000.0, 0.05); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/Base64Test.java
src/test/java/com/thealgorithms/conversions/Base64Test.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; /** * Test cases for Base64 encoding and decoding. * * Author: Nithin U. * Github: https://github.com/NithinU2802 */ class Base64Test { @Test void testBase64Alphabet() { // Test that all Base64 characters are handled correctly String allChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; String encoded = Base64.encode(allChars); String decoded = Base64.decodeToString(encoded); assertEquals(allChars, decoded); } @ParameterizedTest @CsvSource({"'', ''", "A, QQ==", "AB, QUI=", "ABC, QUJD", "ABCD, QUJDRA==", "Hello, SGVsbG8=", "'Hello World', SGVsbG8gV29ybGQ=", "'Hello, World!', 'SGVsbG8sIFdvcmxkIQ=='", "'The quick brown fox jumps over the lazy dog', 'VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw=='", "123456789, MTIzNDU2Nzg5", "'Base64 encoding test', 'QmFzZTY0IGVuY29kaW5nIHRlc3Q='"}) void testStringEncoding(String input, String expected) { assertEquals(expected, Base64.encode(input)); } @ParameterizedTest @CsvSource({"'', ''", "QQ==, A", "QUI=, AB", "QUJD, ABC", "QUJDRA==, ABCD", "SGVsbG8=, Hello", "'SGVsbG8gV29ybGQ=', 'Hello World'", "'SGVsbG8sIFdvcmxkIQ==', 'Hello, World!'", "'VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==', 'The quick brown fox jumps over the lazy dog'", "MTIzNDU2Nzg5, 123456789", "'QmFzZTY0IGVuY29kaW5nIHRlc3Q=', 'Base64 encoding test'"}) void testStringDecoding(String input, String expected) { assertEquals(expected, Base64.decodeToString(input)); } @Test void testByteArrayEncoding() { byte[] input = {72, 101, 108, 108, 111}; String expected = "SGVsbG8="; assertEquals(expected, Base64.encode(input)); } @Test void testByteArrayDecoding() { String input = "SGVsbG8="; byte[] expected = {72, 101, 108, 108, 111}; assertArrayEquals(expected, Base64.decode(input)); } @Test void testRoundTripEncoding() { String[] testStrings = {"", "A", "AB", "ABC", "Hello, World!", "The quick brown fox jumps over the lazy dog", "1234567890", "Special chars: !@#$%^&*()_+-=[]{}|;:,.<>?", "Unicode: வணக்கம்", // Tamil for "Hello" "Multi-line\nstring\rwith\tdifferent\nwhitespace"}; for (String original : testStrings) { String encoded = Base64.encode(original); String decoded = Base64.decodeToString(encoded); assertEquals(original, decoded, "Round trip failed for: " + original); } } @Test void testRoundTripByteArrayEncoding() { byte[][] testArrays = {{}, {0}, {-1}, {0, 1, 2, 3, 4, 5}, {-128, -1, 0, 1, 127}, {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33}}; for (byte[] original : testArrays) { String encoded = Base64.encode(original); byte[] decoded = Base64.decode(encoded); assertArrayEquals(original, decoded, "Round trip failed for byte array"); } } @Test void testBinaryData() { // Test with binary data that might contain null bytes byte[] binaryData = new byte[256]; for (int i = 0; i < 256; i++) { binaryData[i] = (byte) i; } String encoded = Base64.encode(binaryData); byte[] decoded = Base64.decode(encoded); assertArrayEquals(binaryData, decoded); } @Test void testNullInputEncoding() { assertThrows(IllegalArgumentException.class, () -> Base64.encode((String) null)); assertThrows(IllegalArgumentException.class, () -> Base64.encode((byte[]) null)); } @Test void testNullInputDecoding() { assertThrows(IllegalArgumentException.class, () -> Base64.decode(null)); assertThrows(IllegalArgumentException.class, () -> Base64.decodeToString(null)); } @Test void testInvalidBase64Characters() { assertThrows(IllegalArgumentException.class, () -> Base64.decode("SGVsbG8@")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("SGVsbG8#")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("SGVsbG8$")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("SGVsbG8%")); } @Test void testInvalidLength() { // Length must be multiple of 4 assertThrows(IllegalArgumentException.class, () -> Base64.decode("Q")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("QQ")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("QQQ")); } @Test void testInvalidPaddingPosition() { // '=' can only appear at the end assertThrows(IllegalArgumentException.class, () -> Base64.decode("Q=QQ")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("Q=Q=")); assertThrows(IllegalArgumentException.class, () -> Base64.decode("=QQQ")); } @Test void testPaddingVariations() { // Test different padding scenarios '=' assertEquals("A", Base64.decodeToString("QQ==")); assertEquals("AB", Base64.decodeToString("QUI=")); assertEquals("ABC", Base64.decodeToString("QUJD")); } @Test void testPaddingConsistency() { // Ensure that strings requiring different amounts of padding encode/decode correctly String[] testCases = {"A", "AB", "ABC", "ABCD", "ABCDE", "ABCDEF"}; for (String test : testCases) { String encoded = Base64.encode(test); String decoded = Base64.decodeToString(encoded); assertEquals(test, decoded); // Verify padding is correct int expectedPadding = (3 - (test.length() % 3)) % 3; int actualPadding = 0; for (int i = encoded.length() - 1; i >= 0 && encoded.charAt(i) == '='; i--) { actualPadding++; } assertEquals(expectedPadding, actualPadding, "Incorrect padding for: " + test); } } @Test void testLargeData() { // Test with larger data to ensure scalability StringBuilder largeString = new StringBuilder(); for (int i = 0; i < 1000; i++) { largeString.append("This is a test string for Base64 encoding. "); } String original = largeString.toString(); String encoded = Base64.encode(original); String decoded = Base64.decodeToString(encoded); assertEquals(original, decoded); } @Test void testEmptyAndSingleCharacter() { // Test edge cases assertEquals("", Base64.encode("")); assertEquals("", Base64.decodeToString("")); assertEquals("QQ==", Base64.encode("A")); assertEquals("A", Base64.decodeToString("QQ==")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/IntegerToEnglishTest.java
src/test/java/com/thealgorithms/conversions/IntegerToEnglishTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class IntegerToEnglishTest { @Test public void testIntegerToEnglish() { assertEquals("Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven", IntegerToEnglish.integerToEnglishWords(2147483647)); assertEquals("One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven", IntegerToEnglish.integerToEnglishWords(1234567)); assertEquals("Twelve Thousand Three Hundred Forty Five", IntegerToEnglish.integerToEnglishWords(12345)); assertEquals("One Hundred", IntegerToEnglish.integerToEnglishWords(100)); assertEquals("Zero", IntegerToEnglish.integerToEnglishWords(0)); } @Test public void testSmallNumbers() { assertEquals("Ten", IntegerToEnglish.integerToEnglishWords(10)); assertEquals("Nineteen", IntegerToEnglish.integerToEnglishWords(19)); assertEquals("Twenty One", IntegerToEnglish.integerToEnglishWords(21)); assertEquals("Ninety Nine", IntegerToEnglish.integerToEnglishWords(99)); } @Test public void testHundreds() { assertEquals("One Hundred One", IntegerToEnglish.integerToEnglishWords(101)); assertEquals("Five Hundred Fifty", IntegerToEnglish.integerToEnglishWords(550)); assertEquals("Nine Hundred Ninety Nine", IntegerToEnglish.integerToEnglishWords(999)); } @Test public void testThousands() { assertEquals("One Thousand", IntegerToEnglish.integerToEnglishWords(1000)); assertEquals("Ten Thousand One", IntegerToEnglish.integerToEnglishWords(10001)); assertEquals("Seventy Six Thousand Five Hundred Forty Three", IntegerToEnglish.integerToEnglishWords(76543)); } @Test public void testEdgeCases() { assertEquals("One Million", IntegerToEnglish.integerToEnglishWords(1_000_000)); assertEquals("One Billion", IntegerToEnglish.integerToEnglishWords(1_000_000_000)); assertEquals("Two Thousand", IntegerToEnglish.integerToEnglishWords(2000)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/conversions/EndianConverterTest.java
src/test/java/com/thealgorithms/conversions/EndianConverterTest.java
package com.thealgorithms.conversions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class EndianConverterTest { @ParameterizedTest @CsvSource({ "0x78563412, 0x12345678", "0x00000000, 0x00000000", "0x00000001, 0x01000000", "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement "0x0000007F, 0x7F000000" // Positive boundary case }) public void testLittleToBigEndian(String inputHex, String expectedHex) { int input = (int) Long.parseLong(inputHex.substring(2), 16); // Convert hex string to int int expected = (int) Long.parseLong(expectedHex.substring(2), 16); // Convert hex string to int assertEquals(expected, EndianConverter.littleToBigEndian(input)); } @ParameterizedTest @CsvSource({ "0x12345678, 0x78563412", "0x00000000, 0x00000000", "0x01000000, 0x00000001", "0xFFFFFFFF, 0xFFFFFFFF", // -1 in two's complement "0x7F000000, 0x0000007F" // Positive boundary case }) public void testBigToLittleEndian(String inputHex, String expectedHex) { int input = (int) Long.parseLong(inputHex.substring(2), 16); // Convert hex string to int int expected = (int) Long.parseLong(expectedHex.substring(2), 16); // Convert hex string to int assertEquals(expected, EndianConverter.bigToLittleEndian(input)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/CountLeadingZerosTest.java
src/test/java/com/thealgorithms/bitmanipulation/CountLeadingZerosTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CountLeadingZerosTest { @Test public void testCountLeadingZeros() { assertEquals(29, CountLeadingZeros.countLeadingZeros(5)); // 000...0101 has 29 leading zeros assertEquals(32, CountLeadingZeros.countLeadingZeros(0)); // 000...0000 has 32 leading zeros assertEquals(31, CountLeadingZeros.countLeadingZeros(1)); // 000...0001 has 31 leading zeros assertEquals(0, CountLeadingZeros.countLeadingZeros(-1)); // No leading zeros in negative number (-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/bitmanipulation/OnesComplementTest.java
src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; /** * Test case for Highest Set Bit * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma) */ public class OnesComplementTest { @Test public void testOnesComplementAllZeroes() { // Test cases with all-zero binary strings assertEquals("1111", OnesComplement.onesComplement("0000")); assertEquals("111", OnesComplement.onesComplement("000")); assertEquals("11", OnesComplement.onesComplement("00")); assertEquals("1", OnesComplement.onesComplement("0")); } @Test public void testOnesComplementAllOnes() { // Test cases with all-one binary strings assertEquals("0000", OnesComplement.onesComplement("1111")); assertEquals("000", OnesComplement.onesComplement("111")); assertEquals("00", OnesComplement.onesComplement("11")); assertEquals("0", OnesComplement.onesComplement("1")); } @Test public void testOnesComplementMixedBits() { // Test more mixed binary patterns assertEquals("1010", OnesComplement.onesComplement("0101")); assertEquals("0101", OnesComplement.onesComplement("1010")); assertEquals("1100", OnesComplement.onesComplement("0011")); assertEquals("0011", OnesComplement.onesComplement("1100")); assertEquals("1001", OnesComplement.onesComplement("0110")); } @ParameterizedTest @NullAndEmptySource public void testOnesComplementNullOrEmptyInputThrowsException(String input) { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> OnesComplement.onesComplement(input)); assertEquals("Input must be a non-empty binary string.", exception.getMessage()); } @Test public void testOnesComplementInvalidCharactersThrowsException() { Exception exception = assertThrows(IllegalArgumentException.class, () -> OnesComplement.onesComplement("10a1")); assertTrue(exception.getMessage().startsWith("Input must contain only '0' and '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/bitmanipulation/BitSwapTest.java
src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java
package com.thealgorithms.bitmanipulation; 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 BitSwapTest { @ParameterizedTest(name = "Additional cases: data={0}, posA={1}, posB={2} -> expected={3}") @MethodSource("provideAdditionalCases") void testAdditionalCases(int data, int posA, int posB, int expected) { assertEquals(expected, BitSwap.bitSwap(data, posA, posB)); } @ParameterizedTest(name = "Swap different bits: data={0}, posA={1}, posB={2} -> expected={3}") @MethodSource("provideDifferentBitsCases") void swapDifferentBits(int data, int posA, int posB, int expected) { assertEquals(expected, BitSwap.bitSwap(data, posA, posB)); } @ParameterizedTest(name = "Swap same bits: data={0}, posA={1}, posB={2} should not change") @MethodSource("provideSameBitsCases") void swapSameBits(int data, int posA, int posB) { assertEquals(data, BitSwap.bitSwap(data, posA, posB)); } @ParameterizedTest(name = "Edge cases: data={0}, posA={1}, posB={2} -> expected={3}") @MethodSource("provideEdgeCases") void testEdgeCases(int data, int posA, int posB, int expected) { assertEquals(expected, BitSwap.bitSwap(data, posA, posB)); } @ParameterizedTest(name = "Invalid positions: data={0}, posA={1}, posB={2} should throw") @MethodSource("provideInvalidPositions") void invalidPositionThrowsException(int data, int posA, int posB) { assertThrows(IllegalArgumentException.class, () -> BitSwap.bitSwap(data, posA, posB)); } static Stream<Arguments> provideAdditionalCases() { return Stream.of(Arguments.of(3, 0, 1, 3), Arguments.of(6, 0, 1, 5), Arguments.of(7, 1, 1, 7)); } static Stream<Arguments> provideDifferentBitsCases() { return Stream.of(Arguments.of(0b01, 0, 1, 0b10)); } static Stream<Arguments> provideSameBitsCases() { return Stream.of(Arguments.of(0b111, 0, 2), Arguments.of(0b0, 1, 3), Arguments.of(0b1010, 1, 3), Arguments.of(-1, 5, 5)); } static Stream<Arguments> provideEdgeCases() { return Stream.of(Arguments.of(Integer.MIN_VALUE, 31, 0, 1), Arguments.of(0, 0, 31, 0)); } static Stream<Arguments> provideInvalidPositions() { return Stream.of(Arguments.of(0, -1, 0), Arguments.of(0, 0, 32), Arguments.of(0, -5, 33), Arguments.of(0, Integer.MIN_VALUE, Integer.MAX_VALUE)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java
src/test/java/com/thealgorithms/bitmanipulation/GenerateSubsetsTest.java
package com.thealgorithms.bitmanipulation; 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; class GenerateSubsetsTest { @Test void testGenerateSubsetsWithTwoElements() { int[] set = {1, 2}; List<List<Integer>> expected = new ArrayList<>(); expected.add(new ArrayList<>()); expected.add(singletonList(1)); expected.add(singletonList(2)); expected.add(Arrays.asList(1, 2)); List<List<Integer>> result = GenerateSubsets.generateSubsets(set); assertEquals(expected, result); } @Test void testGenerateSubsetsWithOneElement() { int[] set = {3}; List<List<Integer>> expected = new ArrayList<>(); expected.add(new ArrayList<>()); expected.add(singletonList(3)); List<List<Integer>> result = GenerateSubsets.generateSubsets(set); assertEquals(expected, result); } @Test void testGenerateSubsetsWithThreeElements() { int[] set = {4, 5, 6}; List<List<Integer>> expected = new ArrayList<>(); expected.add(new ArrayList<>()); expected.add(singletonList(4)); expected.add(singletonList(5)); expected.add(Arrays.asList(4, 5)); expected.add(singletonList(6)); expected.add(Arrays.asList(4, 6)); expected.add(Arrays.asList(5, 6)); expected.add(Arrays.asList(4, 5, 6)); List<List<Integer>> result = GenerateSubsets.generateSubsets(set); 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/bitmanipulation/SingleBitOperationsTest.java
src/test/java/com/thealgorithms/bitmanipulation/SingleBitOperationsTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class SingleBitOperationsTest { @ParameterizedTest @MethodSource("provideFlipBitTestCases") void testFlipBit(int input, int bit, int expected) { assertEquals(expected, SingleBitOperations.flipBit(input, bit)); } private static Stream<Arguments> provideFlipBitTestCases() { return Stream.of(Arguments.of(3, 1, 1), // Binary: 11 -> 01 Arguments.of(3, 3, 11) // Binary: 11 -> 1011 ); } @ParameterizedTest @MethodSource("provideSetBitTestCases") void testSetBit(int input, int bit, int expected) { assertEquals(expected, SingleBitOperations.setBit(input, bit)); } private static Stream<Arguments> provideSetBitTestCases() { return Stream.of(Arguments.of(4, 0, 5), // 100 -> 101 Arguments.of(4, 2, 4), // 100 -> 100 (bit already set) Arguments.of(0, 1, 2), // 00 -> 10 Arguments.of(10, 2, 14) // 1010 -> 1110 ); } @ParameterizedTest @MethodSource("provideClearBitTestCases") void testClearBit(int input, int bit, int expected) { assertEquals(expected, SingleBitOperations.clearBit(input, bit)); } private static Stream<Arguments> provideClearBitTestCases() { return Stream.of(Arguments.of(7, 1, 5), // 111 -> 101 Arguments.of(5, 1, 5) // 101 -> 101 (bit already cleared) ); } @ParameterizedTest @MethodSource("provideGetBitTestCases") void testGetBit(int input, int bit, int expected) { assertEquals(expected, SingleBitOperations.getBit(input, bit)); } private static Stream<Arguments> provideGetBitTestCases() { return Stream.of(Arguments.of(6, 0, 0), // 110 -> Bit 0: 0 Arguments.of(7, 1, 1) // 111 -> Bit 1: 1 ); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/FirstDifferentBitTest.java
src/test/java/com/thealgorithms/bitmanipulation/FirstDifferentBitTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class FirstDifferentBitTest { @ParameterizedTest @CsvSource({"10, 8, 1", "7, 5, 1", "15, 14, 0", "1, 2, 0"}) void testFirstDifferentBit(int x, int y, int expected) { assertEquals(expected, FirstDifferentBit.firstDifferentBit(x, y)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheckTest.java
src/test/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheckTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class BinaryPalindromeCheckTest { @Test public void testIsBinaryPalindrome() { assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(9)); // 1001 is a palindrome assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(10)); // 1010 is not a palindrome assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(0)); // 0 is a palindrome assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(1)); // 1 is a palindrome assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(12)); // 1100 is not a palindrome } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java
src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test case for Index Of Right Most SetBit * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ class IndexOfRightMostSetBitTest { @Test void testIndexOfRightMostSetBit() { assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(40)); assertEquals(-1, IndexOfRightMostSetBit.indexOfRightMostSetBit(0)); assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(-40)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java
src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; 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 case for IsPowerTwo class * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public class IsPowerTwoTest { @ParameterizedTest @MethodSource("provideNumbersForPowerTwo") public void testIsPowerTwo(int number, boolean expected) { if (expected) { assertTrue(IsPowerTwo.isPowerTwo(number)); } else { assertFalse(IsPowerTwo.isPowerTwo(number)); } } private static Stream<Arguments> provideNumbersForPowerTwo() { return Stream.of(Arguments.of(1, Boolean.TRUE), // 2^0 Arguments.of(2, Boolean.TRUE), // 2^1 Arguments.of(4, Boolean.TRUE), // 2^2 Arguments.of(8, Boolean.TRUE), // 2^3 Arguments.of(16, Boolean.TRUE), // 2^4 Arguments.of(32, Boolean.TRUE), // 2^5 Arguments.of(64, Boolean.TRUE), // 2^6 Arguments.of(128, Boolean.TRUE), // 2^7 Arguments.of(256, Boolean.TRUE), // 2^8 Arguments.of(1024, Boolean.TRUE), // 2^10 Arguments.of(0, Boolean.FALSE), // 0 is not a power of two Arguments.of(-1, Boolean.FALSE), // Negative number Arguments.of(-2, Boolean.FALSE), // Negative number Arguments.of(-4, Boolean.FALSE), // Negative number Arguments.of(3, Boolean.FALSE), // 3 is not a power of two Arguments.of(5, Boolean.FALSE), // 5 is not a power of two Arguments.of(6, Boolean.FALSE), // 6 is not a power of two Arguments.of(15, Boolean.FALSE), // 15 is not a power of two Arguments.of(1000, Boolean.FALSE), // 1000 is not a power of two Arguments.of(1023, Boolean.FALSE) // 1023 is not a power of two ); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java
src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Test case for Non Repeating Number Finder * This test class validates the functionality of the * NonRepeatingNumberFinder by checking various scenarios. * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ class NonRepeatingNumberFinderTest { @ParameterizedTest @MethodSource("testCases") void testNonRepeatingNumberFinder(int[] arr, int expected) { assertEquals(expected, NonRepeatingNumberFinder.findNonRepeatingNumber(arr)); } private static Arguments[] testCases() { return new Arguments[] { Arguments.of(new int[] {1, 2, 1, 2, 6}, 6), Arguments.of(new int[] {1, 2, 1, 2}, 0), // All numbers repeat Arguments.of(new int[] {12}, 12), // Single non-repeating number Arguments.of(new int[] {3, 5, 3, 4, 4}, 5), // More complex case Arguments.of(new int[] {7, 8, 7, 9, 8, 10, 10}, 9), // Non-repeating in the middle Arguments.of(new int[] {0, -1, 0, -1, 2}, 2), // Testing with negative numbers Arguments.of(new int[] {Integer.MAX_VALUE, 1, 1}, Integer.MAX_VALUE), // Edge case with max int Arguments.of(new int[] {2, 2, 3, 3, 4, 5, 4}, 5), // Mixed duplicates Arguments.of(new int[] {}, 0) // Edge case: empty array (should be handled as per design) }; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java
src/test/java/com/thealgorithms/bitmanipulation/SingleElementTest.java
package com.thealgorithms.bitmanipulation; 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 final class SingleElementTest { /** * Parameterized test to find the single non-duplicate element * in the given arrays. * * @param arr the input array where every element appears twice except one * @param expected the expected single element result */ @ParameterizedTest @MethodSource("provideTestCases") void testFindSingleElement(int[] arr, int expected) { assertEquals(expected, SingleElement.findSingleElement(arr)); } /** * Provides test cases for the parameterized test. * * @return Stream of arguments consisting of arrays and expected results */ private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(new int[] {1, 1, 2, 2, 4, 4, 3}, 3), Arguments.of(new int[] {1, 2, 2, 3, 3}, 1), Arguments.of(new int[] {10}, 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/bitmanipulation/BitRotateTest.java
src/test/java/com/thealgorithms/bitmanipulation/BitRotateTest.java
package com.thealgorithms.bitmanipulation; 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 static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Unit tests for BitRotate class covering typical, boundary, and edge cases. * Tests verify correct behavior for 32-bit circular bit rotations. * * @author Yajunesh */ public class BitRotateTest { // ===== rotateLeft Tests ===== @Test public void testRotateLeftBasic() { // Basic left rotation assertEquals(0b00000000_00000000_00000000_00000010, BitRotate.rotateLeft(1, 1)); assertEquals(0b00000000_00000000_00000000_00000100, BitRotate.rotateLeft(1, 2)); assertEquals(0b00000000_00000000_00000000_00001000, BitRotate.rotateLeft(1, 3)); } @Test public void testRotateLeftWithCarry() { // Test bits carrying from left to right // Binary: 10000000_00000000_00000000_00000001 int value = 0x80000001; // After left rotate by 1: 00000000_00000000_00000000_00000011 assertEquals(3, BitRotate.rotateLeft(value, 1)); // Binary: 11000000_00000000_00000000_00000000 value = 0xC0000000; // After left rotate by 1: 10000000_00000000_00000000_00000001 assertEquals(0x80000001, BitRotate.rotateLeft(value, 1)); } @Test public void testRotateLeftShift32() { // Shift of 32 should be same as shift of 0 (modulo behavior) int value = 0x12345678; assertEquals(value, BitRotate.rotateLeft(value, 32)); assertEquals(value, BitRotate.rotateLeft(value, 64)); assertEquals(value, BitRotate.rotateLeft(value, 96)); } @Test public void testRotateLeftShiftNormalization() { // Test that shifts > 32 are properly normalized int value = 1; assertEquals(BitRotate.rotateLeft(value, 1), BitRotate.rotateLeft(value, 33)); assertEquals(BitRotate.rotateLeft(value, 5), BitRotate.rotateLeft(value, 37)); } @Test public void testRotateLeftZeroShift() { // Zero shift should return original value int value = 0xABCD1234; assertEquals(value, BitRotate.rotateLeft(value, 0)); } // ===== rotateRight Tests ===== @Test public void testRotateRightBasic() { // Basic right rotation assertEquals(0b10000000_00000000_00000000_00000000, BitRotate.rotateRight(1, 1)); assertEquals(0b01000000_00000000_00000000_00000000, BitRotate.rotateRight(1, 2)); assertEquals(0b00100000_00000000_00000000_00000000, BitRotate.rotateRight(1, 3)); } @Test public void testRotateRightWithCarry() { // Test bits carrying from right to left // Binary: 00000000_00000000_00000000_00000011 int value = 3; // After right rotate by 1: 10000000_00000000_00000000_00000001 assertEquals(0x80000001, BitRotate.rotateRight(value, 1)); // Binary: 00000000_00000000_00000000_00000001 value = 1; // After right rotate by 1: 10000000_00000000_00000000_00000000 assertEquals(0x80000000, BitRotate.rotateRight(value, 1)); } @Test public void testRotateRightShift32() { // Shift of 32 should be same as shift of 0 (modulo behavior) int value = 0x9ABCDEF0; assertEquals(value, BitRotate.rotateRight(value, 32)); assertEquals(value, BitRotate.rotateRight(value, 64)); assertEquals(value, BitRotate.rotateRight(value, 96)); } @Test public void testRotateRightShiftNormalization() { // Test that shifts > 32 are properly normalized int value = 1; assertEquals(BitRotate.rotateRight(value, 1), BitRotate.rotateRight(value, 33)); assertEquals(BitRotate.rotateRight(value, 7), BitRotate.rotateRight(value, 39)); } @Test public void testRotateRightZeroShift() { // Zero shift should return original value int value = 0xDEADBEEF; assertEquals(value, BitRotate.rotateRight(value, 0)); } // ===== Edge Case Tests ===== @Test public void testRotateLeftMaxValue() { // Test with maximum integer value int value = Integer.MAX_VALUE; // 0x7FFFFFFF int rotated = BitRotate.rotateLeft(value, 1); // MAX_VALUE << 1 should become 0xFFFFFFFE, but with rotation it becomes different assertEquals(0xFFFFFFFE, rotated); } @Test public void testRotateRightMinValue() { // Test with minimum integer value (treated as unsigned) int value = Integer.MIN_VALUE; // 0x80000000 int rotated = BitRotate.rotateRight(value, 1); // MIN_VALUE >>> 1 should become 0x40000000, but with rotation from left assertEquals(0x40000000, rotated); } @Test public void testRotateAllOnes() { // Test with all bits set int value = 0xFFFFFFFF; // All ones assertEquals(value, BitRotate.rotateLeft(value, 13)); assertEquals(value, BitRotate.rotateRight(value, 27)); } @Test public void testRotateAllZeros() { // Test with all bits zero int value = 0x00000000; assertEquals(value, BitRotate.rotateLeft(value, 15)); assertEquals(value, BitRotate.rotateRight(value, 19)); } // ===== Exception Tests ===== @Test public void testRotateLeftNegativeShift() { // Negative shifts should throw IllegalArgumentException Exception exception = assertThrows(IllegalArgumentException.class, () -> BitRotate.rotateLeft(42, -1)); assertTrue(exception.getMessage().contains("negative")); } @Test public void testRotateRightNegativeShift() { // Negative shifts should throw IllegalArgumentException Exception exception = assertThrows(IllegalArgumentException.class, () -> BitRotate.rotateRight(42, -5)); assertTrue(exception.getMessage().contains("negative")); } // ===== Complementary Operations Test ===== @Test public void testRotateLeftRightComposition() { // Rotating left then right by same amount should return original value int original = 0x12345678; int shift = 7; int leftRotated = BitRotate.rotateLeft(original, shift); int restored = BitRotate.rotateRight(leftRotated, shift); assertEquals(original, restored); } @Test public void testRotateRightLeftComposition() { // Rotating right then left by same amount should return original value int original = 0x9ABCDEF0; int shift = 13; int rightRotated = BitRotate.rotateRight(original, shift); int restored = BitRotate.rotateLeft(rightRotated, shift); assertEquals(original, restored); } @Test public void testRotateLeft31IsSameAsRotateRight1() { // Rotating left by 31 should be same as rotating right by 1 int value = 0x55555555; assertEquals(BitRotate.rotateLeft(value, 31), BitRotate.rotateRight(value, 1)); } @Test public void testTraversals() { // Test that methods don't throw exceptions assertDoesNotThrow(() -> BitRotate.rotateLeft(1, 1)); assertDoesNotThrow(() -> BitRotate.rotateRight(1, 1)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/BitwiseGCDTest.java
src/test/java/com/thealgorithms/bitmanipulation/BitwiseGCDTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigInteger; import org.junit.jupiter.api.Test; public class BitwiseGCDTest { @Test public void testGcdBasic() { assertEquals(6L, BitwiseGCD.gcd(48L, 18L)); } @Test public void testGcdZeroAndNonZero() { assertEquals(5L, BitwiseGCD.gcd(0L, 5L)); assertEquals(5L, BitwiseGCD.gcd(5L, 0L)); } @Test public void testGcdBothZero() { assertEquals(0L, BitwiseGCD.gcd(0L, 0L)); } @Test public void testGcdNegativeInputs() { assertEquals(6L, BitwiseGCD.gcd(-48L, 18L)); assertEquals(6L, BitwiseGCD.gcd(48L, -18L)); assertEquals(6L, BitwiseGCD.gcd(-48L, -18L)); } @Test public void testGcdIntOverload() { assertEquals(6, BitwiseGCD.gcd(48, 18)); } @Test public void testGcdArray() { long[] values = {48L, 18L, 6L}; assertEquals(6L, BitwiseGCD.gcd(values)); } @Test public void testGcdEmptyArray() { long[] empty = {}; assertEquals(0L, BitwiseGCD.gcd(empty)); } @Test public void testGcdCoprime() { assertEquals(1L, BitwiseGCD.gcd(17L, 13L)); } @Test public void testGcdPowersOfTwo() { assertEquals(1024L, BitwiseGCD.gcd(1L << 20, 1L << 10)); } @Test public void testGcdLargeNumbers() { assertEquals(6L, BitwiseGCD.gcd(270L, 192L)); } @Test public void testGcdEarlyExitArray() { long[] manyCoprimes = {7L, 11L, 13L, 17L, 19L, 23L, 29L}; assertEquals(1L, BitwiseGCD.gcd(manyCoprimes)); } @Test public void testGcdSameNumbers() { assertEquals(42L, BitwiseGCD.gcd(42L, 42L)); } @Test public void testGcdLongMinValueBigInteger() { // gcd(Long.MIN_VALUE, 0) = |Long.MIN_VALUE| = 2^63; must use BigInteger to represent it BigInteger expected = BigInteger.ONE.shiftLeft(63); // 2^63 assertEquals(expected, BitwiseGCD.gcdBig(Long.MIN_VALUE, 0L)); } @Test public void testGcdLongMinValueLongOverloadThrows() { // The long overload cannot return 2^63 as a positive signed long, so it must throw assertThrows(ArithmeticException.class, () -> BitwiseGCD.gcd(Long.MIN_VALUE, 0L)); } @Test public void testGcdWithLongMinAndOther() { // gcd(Long.MIN_VALUE, 2^10) should be 2^10 long p = 1L << 10; BigInteger expected = BigInteger.valueOf(p); assertEquals(expected, BitwiseGCD.gcdBig(Long.MIN_VALUE, p)); } @Test public void testGcdWithBothLongMin() { // gcd(Long.MIN_VALUE, Long.MIN_VALUE) = 2^63 BigInteger expected = BigInteger.ONE.shiftLeft(63); assertEquals(expected, BitwiseGCD.gcdBig(Long.MIN_VALUE, Long.MIN_VALUE)); } @Test public void testGcdEdgeCasesMixed() { assertEquals(1L, BitwiseGCD.gcd(1L, Long.MAX_VALUE)); assertEquals(1L, BitwiseGCD.gcd(Long.MAX_VALUE, 1L)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java
src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class CountSetBitsTest { @Test void testCountSetBitsZero() { assertEquals(0, CountSetBits.countSetBits(0)); } @Test void testCountSetBitsOne() { assertEquals(1, CountSetBits.countSetBits(1)); } @Test void testCountSetBitsSmallNumber() { assertEquals(4, CountSetBits.countSetBits(3)); // 1(1) + 10(1) + 11(2) = 4 } @Test void testCountSetBitsFive() { assertEquals(7, CountSetBits.countSetBits(5)); // 1 + 1 + 2 + 1 + 2 = 7 } @Test void testCountSetBitsTen() { assertEquals(17, CountSetBits.countSetBits(10)); } @Test void testCountSetBitsLargeNumber() { assertEquals(42, CountSetBits.countSetBits(20)); // Changed from 93 to 42 } @Test void testCountSetBitsPowerOfTwo() { assertEquals(13, CountSetBits.countSetBits(8)); // Changed from 9 to 13 } @Test void testCountSetBitsNegativeInput() { assertThrows(IllegalArgumentException.class, () -> CountSetBits.countSetBits(-1)); } @Test void testNaiveApproachMatchesOptimized() { for (int i = 0; i <= 100; i++) { assertEquals(CountSetBits.countSetBitsNaive(i), CountSetBits.countSetBits(i), "Mismatch at n = " + i); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java
src/test/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGatesTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.ANDGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.BooleanGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.NANDGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.NORGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.NOTGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.ORGate; import com.thealgorithms.bitmanipulation.BooleanAlgebraGates.XORGate; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; class BooleanAlgebraGatesTest { @ParameterizedTest(name = "ANDGate Test Case {index}: inputs={0} -> expected={1}") @MethodSource("provideAndGateTestCases") void testANDGate(List<Boolean> inputs, boolean expected) { BooleanGate gate = new ANDGate(); assertEquals(expected, gate.evaluate(inputs)); } @ParameterizedTest(name = "ORGate Test Case {index}: inputs={0} -> expected={1}") @MethodSource("provideOrGateTestCases") void testORGate(List<Boolean> inputs, boolean expected) { BooleanGate gate = new ORGate(); assertEquals(expected, gate.evaluate(inputs)); } @ParameterizedTest(name = "NOTGate Test Case {index}: input={0} -> expected={1}") @CsvSource({"true, false", "false, true"}) void testNOTGate(boolean input, boolean expected) { NOTGate gate = new NOTGate(); assertEquals(expected, gate.evaluate(input)); } @ParameterizedTest(name = "XORGate Test Case {index}: inputs={0} -> expected={1}") @MethodSource("provideXorGateTestCases") void testXORGate(List<Boolean> inputs, boolean expected) { BooleanGate gate = new XORGate(); assertEquals(expected, gate.evaluate(inputs)); } @ParameterizedTest(name = "NANDGate Test Case {index}: inputs={0} -> expected={1}") @MethodSource("provideNandGateTestCases") void testNANDGate(List<Boolean> inputs, boolean expected) { BooleanGate gate = new NANDGate(); assertEquals(expected, gate.evaluate(inputs)); } @ParameterizedTest(name = "NORGate Test Case {index}: inputs={0} -> expected={1}") @MethodSource("provideNorGateTestCases") void testNORGate(List<Boolean> inputs, boolean expected) { BooleanGate gate = new NORGate(); assertEquals(expected, gate.evaluate(inputs)); } // Helper methods to provide test data for each gate static Stream<Object[]> provideAndGateTestCases() { return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, new Object[] {Collections.emptyList(), Boolean.TRUE} // AND over no inputs is true ); } static Stream<Object[]> provideOrGateTestCases() { return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.TRUE}, new Object[] {Collections.emptyList(), Boolean.FALSE} // OR over no inputs is false ); } static Stream<Object[]> provideXorGateTestCases() { return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // XOR over odd true new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // XOR over single true new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE), Boolean.FALSE}, // XOR over all false new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE} // XOR over even true ); } static Stream<Object[]> provideNandGateTestCases() { return Stream.of(new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NAND of all true is false new Object[] {Arrays.asList(Boolean.TRUE, Boolean.FALSE), Boolean.TRUE}, // NAND with one false is true new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NAND of all false is true new Object[] {Collections.emptyList(), Boolean.FALSE} // NAND over no inputs is false (negation of AND) ); } static Stream<Object[]> provideNorGateTestCases() { return Stream.of(new Object[] {Arrays.asList(Boolean.FALSE, Boolean.FALSE), Boolean.TRUE}, // NOR of all false is true new Object[] {Arrays.asList(Boolean.FALSE, Boolean.TRUE), Boolean.FALSE}, // NOR with one true is false new Object[] {Arrays.asList(Boolean.TRUE, Boolean.TRUE), Boolean.FALSE}, // NOR of all true is false new Object[] {Collections.emptyList(), Boolean.TRUE} // NOR over no inputs is true (negation of OR) ); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/IsEvenTest.java
src/test/java/com/thealgorithms/bitmanipulation/IsEvenTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class IsEvenTest { @Test void testIsEven() { assertTrue(IsEven.isEven(0)); assertTrue(IsEven.isEven(2)); assertTrue(IsEven.isEven(-12)); assertFalse(IsEven.isEven(21)); assertFalse(IsEven.isEven(-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/bitmanipulation/CountBitsFlipTest.java
src/test/java/com/thealgorithms/bitmanipulation/CountBitsFlipTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Random; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests for CountBitsFlip. * Covers: * - simple examples * - zeros and identical values * - negative numbers and two's complement edge cases * - Long.MIN_VALUE / Long.MAX_VALUE * - randomized consistency checks between two implementations */ @DisplayName("CountBitsFlip Tests") class CountBitsFlipTest { @Test @DisplayName("Example: A=10, B=20 => 4 bits") void exampleTenTwenty() { long a = 10L; long b = 20L; long expected = 4L; assertEquals(expected, CountBitsFlip.countBitsFlip(a, b), "Brian Kernighan implementation should return 4"); assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b), "Long.bitCount implementation should return 4"); } @Test @DisplayName("Identical values => 0 bits") void identicalValues() { long a = 123456789L; long b = 123456789L; long expected = 0L; assertEquals(expected, CountBitsFlip.countBitsFlip(a, b)); assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b)); } @Test @DisplayName("Both zeros => 0 bits") void bothZeros() { assertEquals(0L, CountBitsFlip.countBitsFlip(0L, 0L)); assertEquals(0L, CountBitsFlip.countBitsFlipAlternative(0L, 0L)); } @Test @DisplayName("Small example: A=15 (1111), B=8 (1000) => 3 bits") void smallExample() { long a = 15L; // 1111 long b = 8L; // 1000 long expected = 3L; // differs in three low bits assertEquals(expected, CountBitsFlip.countBitsFlip(a, b)); assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b)); } @Test @DisplayName("Negative values: -1 vs 0 => 64 bits (two's complement all ones)") void negativeVsZero() { long a = -1L; long b = 0L; long expected = 64L; // all 64 bits differ assertEquals(expected, CountBitsFlip.countBitsFlip(a, b)); assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b)); } @Test @DisplayName("Long.MIN_VALUE vs Long.MAX_VALUE => 64 bits") void minMaxLongs() { long a = Long.MIN_VALUE; long b = Long.MAX_VALUE; long expected = 64L; // MAX ^ MIN yields all ones on 64-bit long assertEquals(expected, CountBitsFlip.countBitsFlip(a, b)); assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b)); } @Test @DisplayName("Randomized consistency: both implementations agree across many pairs") void randomizedConsistency() { final int iterations = 1000; final Random rnd = new Random(12345L); // deterministic seed for reproducibility for (int i = 0; i < iterations; i++) { long a = rnd.nextLong(); long b = rnd.nextLong(); long res1 = CountBitsFlip.countBitsFlip(a, b); long res2 = CountBitsFlip.countBitsFlipAlternative(a, b); assertEquals(res2, res1, () -> String.format("Mismatch for a=%d, b=%d: impl1=%d, impl2=%d", a, b, res1, res2)); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java
src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; 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; /** * Parameterized tests for NumbersDifferentSigns class, which checks * if two integers have different signs using bitwise XOR. * * @author Bama Charan Chhandogi */ class NumbersDifferentSignsTest { @ParameterizedTest @MethodSource("provideTestCases") void testDifferentSigns(int num1, int num2, boolean expected) { if (expected) { assertTrue(NumbersDifferentSigns.differentSigns(num1, num2)); } else { assertFalse(NumbersDifferentSigns.differentSigns(num1, num2)); } } private static Stream<Arguments> provideTestCases() { return Stream.of( // Different signs (positive and negative) Arguments.of(2, -1, Boolean.TRUE), Arguments.of(-3, 7, Boolean.TRUE), // Same signs (both positive) Arguments.of(10, 20, Boolean.FALSE), Arguments.of(0, 5, Boolean.FALSE), // 0 is considered non-negative // Same signs (both negative) Arguments.of(-5, -8, Boolean.FALSE), // Edge case: Large positive and negative values Arguments.of(Integer.MAX_VALUE, Integer.MIN_VALUE, Boolean.TRUE), // Edge case: Same number (positive and negative) Arguments.of(-42, -42, Boolean.FALSE), Arguments.of(42, 42, Boolean.FALSE)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java
src/test/java/com/thealgorithms/bitmanipulation/HighestSetBitTest.java
package com.thealgorithms.bitmanipulation; 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 org.junit.jupiter.api.Test; /** * Test case for Highest Set Bit * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ class HighestSetBitTest { @Test void testHighestSetBit() { assertFalse(HighestSetBit.findHighestSetBit(0).isPresent()); assertEquals(0, HighestSetBit.findHighestSetBit(1).get()); assertEquals(1, HighestSetBit.findHighestSetBit(2).get()); assertEquals(1, HighestSetBit.findHighestSetBit(3).get()); assertEquals(2, HighestSetBit.findHighestSetBit(4).get()); assertEquals(2, HighestSetBit.findHighestSetBit(5).get()); assertEquals(2, HighestSetBit.findHighestSetBit(7).get()); assertEquals(3, HighestSetBit.findHighestSetBit(8).get()); assertEquals(3, HighestSetBit.findHighestSetBit(9).get()); assertEquals(3, HighestSetBit.findHighestSetBit(15).get()); assertEquals(4, HighestSetBit.findHighestSetBit(16).get()); assertEquals(4, HighestSetBit.findHighestSetBit(17).get()); assertEquals(4, HighestSetBit.findHighestSetBit(31).get()); assertEquals(5, HighestSetBit.findHighestSetBit(32).get()); assertEquals(5, HighestSetBit.findHighestSetBit(33).get()); assertEquals(7, HighestSetBit.findHighestSetBit(255).get()); assertEquals(8, HighestSetBit.findHighestSetBit(256).get()); assertEquals(8, HighestSetBit.findHighestSetBit(511).get()); assertEquals(9, HighestSetBit.findHighestSetBit(512).get()); assertThrows(IllegalArgumentException.class, () -> HighestSetBit.findHighestSetBit(-37)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/ParityCheckTest.java
src/test/java/com/thealgorithms/bitmanipulation/ParityCheckTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class ParityCheckTest { @Test public void testIsEvenParity() { assertTrue(ParityCheck.checkParity(0)); // 0 -> 0 ones assertTrue(ParityCheck.checkParity(3)); // 11 -> 2 ones assertTrue(ParityCheck.checkParity(5)); // 101 -> 2 ones assertTrue(ParityCheck.checkParity(10)); // 1010 -> 2 ones assertTrue(ParityCheck.checkParity(15)); // 1111 -> 4 ones assertTrue(ParityCheck.checkParity(1023)); // 10 ones } @Test public void testIsOddParity() { assertFalse(ParityCheck.checkParity(1)); // 1 -> 1 one assertFalse(ParityCheck.checkParity(2)); // 10 -> 1 one assertFalse(ParityCheck.checkParity(7)); // 111 -> 3 ones assertFalse(ParityCheck.checkParity(8)); // 1000 -> 1 one assertFalse(ParityCheck.checkParity(11)); // 1011 -> 3 ones assertFalse(ParityCheck.checkParity(31)); // 11111 -> 5 ones } @Test public void testLargeNumbers() { assertTrue(ParityCheck.checkParity(0b10101010)); // 4 ones assertFalse(ParityCheck.checkParity(0b100000000)); // 1 one assertTrue(ParityCheck.checkParity(0xAAAAAAAA)); // Alternating bits, 16 ones } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java
src/test/java/com/thealgorithms/bitmanipulation/FindNthBitTest.java
package com.thealgorithms.bitmanipulation; 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 final class FindNthBitTest { /** * A parameterized test that checks the value of the Nth bit for different inputs. * * @param num the number whose Nth bit is being tested * @param n the bit position * @param expected the expected value of the Nth bit (0 or 1) */ @ParameterizedTest @MethodSource("provideTestCases") void findNthBitParameterizedTest(int num, int n, int expected) { assertEquals(expected, FindNthBit.findNthBit(num, n)); } /** * Provides the test cases as a stream of arguments for the parameterized test. * * @return a stream of test cases where each case consists of a number, the bit position, * and the expected result. */ private static Stream<Arguments> provideTestCases() { return Stream.of(Arguments.of(13, 2, 0), // binary: 1101, 2nd bit is 0 Arguments.of(13, 3, 1), // binary: 1101, 3rd bit is 1 Arguments.of(4, 2, 0), // binary: 100, 2nd bit is 0 Arguments.of(4, 3, 1), // binary: 100, 3rd bit is 1 Arguments.of(1, 1, 1) // binary: 1, 1st bit is 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/bitmanipulation/ReverseBitsTest.java
src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class ReverseBitsTest { @ParameterizedTest @MethodSource("provideTestCases") void testReverseBits(int input, int expected) { assertEquals(expected, ReverseBits.reverseBits(input)); } private static Stream<Arguments> provideTestCases() { return Stream.of( // Edge case: All bits are 0 Arguments.of(0, 0), // Edge case: All bits are 1 (Two’s complement representation of -1) Arguments.of(-1, -1), // Case with random number 43261596 Arguments.of(43261596, 964176192), // Case with maximum positive value for 32-bit integer Arguments.of(Integer.MAX_VALUE, -2), // Case with minimum value (all bits 1 except the sign bit) Arguments.of(Integer.MIN_VALUE, 1), // Case with a single bit set (2^0 = 1) Arguments.of(1, Integer.MIN_VALUE), // Case with alternating bits: 0b101010...10 (in binary) Arguments.of(0xAAAAAAAA, 0x55555555)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java
src/test/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimesTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class NumberAppearingOddTimesTest { /** * Parameterized test for findOddOccurrence method. Tests multiple * input arrays and their expected results. */ @ParameterizedTest @MethodSource("provideTestCases") void testFindOddOccurrence(int[] input, int expected) { assertEquals(expected, NumberAppearingOddTimes.findOddOccurrence(input)); } /** * Provides test cases for the parameterized test. * Each test case consists of an input array and the expected result. */ private static Stream<Arguments> provideTestCases() { return Stream.of( // Single element appearing odd times (basic case) Arguments.of(new int[] {5, 6, 7, 8, 6, 7, 5}, 8), // More complex case with multiple pairs Arguments.of(new int[] {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}, 5), // Case with only one element appearing once Arguments.of(new int[] {10, 10, 20, 20, 30}, 30), // Negative numbers with an odd occurrence Arguments.of(new int[] {-5, -5, -3, -3, -7, -7, -7}, -7), // All elements cancel out to 0 (even occurrences of all elements) Arguments.of(new int[] {1, 2, 1, 2}, 0), // Array with a single element (trivial case) Arguments.of(new int[] {42}, 42), // Large array with repeated patterns Arguments.of(new int[] {1, 1, 2, 2, 3, 3, 3, 4, 4}, 3)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java
src/test/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwoTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class ModuloPowerOfTwoTest { @ParameterizedTest @CsvSource({ "10, 3, 2", "15, 2, 3", "20, 4, 4", "7, 1, 1", "5, 1, 1", "36, 5, 4", }) void testModuloPowerOfTwo(int x, int n, int expected) { assertEquals(expected, ModuloPowerOfTwo.moduloPowerOfTwo(x, n)); } @ParameterizedTest @CsvSource({ "10, 0", "15, -2", "20, -4", "7, -1", "5, -1", }) void testNegativeExponent(int x, int n) { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ModuloPowerOfTwo.moduloPowerOfTwo(x, n)); assertEquals("The exponent must be positive", exception.getMessage()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java
src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class GrayCodeConversionTest { @Test public void testBinaryToGray() { assertEquals(7, GrayCodeConversion.binaryToGray(5)); // 101 -> 111 assertEquals(4, GrayCodeConversion.binaryToGray(7)); // 111 -> 100 assertEquals(1, GrayCodeConversion.binaryToGray(1)); // 001 -> 001 } @Test public void testGrayToBinary() { assertEquals(5, GrayCodeConversion.grayToBinary(7)); // 111 -> 101 assertEquals(4, GrayCodeConversion.grayToBinary(6)); // 110 -> 100 assertEquals(1, GrayCodeConversion.grayToBinary(1)); // 001 -> 001 } @Test public void testBinaryGrayCycle() { int binary = 9; // 1001 in binary int gray = GrayCodeConversion.binaryToGray(binary); assertEquals(binary, GrayCodeConversion.grayToBinary(gray)); // Should return to original binary } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java
src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test case for Lowest Set Bit * @author Prayas Kumar (https://github.com/prayas7102) */ public class LowestSetBitTest { @Test void testLowestSetBitWithPositiveNumber() { // Test with a general positive number assertEquals(2, LowestSetBit.isolateLowestSetBit(18)); // 18 in binary: 10010, lowest bit is 2 } @Test void testLowestSetBitWithZero() { // Test with zero (edge case, no set bits) assertEquals(0, LowestSetBit.isolateLowestSetBit(0)); // 0 has no set bits, result should be 0 } @Test void testLowestSetBitWithOne() { // Test with number 1 (lowest set bit is 1 itself) assertEquals(1, LowestSetBit.isolateLowestSetBit(1)); // 1 in binary: 0001, lowest bit is 1 } @Test void testLowestSetBitWithPowerOfTwo() { // Test with a power of two (only one set bit) assertEquals(16, LowestSetBit.isolateLowestSetBit(16)); // 16 in binary: 10000, lowest bit is 16 } @Test void testLowestSetBitWithAllBitsSet() { // Test with a number with multiple set bits (like 7) assertEquals(1, LowestSetBit.isolateLowestSetBit(7)); // 7 in binary: 111, lowest bit is 1 } @Test void testLowestSetBitWithNegativeNumber() { // Test with a negative number (-1 in two's complement has all bits set) assertEquals(1, LowestSetBit.isolateLowestSetBit(-1)); // -1 in two's complement is all 1s, lowest bit is 1 } @Test void testLowestSetBitWithLargeNumber() { // Test with a large number assertEquals(64, LowestSetBit.isolateLowestSetBit(448)); // 448 in binary: 111000000, lowest bit is 64 } @Test void testClearLowestSetBitFor18() { // n = 18 (binary: 10010), expected result = 16 (binary: 10000) assertEquals(16, LowestSetBit.clearLowestSetBit(18)); } @Test void testClearLowestSetBitFor10() { // n = 10 (binary: 1010), expected result = 8 (binary: 1000) assertEquals(8, LowestSetBit.clearLowestSetBit(10)); } @Test void testClearLowestSetBitFor7() { // n = 7 (binary: 0111), expected result = 6 (binary: 0110) assertEquals(6, LowestSetBit.clearLowestSetBit(7)); } @Test void testClearLowestSetBitFor0() { // n = 0 (binary: 0000), no set bits to clear, expected result = 0 assertEquals(0, LowestSetBit.clearLowestSetBit(0)); } @Test void testClearLowestSetBitForNegativeNumber() { // Test negative number to see how it behaves with two's complement // n = -1 (binary: all 1s in two's complement), expected result = -2 (clearing lowest set bit) assertEquals(-2, LowestSetBit.clearLowestSetBit(-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/bitmanipulation/HammingDistanceTest.java
src/test/java/com/thealgorithms/bitmanipulation/HammingDistanceTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class HammingDistanceTest { @Test public void testHammingDistance() { assertEquals(3, HammingDistance.hammingDistance(9, 14)); // 1001 vs 1110, Hamming distance is 3 assertEquals(0, HammingDistance.hammingDistance(10, 10)); // Same number, Hamming distance is 0 assertEquals(1, HammingDistance.hammingDistance(1, 0)); // 0001 vs 0000, Hamming distance is 1 assertEquals(2, HammingDistance.hammingDistance(4, 1)); // 100 vs 001, Hamming distance is 2 assertEquals(4, HammingDistance.hammingDistance(0, 15)); // 0000 vs 1111, Hamming distance is 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/bitmanipulation/NextHigherSameBitCountTest.java
src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class NextHigherSameBitCountTest { @ParameterizedTest @CsvSource({ "5, 6", // 101 -> 110 "7, 11", // 0111 -> 1011 "3, 5", // 011 -> 101 "12, 17", // 001100 -> 010001 "15, 23" // 01111 -> 10111 }) void testNextHigherSameBitCount(int input, int expected) { assertEquals(expected, NextHigherSameBitCount.nextHigherSameBitCount(input)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwoTest.java
src/test/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwoTest.java
package com.thealgorithms.bitmanipulation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class HigherLowerPowerOfTwoTest { @Test public void testNextHigherPowerOfTwo() { assertEquals(32, HigherLowerPowerOfTwo.nextHigherPowerOfTwo(19)); // next higher power of two is 32 assertEquals(1, HigherLowerPowerOfTwo.nextHigherPowerOfTwo(1)); // next higher power of two is 1 assertEquals(16, HigherLowerPowerOfTwo.nextHigherPowerOfTwo(15)); // next higher power of two is 16 assertEquals(8, HigherLowerPowerOfTwo.nextHigherPowerOfTwo(8)); // next higher power of two is 8 assertEquals(16, HigherLowerPowerOfTwo.nextHigherPowerOfTwo(9)); // next higher power of two is 16 } @Test public void testNextLowerPowerOfTwo() { assertEquals(16, HigherLowerPowerOfTwo.nextLowerPowerOfTwo(19)); // next lower power of two is 16 assertEquals(1, HigherLowerPowerOfTwo.nextLowerPowerOfTwo(1)); // next lower power of two is 1 assertEquals(8, HigherLowerPowerOfTwo.nextLowerPowerOfTwo(9)); // next lower power of two is 8 assertEquals(8, HigherLowerPowerOfTwo.nextLowerPowerOfTwo(15)); // next lower power of two is 8 assertEquals(8, HigherLowerPowerOfTwo.nextLowerPowerOfTwo(8)); // next lower power of two is 8 } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false