Merge branch 'eugenp:master' into master

This commit is contained in:
ciphx 2023-03-24 15:20:39 +05:30 committed by GitHub
commit 4abc9c1a39
3394 changed files with 88256 additions and 11716 deletions

14
.gitignore vendored
View File

@ -65,6 +65,11 @@ core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/ ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv jmeter/src/main/resources/*-JMeter.csv
jmeter/src/main/resources/*-Basic*.csv
jmeter/src/main/resources/*-JMeter*.csv
jmeter/src/main/resources/*ReportsDashboard*.csv
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
ninja/devDb.mv.db ninja/devDb.mv.db
**/node_modules/ **/node_modules/
@ -102,4 +107,11 @@ spring-boot-modules/spring-boot-properties-3/*.log
.sdkmanrc .sdkmanrc
# Localstack # Localstack
**/.localstack **/.localstack
#libraries-2
libraries-2/employee*
libraries-2/src/test/resources/crawler4j/**
#web-modules/ninja
devDb*.db

View File

@ -31,9 +31,11 @@ The projects are broadly divided into 3 lists: first, second and heavy.
Next, they are segregated further on the basis of the tests that we want to execute. Next, they are segregated further on the basis of the tests that we want to execute.
Additionally, there are 2 profiles dedicated for JDK9 and above builds. Additionally, there are 2 profiles dedicated for JDK9 and above builds - **which require JDK 17**.
Therefore, we have a total of 8 profiles: We also have a parents profile to build only parent modules.
Therefore, we have a total of 9 profiles:
| Profile | Includes | Type of test enabled | | Profile | Includes | Type of test enabled |
| -------------------------- | --------------------------- | -------------------- | | -------------------------- | --------------------------- | -------------------- |
@ -45,6 +47,7 @@ Therefore, we have a total of 8 profiles:
| integration-heavy | Heavy/long running projects | *IntegrationTest | | integration-heavy | Heavy/long running projects | *IntegrationTest |
| default-jdk9-and-above | JDK9 and above projects | *UnitTest | | default-jdk9-and-above | JDK9 and above projects | *UnitTest |
| integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest | | integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest |
| parents | Set of parent modules | None |
Building the project Building the project
==================== ====================
@ -71,6 +74,17 @@ Building a single module
==================== ====================
To build a specific module, run the command: `mvn clean install` in the module directory. To build a specific module, run the command: `mvn clean install` in the module directory.
It can happen that your module is part of a parent module e.g. `parent-boot-1`,`parent-spring-5` etc, then you will need to build the parent module first so that you can build your module.
We have created a `parents` profile that you can use to build just the parent modules, just run the profile as:
`mvn clean install -Pparents`
Building modules from the root of the repository
====================
To build specific modules from the root of the repository, run the command: `mvn clean install --pl asm,atomikos -Pdefault-first` in the root directory.
Here `asm` and `atomikos` are the modules that we want to build and `default-first` is the maven profile in which these modules are present.
Running a Spring Boot module Running a Spring Boot module
==================== ====================

View File

@ -36,6 +36,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<akka.http.version>10.0.11</akka.http.version> <akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version> <akka.stream.version>2.5.11</akka.stream.version>

View File

@ -43,7 +43,7 @@
</dependencyManagement> </dependencyManagement>
<properties> <properties>
<spring.version>4.3.4.RELEASE</spring.version> <spring.version>5.3.25</spring.version>
<akka.version>2.4.14</akka.version> <akka.version>2.4.14</akka.version>
</properties> </properties>

View File

@ -1,22 +1,24 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
public class AntColonyOptimizationLongRunningUnitTest { class AntColonyOptimizationLongRunningUnitTest {
@Test @Test
public void testGenerateRandomMatrix() { void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5); AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.generateRandomMatrix(5)); assertNotNull(antTSP.generateRandomMatrix(5));
} }
@Test @Test
public void testStartAntOptimization() { void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5); AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.solve()); assertNotNull(antTSP.solve());
} }
} }

View File

@ -1,16 +1,19 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmLongRunningUnitTest { class BinaryGeneticAlgorithmLongRunningUnitTest {
@Test @Test
public void testGA() { void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
} }
} }

View File

@ -1,15 +1,17 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
public class SimulatedAnnealingLongRunningUnitTest { class SimulatedAnnealingLongRunningUnitTest {
@Test @Test
public void testSimulateAnnealing() { void testSimulateAnnealing() {
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0); assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
} }
} }

View File

@ -1,23 +1,25 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.hillclimbing.HillClimbing; import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State; import com.baeldung.algorithms.hillclimbing.State;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmUnitTest { class HillClimbingAlgorithmUnitTest {
private Stack<String> initStack; private Stack<String> initStack;
private Stack<String> goalStack; private Stack<String> goalStack;
@Before @BeforeEach
public void initStacks() { public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" }; String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" }; String goalBlockArr[] = { "A", "B", "C", "D" };
@ -30,7 +32,7 @@ public class HillClimbingAlgorithmUnitTest {
} }
@Test @Test
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() { void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
HillClimbing hillClimbing = new HillClimbing(); HillClimbing hillClimbing = new HillClimbing();
List<State> path; List<State> path;
@ -46,7 +48,7 @@ public class HillClimbingAlgorithmUnitTest {
} }
@Test @Test
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing(); HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<>(); List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack); initList.add(initStack);

View File

@ -1,14 +1,16 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.automata.*; import com.baeldung.algorithms.automata.*;
import org.junit.Test;
import static org.junit.Assert.assertTrue; class RtFiniteStateMachineLongRunningUnitTest {
public final class RtFiniteStateMachineLongRunningUnitTest {
@Test @Test
public void acceptsSimplePair() { void acceptsSimplePair() {
String json = "{\"key\":\"value\"}"; String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) { for (int i = 0; i < json.length(); i++) {
@ -18,7 +20,7 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
} }
@Test @Test
public void acceptsMorePairs() { void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) { for (int i = 0; i < json.length(); i++) {
@ -27,13 +29,15 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
assertTrue(machine.canStop()); assertTrue(machine.canStop());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingColon() { void missingColon() {
String json = "{\"key\"\"value\"}"; String json = "{\"key\"\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); assertThrows(IllegalArgumentException.class, () -> {
for (int i = 0; i < json.length(); i++) { FiniteStateMachine machine = this.buildJsonStateMachine();
machine = machine.switchState(String.valueOf(json.charAt(i))); for (int i = 0; i < json.length(); i++) {
} machine = machine.switchState(String.valueOf(json.charAt(i)));
}
});
} }
/** /**

View File

@ -1,54 +1,54 @@
package com.baeldung.algorithms.kthlargest; package com.baeldung.algorithms.kthlargest;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class FindKthLargestUnitTest { class FindKthLargestUnitTest {
private FindKthLargest findKthLargest; private FindKthLargest findKthLargest;
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 }; private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
@Before @BeforeEach
public void setup() { public void setup() {
findKthLargest = new FindKthLargest(); findKthLargest = new FindKthLargest();
} }
@Test @Test
public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() { void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
int k = 3; int k = 3;
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8); assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
} }
@Test @Test
public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() { void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
int k = 3; int k = 3;
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8); assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
} }
@Test @Test
public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() { void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
int k = 3; int k = 3;
int kthLargest = arr.length - k; int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
} }
@Test @Test
public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() { void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
int k = 3; int k = 3;
int kthLargest = arr.length - k; int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
} }
@Test @Test
public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() { void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
int k = 3; int k = 3;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3); assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
} }
@Test @Test
public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() { void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
int k = 3; int k = 3;
int kthLargest = arr.length - k; int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);

View File

@ -1,23 +1,24 @@
package com.baeldung.algorithms.minimax; package com.baeldung.algorithms.minimax;
import org.junit.Before; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.*; import org.junit.jupiter.api.BeforeEach;
import com.baeldung.algorithms.minimax.MiniMax; import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.minimax.Tree;
public class MinimaxUnitTest { class MinimaxUnitTest {
private Tree gameTree; private Tree gameTree;
private MiniMax miniMax; private MiniMax miniMax;
@Before @BeforeEach
public void initMiniMaxUtility() { public void initMiniMaxUtility() {
miniMax = new MiniMax(); miniMax = new MiniMax();
} }
@Test @Test
public void givenMiniMax_whenConstructTree_thenNotNullTree() { void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree); assertNull(gameTree);
miniMax.constructTree(6); miniMax.constructTree(6);
gameTree = miniMax.getTree(); gameTree = miniMax.getTree();
@ -25,7 +26,7 @@ public class MinimaxUnitTest {
} }
@Test @Test
public void givenMiniMax_whenCheckWin_thenComputeOptimal() { void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6); miniMax.constructTree(6);
boolean result = miniMax.checkWin(); boolean result = miniMax.checkWin();
assertTrue(result); assertTrue(result);

View File

@ -1,6 +1,6 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import org.junit.Test;
import com.baeldung.algorithms.ga.dijkstra.Dijkstra; import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
import com.baeldung.algorithms.ga.dijkstra.Graph; import com.baeldung.algorithms.ga.dijkstra.Graph;
@ -11,7 +11,9 @@ import java.util.List;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class DijkstraAlgorithmLongRunningUnitTest { import org.junit.jupiter.api.Test;
class DijkstraAlgorithmLongRunningUnitTest {
@Test @Test
public void whenSPPSolved_thenCorrect() { public void whenSPPSolved_thenCorrect() {

View File

@ -1,5 +1,6 @@
package com.baeldung.algorithms.astar.underground; package com.baeldung.algorithms.astar.underground;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap; import java.util.HashMap;
@ -10,22 +11,22 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.astar.Graph; import com.baeldung.algorithms.astar.Graph;
import com.baeldung.algorithms.astar.RouteFinder; import com.baeldung.algorithms.astar.RouteFinder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
@Slf4j @Slf4j
public class RouteFinderIntegrationTest { class RouteFinderIntegrationTest {
private Graph<Station> underground; private Graph<Station> underground;
private RouteFinder<Station> routeFinder; private RouteFinder<Station> routeFinder;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
Set<Station> stations = new HashSet<>(); Set<Station> stations = new HashSet<>();
Map<String, Set<String>> connections = new HashMap<>(); Map<String, Set<String>> connections = new HashMap<>();
@ -641,7 +642,7 @@ public class RouteFinderIntegrationTest {
} }
@Test @Test
public void findRoute() { void findRoute() {
List<Station> route = routeFinder.findRoute(underground.getNode("74"), underground.getNode("7")); List<Station> route = routeFinder.findRoute(underground.getNode("74"), underground.getNode("7"));
assertThat(route).size().isPositive(); assertThat(route).size().isPositive();

View File

@ -1,21 +0,0 @@
package com.baeldung.algorithms.editdistance;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
public class EditDistanceDataProvider {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ "", "", 0 },
{ "ago", "", 3 },
{ "", "do", 2 },
{ "abc", "adc", 1 },
{ "peek", "pesek", 1 },
{ "sunday", "saturday", 3 }
});
}
}

View File

@ -1,32 +1,39 @@
package com.baeldung.algorithms.editdistance; package com.baeldung.algorithms.editdistance;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(Parameterized.class) import java.util.stream.Stream;
public class EditDistanceUnitTest extends EditDistanceDataProvider {
private String x;
private String y;
private int result;
public EditDistanceUnitTest(String a, String b, int res) { import org.junit.jupiter.params.ParameterizedTest;
super(); import org.junit.jupiter.params.provider.Arguments;
x = a;
y = b;
result = res;
}
@Test import org.junit.jupiter.params.provider.MethodSource;
public void testEditDistance_RecursiveImplementation() {
class EditDistanceUnitTest {
@ParameterizedTest
@MethodSource("provideArguments")
void testEditDistance_RecursiveImplementation(String x, String y, int result) {
assertEquals(result, EditDistanceRecursive.calculate(x, y)); assertEquals(result, EditDistanceRecursive.calculate(x, y));
} }
@Test @ParameterizedTest
public void testEditDistance_givenDynamicProgrammingImplementation() { @MethodSource("provideArguments")
void testEditDistance_givenDynamicProgrammingImplementation(String x, String y, int result) {
assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
} }
static Stream<? extends Arguments> provideArguments() {
return Stream.of(new Object[][] {
{ "", "", 0 },
{ "ago", "", 3 },
{ "", "do", 2 },
{ "abc", "adc", 1 },
{ "peek", "pesek", 1 },
{ "sunday", "saturday", 3 }
}).map(Arguments::of);
}
} }

View File

@ -1,23 +1,16 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import org.junit.jupiter.params.ParameterizedTest;
public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { import org.junit.jupiter.params.provider.MethodSource;
boolean cycleExists;
Node<Integer> head;
public CycleDetectionBruteForceUnitTest(Node<Integer> head, boolean cycleExists) { class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_detectLoop() { @ParameterizedTest
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); @MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
} }
} }

View File

@ -1,23 +1,16 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import static org.junit.jupiter.api.Assertions.assertEquals;
public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByFastAndSlowIteratorsUnitTest(Node<Integer> head, boolean cycleExists) { import org.junit.jupiter.params.ParameterizedTest;
super(); import org.junit.jupiter.params.provider.MethodSource;
this.cycleExists = cycleExists;
this.head = head;
}
@Test class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); @ParameterizedTest
@MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
} }
} }

View File

@ -1,23 +1,17 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import static org.junit.jupiter.api.Assertions.assertEquals;
public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByHashingUnitTest(Node<Integer> head, boolean cycleExists) { import org.junit.jupiter.params.ParameterizedTest;
super(); import org.junit.jupiter.params.provider.MethodSource;
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_detectLoop() { class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
@ParameterizedTest
@MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
} }
} }

View File

@ -7,7 +7,7 @@ import org.junit.runners.Parameterized.Parameters;
public class CycleDetectionTestBase { public class CycleDetectionTestBase {
@Parameters
public static Collection<Object[]> getLists() { public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] { return Arrays.asList(new Object[][] {
{ createList(), false }, { createList(), false },

View File

@ -1,24 +1,19 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import static org.junit.jupiter.api.Assertions.assertEquals;
public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { import static org.junit.jupiter.api.Assertions.assertFalse;
boolean cycleExists;
Node<Integer> head;
public CycleRemovalBruteForceUnitTest(Node<Integer> head, boolean cycleExists) { import org.junit.jupiter.params.ParameterizedTest;
super(); import org.junit.jupiter.params.provider.MethodSource;
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase {
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); @ParameterizedTest
@MethodSource("getLists")
void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
} }
} }

View File

@ -1,24 +1,17 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import org.junit.jupiter.params.ParameterizedTest;
public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { import org.junit.jupiter.params.provider.MethodSource;
boolean cycleExists;
Node<Integer> head;
public CycleRemovalByCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) { class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test @ParameterizedTest
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { @MethodSource("getLists")
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
} }
} }

View File

@ -1,24 +1,19 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class) import static org.junit.jupiter.api.Assertions.assertEquals;
public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { import static org.junit.jupiter.api.Assertions.assertFalse;
boolean cycleExists;
Node<Integer> head;
public CycleRemovalWithoutCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) { import org.junit.jupiter.params.ParameterizedTest;
super(); import org.junit.jupiter.params.provider.MethodSource;
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase {
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); @ParameterizedTest
@MethodSource("getLists")
void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
} }
} }

View File

@ -1,84 +1,84 @@
package com.baeldung.algorithms.moneywords; package com.baeldung.algorithms.moneywords;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
public class NumberWordConverterUnitTest { class NumberWordConverterUnitTest {
@Test @Test
public void whenMoneyNegative_thenReturnInvalidInput() { void whenMoneyNegative_thenReturnInvalidInput() {
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
} }
@Test @Test
public void whenZeroDollarsGiven_thenReturnEmptyString() { void whenZeroDollarsGiven_thenReturnEmptyString() {
assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
} }
@Test @Test
public void whenOnlyDollarsGiven_thenReturnWords() { void whenOnlyDollarsGiven_thenReturnWords() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
} }
@Test @Test
public void whenOnlyCentsGiven_thenReturnWords() { void whenOnlyCentsGiven_thenReturnWords() {
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
} }
@Test @Test
public void whenAlmostAMillioDollarsGiven_thenReturnWords() { void whenAlmostAMillioDollarsGiven_thenReturnWords() {
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
} }
@Test @Test
public void whenThirtyMillionDollarsGiven_thenReturnWords() { void whenThirtyMillionDollarsGiven_thenReturnWords() {
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
} }
@Test @Test
public void whenTwoBillionDollarsGiven_thenReturnWords() { void whenTwoBillionDollarsGiven_thenReturnWords() {
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
} }
@Test @Test
public void whenGivenDollarsAndCents_thenReturnWords() { void whenGivenDollarsAndCents_thenReturnWords() {
String expectedResult = "nine hundred twenty four dollars and sixty cents"; String expectedResult = "nine hundred twenty four dollars and sixty cents";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
} }
@Test @Test
public void whenOneDollarAndNoCents_thenReturnDollarSingular() { void whenOneDollarAndNoCents_thenReturnDollarSingular() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
} }
@Test @Test
public void whenNoDollarsAndOneCent_thenReturnCentSingular() { void whenNoDollarsAndOneCent_thenReturnCentSingular() {
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
} }
@Test @Test
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
} }
@Test @Test
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() { void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
} }
@Test @Test
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
} }
@Test @Test
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
} }
} }

View File

@ -1,6 +1,8 @@
package com.baeldung.jgrapht; package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List; import java.util.List;
@ -9,15 +11,15 @@ import org.jgrapht.alg.HamiltonianCycle;
import org.jgrapht.generate.CompleteGraphGenerator; import org.jgrapht.generate.CompleteGraphGenerator;
import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph; import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class CompleteGraphUnitTest { class CompleteGraphUnitTest {
static SimpleWeightedGraph<String, DefaultEdge> completeGraph; static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
static int size = 10; static int size = 10;
@Before @BeforeEach
public void createCompleteGraph() { public void createCompleteGraph() {
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size); CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);

View File

@ -1,7 +1,9 @@
package com.baeldung.jgrapht; package com.baeldung.jgrapht;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -21,13 +23,13 @@ import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedSubgraph; import org.jgrapht.graph.DirectedSubgraph;
import org.jgrapht.traverse.BreadthFirstIterator; import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.DepthFirstIterator; import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class DirectedGraphUnitTest { class DirectedGraphUnitTest {
DirectedGraph<String, DefaultEdge> directedGraph; DirectedGraph<String, DefaultEdge> directedGraph;
@Before @BeforeEach
public void createDirectedGraph() { public void createDirectedGraph() {
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
IntStream.range(1, 10).forEach(i -> { IntStream.range(1, 10).forEach(i -> {
@ -46,7 +48,7 @@ public class DirectedGraphUnitTest {
} }
@Test @Test
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
@ -60,7 +62,7 @@ public class DirectedGraphUnitTest {
} }
@Test @Test
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph); CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
assertTrue(cycleDetector.detectCycles()); assertTrue(cycleDetector.detectCycles());
Set<String> cycleVertices = cycleDetector.findCycles(); Set<String> cycleVertices = cycleDetector.findCycles();
@ -68,26 +70,26 @@ public class DirectedGraphUnitTest {
} }
@Test @Test
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
assertNotNull(depthFirstIterator); assertNotNull(depthFirstIterator);
} }
@Test @Test
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
assertNotNull(breadthFirstIterator); assertNotNull(breadthFirstIterator);
} }
@Test @Test
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath); assertNotNull(shortestPath);
} }
@Test @Test
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath); assertNotNull(shortestPath);

View File

@ -1,7 +1,7 @@
package com.baeldung.jgrapht; package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@ -9,13 +9,13 @@ import org.jgrapht.GraphPath;
import org.jgrapht.alg.cycle.HierholzerEulerianCycle; import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph; import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class EulerianCircuitUnitTest { class EulerianCircuitUnitTest {
SimpleWeightedGraph<String, DefaultEdge> simpleGraph; SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
@Before @BeforeEach
public void createGraphWithEulerianCircuit() { public void createGraphWithEulerianCircuit() {
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
IntStream.range(1, 6).forEach(i -> { IntStream.range(1, 6).forEach(i -> {

View File

@ -1,6 +1,8 @@
package com.baeldung.jgrapht; package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@ -12,18 +14,18 @@ import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter; import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DefaultEdge;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.mxgraph.layout.mxCircleLayout; import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout; import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer; import com.mxgraph.util.mxCellRenderer;
public class GraphImageGenerationUnitTest { class GraphImageGenerationUnitTest {
static DefaultDirectedGraph<String, DefaultEdge> g; static DefaultDirectedGraph<String, DefaultEdge> g;
@Before @BeforeEach
public void createGraph() throws IOException { public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph1.png"); File imgFile = new File("src/test/resources/graph1.png");
imgFile.createNewFile(); imgFile.createNewFile();
@ -39,14 +41,14 @@ public class GraphImageGenerationUnitTest {
g.addEdge(x3, x1); g.addEdge(x3, x1);
} }
@After @AfterEach
public void cleanup() { public void cleanup() {
File imgFile = new File("src/test/resources/graph1.png"); File imgFile = new File("src/test/resources/graph1.png");
imgFile.deleteOnExit(); imgFile.deleteOnExit();
} }
@Test @Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g); JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter); mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent()); layout.execute(graphAdapter.getDefaultParent());

View File

@ -0,0 +1,58 @@
package com.baeldung.algorithms.checktargetsum;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class CheckTargetSum {
public boolean isTargetSumExistNaive(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return true;
}
}
}
return false;
}
public boolean isTargetSumExistSorted(int[] nums, int target) {
Arrays.sort(nums);
int start = 0;
int end = nums.length - 1;
while (start < end) {
int sum = nums[start] + nums[end];
if (sum == target) {
return true;
}
if (sum < target) {
start++;
} else {
end--;
}
}
return false;
}
public boolean isTargetSumExistHashSet(int[] nums, int target) {
Set<Integer> hashSet = new HashSet<>();
for (int num : nums) {
int diff = target - num;
if (hashSet.contains(diff)) {
return true;
}
hashSet.add(num);
}
return false;
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.algorithms.analysis; package com.baeldung.algorithms.analysis;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class AnalysisRunnerLiveTest { class AnalysisRunnerLiveTest {
int n = 10; int n = 10;
int total = 0; int total = 0;
@Test @Test
public void whenConstantComplexity_thenConstantRuntime() { void whenConstantComplexity_thenConstantRuntime() {
System.out.println("**** n = " + n + " ****"); System.out.println("**** n = " + n + " ****");
System.out.println(); System.out.println();
@ -22,7 +22,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenLogarithmicComplexity_thenLogarithmicRuntime() { void whenLogarithmicComplexity_thenLogarithmicRuntime() {
// Logarithmic Time // Logarithmic Time
System.out.println("**** Logarithmic Time ****"); System.out.println("**** Logarithmic Time ****");
for (int i = 1; i < n; i = i * 2) { for (int i = 1; i < n; i = i * 2) {
@ -34,7 +34,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenLinearComplexity_thenLinearRuntime() { void whenLinearComplexity_thenLinearRuntime() {
// Linear Time // Linear Time
System.out.println("**** Linear Time ****"); System.out.println("**** Linear Time ****");
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
@ -47,7 +47,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenNLogNComplexity_thenNLogNRuntime() { void whenNLogNComplexity_thenNLogNRuntime() {
// N Log N Time // N Log N Time
System.out.println("**** nlogn Time ****"); System.out.println("**** nlogn Time ****");
total = 0; total = 0;
@ -64,7 +64,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenQuadraticComplexity_thenQuadraticRuntime() { void whenQuadraticComplexity_thenQuadraticRuntime() {
// Quadratic Time // Quadratic Time
System.out.println("**** Quadratic Time ****"); System.out.println("**** Quadratic Time ****");
total = 0; total = 0;
@ -81,7 +81,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenCubicComplexity_thenCubicRuntime() { void whenCubicComplexity_thenCubicRuntime() {
// Cubic Time // Cubic Time
System.out.println("**** Cubic Time ****"); System.out.println("**** Cubic Time ****");
total = 0; total = 0;
@ -100,7 +100,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenExponentialComplexity_thenExponentialRuntime() { void whenExponentialComplexity_thenExponentialRuntime() {
// Exponential Time // Exponential Time
System.out.println("**** Exponential Time ****"); System.out.println("**** Exponential Time ****");
total = 0; total = 0;
@ -115,7 +115,7 @@ public class AnalysisRunnerLiveTest {
} }
@Test @Test
public void whenFactorialComplexity_thenFactorialRuntime() { void whenFactorialComplexity_thenFactorialRuntime() {
// Factorial Time // Factorial Time
System.out.println("**** Factorial Time ****"); System.out.println("**** Factorial Time ****");
total = 0; total = 0;

View File

@ -11,10 +11,10 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class SortedListCheckerUnitTest { class SortedListCheckerUnitTest {
private List<String> sortedListOfString; private List<String> sortedListOfString;
private List<String> unsortedListOfString; private List<String> unsortedListOfString;
@ -23,7 +23,7 @@ public class SortedListCheckerUnitTest {
private List<Employee> employeesSortedByName; private List<Employee> employeesSortedByName;
private List<Employee> employeesNotSortedByName; private List<Employee> employeesNotSortedByName;
@Before @BeforeEach
public void setUp() { public void setUp() {
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY"); sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada"); unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
@ -34,72 +34,72 @@ public class SortedListCheckerUnitTest {
} }
@Test @Test
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() { void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue(); assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
} }
@Test @Test
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() { void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue(); assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
} }
@Test @Test
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() { void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse(); assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
} }
@Test @Test
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() { void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
} }
@Test @Test
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() { void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
} }
@Test @Test
public void givenSortedList_whenUsingRecursion_thenReturnTrue() { void givenSortedList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue(); assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
} }
@Test @Test
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() { void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue(); assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
} }
@Test @Test
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() { void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse(); assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
} }
@Test @Test
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() { void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue(); assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
} }
@Test @Test
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() { void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse(); assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
} }
@Test @Test
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() { void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
} }
@Test @Test
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() { void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
} }
@Test @Test
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() { void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue(); assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
} }
@Test @Test
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() { void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse(); assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
} }

View File

@ -0,0 +1,46 @@
package com.baeldung.algorithms.checktargetsum;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CheckTargetSumUnitTest {
private CheckTargetSum checkTargetSum = new CheckTargetSum();
private int[] nums = new int[] { 10, 5, 15, 7, 14, 1, 9 };
private int existingTarget = 6;
private int nonExistingTarget = 27;
@Test
public void givenArrayOfIntegers_whenTargetSumNaive_thenPairExists() {
assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
}
@Test
public void givenArrayOfIntegers_whenTargetSumNaive_thenPairDoesNotExists() {
assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
}
@Test
public void givenArrayOfIntegers_whenTargetSumSorted_thenPairExists() {
assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
}
@Test
public void givenArrayOfIntegers_whenTargetSumSorted_thenPairDoesNotExists() {
assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
}
@Test
public void givenArrayOfIntegers_whenTargetSumHashSet_thenPairExists() {
assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
}
@Test
public void givenArrayOfIntegers_whenTargetSumHashSet_thenPairDoesNotExists() {
assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
}
}

View File

@ -1,37 +1,37 @@
package com.baeldung.algorithms.enumstatemachine; package com.baeldung.algorithms.enumstatemachine;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class LeaveRequestStateUnitTest { class LeaveRequestStateUnitTest {
@Test @Test
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() { void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
LeaveRequestState state = LeaveRequestState.Escalated; LeaveRequestState state = LeaveRequestState.Escalated;
assertEquals(state.responsiblePerson(), "Team Leader"); assertEquals( "Team Leader", state.responsiblePerson());
} }
@Test @Test
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() { void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
LeaveRequestState state = LeaveRequestState.Approved; LeaveRequestState state = LeaveRequestState.Approved;
assertEquals(state.responsiblePerson(), "Department Manager"); assertEquals( "Department Manager" , state.responsiblePerson());
} }
@Test @Test
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() { void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
LeaveRequestState state = LeaveRequestState.Submitted; LeaveRequestState state = LeaveRequestState.Submitted;
state = state.nextState(); state = state.nextState();
assertEquals(state, LeaveRequestState.Escalated); assertEquals(LeaveRequestState.Escalated, state);
state = state.nextState(); state = state.nextState();
assertEquals(state, LeaveRequestState.Approved); assertEquals(LeaveRequestState.Approved, state);
state = state.nextState(); state = state.nextState();
assertEquals(state, LeaveRequestState.Approved); assertEquals(LeaveRequestState.Approved, state);
} }
} }

View File

@ -1,14 +1,14 @@
package com.baeldung.algorithms.graphcycledetection; package com.baeldung.algorithms.graphcycledetection;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.graphcycledetection.domain.Graph; import com.baeldung.algorithms.graphcycledetection.domain.Graph;
import com.baeldung.algorithms.graphcycledetection.domain.Vertex; import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
public class GraphCycleDetectionUnitTest { class GraphCycleDetectionUnitTest {
@Test @Test
public void givenGraph_whenCycleExists_thenReturnTrue() { public void givenGraph_whenCycleExists_thenReturnTrue() {
@ -33,7 +33,7 @@ public class GraphCycleDetectionUnitTest {
} }
@Test @Test
public void givenGraph_whenNoCycleExists_thenReturnFalse() { void givenGraph_whenNoCycleExists_thenReturnFalse() {
Vertex vertexA = new Vertex("A"); Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B"); Vertex vertexB = new Vertex("B");

View File

@ -1,14 +1,11 @@
package com.baeldung.algorithms.printtriangles; package com.baeldung.algorithms.printtriangles;
import junitparams.JUnitParamsRunner; import static org.junit.jupiter.api.Assertions.assertEquals;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(JUnitParamsRunner.class) class PrintTriangleExamplesUnitTest {
public class PrintTriangleExamplesUnitTest {
private static Object[][] rightTriangles() { private static Object[][] rightTriangles() {
String expected0 = ""; String expected0 = "";
@ -38,9 +35,9 @@ public class PrintTriangleExamplesUnitTest {
}; };
} }
@Test @ParameterizedTest
@Parameters(method = "rightTriangles") @MethodSource("rightTriangles")
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows); String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
assertEquals(expected, actual); assertEquals(expected, actual);
@ -74,24 +71,24 @@ public class PrintTriangleExamplesUnitTest {
}; };
} }
@Test @ParameterizedTest
@Parameters(method = "isoscelesTriangles") @MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows); String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
assertEquals(expected, actual); assertEquals(expected, actual);
} }
@Test @ParameterizedTest
@Parameters(method = "isoscelesTriangles") @MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows); String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
assertEquals(expected, actual); assertEquals(expected, actual);
} }
@Test @ParameterizedTest
@Parameters(method = "isoscelesTriangles") @MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows); String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);

View File

@ -1,13 +1,14 @@
package com.baeldung.algorithms.romannumerals; package com.baeldung.algorithms.romannumerals;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class RomanArabicConverterUnitTest { class RomanArabicConverterUnitTest {
@Test @Test
public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
String roman2018 = "MMXVIII"; String roman2018 = "MMXVIII";
@ -17,7 +18,7 @@ public class RomanArabicConverterUnitTest {
} }
@Test @Test
public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
int arabic1999 = 1999; int arabic1999 = 1999;

View File

@ -2,14 +2,14 @@ package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class LinkedListFindMiddleUnitTest { class LinkedListFindMiddleUnitTest {
LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle(); LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle();
@Test @Test
public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() { void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
MyNode<String> head = createNodesList(8); MyNode<String> head = createNodesList(8);

View File

@ -1,10 +1,10 @@
package com.baeldung.algorithms.twopointertechnique; package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class RotateArrayUnitTest { class RotateArrayUnitTest {
private RotateArray rotateArray = new RotateArray(); private RotateArray rotateArray = new RotateArray();
@ -13,7 +13,7 @@ public class RotateArrayUnitTest {
private int step; private int step;
@Test @Test
public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() { void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 }; inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
step = 4; step = 4;

View File

@ -1,11 +1,12 @@
package com.baeldung.algorithms.twopointertechnique; package com.baeldung.algorithms.twopointertechnique;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TwoSumUnitTest { class TwoSumUnitTest {
private TwoSum twoSum = new TwoSum(); private TwoSum twoSum = new TwoSum();
@ -14,7 +15,7 @@ public class TwoSumUnitTest {
private int targetValue; private int targetValue;
@Test @Test
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() { void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -24,7 +25,7 @@ public class TwoSumUnitTest {
} }
@Test @Test
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() { void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -34,7 +35,7 @@ public class TwoSumUnitTest {
} }
@Test @Test
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() { void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -44,7 +45,7 @@ public class TwoSumUnitTest {
} }
@Test @Test
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() { void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };

View File

@ -1,18 +1,18 @@
package com.baeldung.counter; package com.baeldung.counter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import org.junit.Test;
import com.baeldung.counter.CounterUtil.MutableInteger; import com.baeldung.counter.CounterUtil.MutableInteger;
public class CounterUnitTest { class CounterUnitTest {
@Test @Test
public void whenMapWithWrapperAsCounter_runsSuccessfully() { void whenMapWithWrapperAsCounter_runsSuccessfully() {
Map<String, Integer> counterMap = new HashMap<>(); Map<String, Integer> counterMap = new HashMap<>();
CounterUtil.counterWithWrapperObject(counterMap); CounterUtil.counterWithWrapperObject(counterMap);
@ -23,7 +23,7 @@ public class CounterUnitTest {
} }
@Test @Test
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() { void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
Map<String, Long> counterMap = new HashMap<>(); Map<String, Long> counterMap = new HashMap<>();
CounterUtil.counterWithLambdaAndWrapper(counterMap); CounterUtil.counterWithLambdaAndWrapper(counterMap);
@ -34,7 +34,7 @@ public class CounterUnitTest {
} }
@Test @Test
public void whenMapWithMutableIntegerCounter_runsSuccessfully() { void whenMapWithMutableIntegerCounter_runsSuccessfully() {
Map<String, MutableInteger> counterMap = new HashMap<>(); Map<String, MutableInteger> counterMap = new HashMap<>();
CounterUtil.counterWithMutableInteger(counterMap); CounterUtil.counterWithMutableInteger(counterMap);
assertEquals(3, counterMap.get("China") assertEquals(3, counterMap.get("China")
@ -44,7 +44,7 @@ public class CounterUnitTest {
} }
@Test @Test
public void whenMapWithPrimitiveArray_runsSuccessfully() { void whenMapWithPrimitiveArray_runsSuccessfully() {
Map<String, int[]> counterMap = new HashMap<>(); Map<String, int[]> counterMap = new HashMap<>();
CounterUtil.counterWithPrimitiveArray(counterMap); CounterUtil.counterWithPrimitiveArray(counterMap);
assertEquals(3, counterMap.get("China")[0]); assertEquals(3, counterMap.get("China")[0]);

View File

@ -1,22 +1,22 @@
package com.baeldung.folding; package com.baeldung.folding;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class FoldingHashUnitTest { class FoldingHashUnitTest {
@Test @Test
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception { void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int value = hasher.hash("Java language", 2, 100_000); final int value = hasher.hash("Java language", 2, 100_000);
assertEquals(value, 48933); assertEquals(value, 48933);
} }
@Test @Test
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int java = hasher.hash("Java language", 2, 100_000); final int java = hasher.hash("Java language", 2, 100_000);
final int vaja = hasher.hash("vaJa language", 2, 100_000); final int vaja = hasher.hash("vaJa language", 2, 100_000);
@ -24,28 +24,28 @@ public class FoldingHashUnitTest {
} }
@Test @Test
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 5 }, 0, 2); final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
assertArrayEquals(new int[] { 5 }, value); assertArrayEquals(new int[] { 5 }, value);
} }
@Test @Test
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
assertArrayEquals(new int[] { 1, 2, 3 }, value); assertArrayEquals(new int[] { 1, 2, 3 }, value);
} }
@Test @Test
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
assertArrayEquals(new int[] { 2, 3 }, value); assertArrayEquals(new int[] { 2, 3 }, value);
} }
@Test @Test
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
final FoldingHash hasher = new FoldingHash(); final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
assertArrayEquals(new int[] { 3, 4, 5 }, value); assertArrayEquals(new int[] { 3, 4, 5 }, value);

View File

@ -1,18 +1,19 @@
package com.baeldung.algorithms; package com.baeldung.algorithms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node; import com.baeldung.algorithms.middleelementlookup.Node;
import org.junit.Test;
import java.util.LinkedList; import java.util.LinkedList;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertFalse;
public class MiddleElementLookupUnitTest { class MiddleElementLookupUnitTest {
@Test @Test
public void whenFindingMiddleLinkedList_thenMiddleFound() { void whenFindingMiddleLinkedList_thenMiddleFound() {
assertEquals("3", MiddleElementLookup assertEquals("3", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(5)) .findMiddleElementLinkedList(createLinkedList(5))
.get()); .get());
@ -22,7 +23,7 @@ public class MiddleElementLookupUnitTest {
} }
@Test @Test
public void whenFindingMiddleFromHead_thenMiddleFound() { void whenFindingMiddleFromHead_thenMiddleFound() {
assertEquals("3", MiddleElementLookup assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(5)) .findMiddleElementFromHead(createNodesList(5))
.get()); .get());
@ -32,7 +33,7 @@ public class MiddleElementLookupUnitTest {
} }
@Test @Test
public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(5)) .findMiddleElementFromHead1PassRecursively(createNodesList(5))
.get()); .get());
@ -42,7 +43,7 @@ public class MiddleElementLookupUnitTest {
} }
@Test @Test
public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(5)) .findMiddleElementFromHead1PassIteratively(createNodesList(5))
.get()); .get());
@ -52,7 +53,7 @@ public class MiddleElementLookupUnitTest {
} }
@Test @Test
public void whenListEmptyOrNull_thenMiddleNotFound() { void whenListEmptyOrNull_thenMiddleNotFound() {
// null list // null list
assertFalse(MiddleElementLookup assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(null) .findMiddleElementLinkedList(null)

View File

@ -34,6 +34,23 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${xml-bind-api.version}</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb-runtime.version}</version>
</dependency>
</dependencies> </dependencies>
<properties>
<xml-bind-api.version>4.0.0</xml-bind-api.version>
<jaxb-runtime.version>4.0.0</jaxb-runtime.version>
</properties>
</project> </project>

View File

@ -2,13 +2,15 @@ package com.baeldung.algorithms.conversion;
import java.math.BigInteger; import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding; import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
public class HexStringConverter { public class HexStringConverter {
/** /**
@ -90,7 +92,7 @@ public class HexStringConverter {
return DatatypeConverter.parseHexBinary(hexString); return DatatypeConverter.parseHexBinary(hexString);
} }
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException { public String encodeUsingApacheCommons(byte[] bytes) {
return Hex.encodeHexString(bytes); return Hex.encodeHexString(bytes);
} }

View File

@ -1,22 +1,23 @@
package com.baeldung.algorithms.balancedbinarytree; package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider { import org.junit.jupiter.api.Test;
class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
@Test @Test
public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() { void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
for (Tree tree : balancedTrees()) { for (Tree tree : balancedTrees()) {
assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree)); assertTrue(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should be balanced");
} }
} }
@Test @Test
public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() { void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
for (Tree tree : unbalancedTrees()) { for (Tree tree : unbalancedTrees()) {
assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree)); assertFalse(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should not be balanced");
} }
} }

View File

@ -5,27 +5,31 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class BinaryGapUnitTest { class BinaryGapUnitTest {
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { @Test
void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(63); int result = calculateBinaryGap(63);
assertEquals(0, result); assertEquals(0, result);
} }
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { @Test
void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(40); int result = calculateBinaryGap(40);
assertEquals(1, result); assertEquals(1, result);
} }
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { @Test
void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(9); int result = calculateBinaryGap(9);
assertEquals(2, result); assertEquals(2, result);
} }
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { @Test
void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(145); int result = calculateBinaryGap(145);
assertEquals(3, result); assertEquals(3, result);

View File

@ -1,17 +1,18 @@
package com.baeldung.algorithms.combinatorics; package com.baeldung.algorithms.combinatorics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class CombinatoricsUnitTest { class CombinatoricsUnitTest {
@Test @Test
public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() { void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
List<Integer> sequence = Arrays.asList(); List<Integer> sequence = Arrays.asList();
List<List<Integer>> permutations = Combinatorics.permutations(sequence); List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -20,7 +21,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() { void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1); List<Integer> sequence = Arrays.asList(1);
List<List<Integer>> permutations = Combinatorics.permutations(sequence); List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -31,7 +32,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() { void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1, 2, 3, 4); List<Integer> sequence = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> permutations = Combinatorics.permutations(sequence); List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -41,7 +42,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() { void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
List<Integer> set = Arrays.asList(1, 2); List<Integer> set = Arrays.asList(1, 2);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3); List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
@ -50,7 +51,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() { void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
List<Integer> set = Arrays.asList(1, 2, 3); List<Integer> set = Arrays.asList(1, 2, 3);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3); List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
@ -60,7 +61,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() { void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
List<Integer> set = Arrays.asList(1, 2, 3, 4); List<Integer> set = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> combinations = Combinatorics.combinations(set, 2); List<List<Integer>> combinations = Combinatorics.combinations(set, 2);
@ -70,7 +71,7 @@ public class CombinatoricsUnitTest {
} }
@Test @Test
public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() { void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd'); List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd');
List<List<Character>> combinations = Combinatorics.powerSet(sequence); List<List<Character>> combinations = Combinatorics.powerSet(sequence);

View File

@ -1,27 +1,27 @@
package com.baeldung.algorithms.conversion; package com.baeldung.algorithms.conversion;
import static org.junit.Assert.assertArrayEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase; import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.conversion.HexStringConverter; import com.baeldung.algorithms.conversion.HexStringConverter;
public class ByteArrayConverterUnitTest { class ByteArrayConverterUnitTest {
private HexStringConverter hexStringConverter; private HexStringConverter hexStringConverter;
@Before @BeforeEach
public void setup() { public void setup() {
hexStringConverter = new HexStringConverter(); hexStringConverter = new HexStringConverter();
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
if(hexString.charAt(0) == '0') { if(hexString.charAt(0) == '0') {
@ -32,7 +32,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes); String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
@ -40,7 +40,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldDecodeHexStringToByteArrayUsingBigInteger() { void shouldDecodeHexStringToByteArrayUsingBigInteger() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString); byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
@ -48,7 +48,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
String output = hexStringConverter.encodeHexString(bytes); String output = hexStringConverter.encodeHexString(bytes);
@ -56,20 +56,22 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeHexString(hexString); byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output); assertArrayEquals(bytes, output);
} }
@Test(expected=IllegalArgumentException.class) @Test
public void shouldDecodeHexToByteWithInvalidHexCharacter() { void shouldDecodeHexToByteWithInvalidHexCharacter() {
hexStringConverter.hexToByte("fg"); assertThrows(IllegalArgumentException.class, () -> {
hexStringConverter.hexToByte("fg");
});
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringDataTypeConverter() { void shouldEncodeByteArrayToHexStringDataTypeConverter() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes); String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
@ -77,7 +79,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString); byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
@ -85,7 +87,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringUsingGuava() { void shouldEncodeByteArrayToHexStringUsingGuava() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingGuava(bytes); String output = hexStringConverter.encodeUsingGuava(bytes);
@ -93,7 +95,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldDecodeHexStringToByteArrayUsingGuava() { void shouldDecodeHexStringToByteArrayUsingGuava() {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingGuava(hexString); byte[] output = hexStringConverter.decodeUsingGuava(hexString);
@ -101,7 +103,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingApacheCommons(bytes); String output = hexStringConverter.encodeUsingApacheCommons(bytes);
@ -109,7 +111,7 @@ public class ByteArrayConverterUnitTest {
} }
@Test @Test
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes(); byte[] bytes = getSampleBytes();
String hexString = getSampleHexString(); String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString); byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);

View File

@ -1,16 +1,18 @@
package com.baeldung.algorithms.integerstreammedian; package com.baeldung.algorithms.integerstreammedian;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
public class MedianOfIntegerStreamUnitTest { class MedianOfIntegerStreamUnitTest {
@Test @Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() { void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
MedianOfIntegerStream mis = new MedianOfIntegerStream(); MedianOfIntegerStream mis = new MedianOfIntegerStream();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) { for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey()); mis.add(e.getKey());
@ -19,7 +21,7 @@ public class MedianOfIntegerStreamUnitTest {
} }
@Test @Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() { void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
MedianOfIntegerStream2 mis = new MedianOfIntegerStream2(); MedianOfIntegerStream2 mis = new MedianOfIntegerStream2();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) { for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey()); mis.add(e.getKey());

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class KnapsackUnitTest { class KnapsackUnitTest {
@Test @Test
public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() { void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10; final int n = 10;
@ -19,7 +19,7 @@ public class KnapsackUnitTest {
} }
@Test @Test
public void givenZeroItems_whenCalculateMax_thenOutputZero() { void givenZeroItems_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] {}; final int[] w = new int[] {};
final int[] v = new int[] {}; final int[] v = new int[] {};
final int n = 0; final int n = 0;
@ -31,7 +31,7 @@ public class KnapsackUnitTest {
} }
@Test @Test
public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() { void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10; final int n = 10;

View File

@ -5,10 +5,10 @@ import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.mergesortedarrays.SortedArrays; import com.baeldung.algorithms.mergesortedarrays.SortedArrays;
public class SortedArraysUnitTest { class SortedArraysUnitTest {
@Test @Test
public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() { void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 7 }; int[] foo = { 3, 7 };
int[] bar = { 4, 8, 11 }; int[] bar = { 4, 8, 11 };
@ -18,7 +18,7 @@ public class SortedArraysUnitTest {
} }
@Test @Test
public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() { void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 3, 7 }; int[] foo = { 3, 3, 7 };
int[] bar = { 4, 8, 8, 11 }; int[] bar = { 4, 8, 8, 11 };

View File

@ -1,14 +1,15 @@
package com.baeldung.algorithms.prim; package com.baeldung.algorithms.prim;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class PrimUnitTest { import org.junit.jupiter.api.Test;
class PrimUnitTest {
@Test @Test
public void givenAGraph_whenPrimRuns_thenPrintMST() { void givenAGraph_whenPrimRuns_thenPrintMST() {
Prim prim = new Prim(createGraph()); Prim prim = new Prim(createGraph());
System.out.println(prim.originalGraphToString()); System.out.println(prim.originalGraphToString());
System.out.println("----------------"); System.out.println("----------------");

View File

@ -1,49 +1,49 @@
package com.baeldung.algorithms.relativelyprime; package com.baeldung.algorithms.relativelyprime;
import org.junit.Test;
import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*; import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class RelativelyPrimeUnitTest { import org.junit.jupiter.api.Test;
class RelativelyPrimeUnitTest {
@Test @Test
public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() { void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
boolean result = iterativeRelativelyPrime(45, 35); boolean result = iterativeRelativelyPrime(45, 35);
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() { void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
boolean result = iterativeRelativelyPrime(500, 501); boolean result = iterativeRelativelyPrime(500, 501);
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() { void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
boolean result = recursiveRelativelyPrime(45, 35); boolean result = recursiveRelativelyPrime(45, 35);
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() { void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
boolean result = recursiveRelativelyPrime(500, 501); boolean result = recursiveRelativelyPrime(500, 501);
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() { void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
boolean result = bigIntegerRelativelyPrime(45, 35); boolean result = bigIntegerRelativelyPrime(45, 35);
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() { void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
boolean result = bigIntegerRelativelyPrime(500, 501); boolean result = bigIntegerRelativelyPrime(500, 501);
assertThat(result).isTrue(); assertThat(result).isTrue();

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class TreeReverserUnitTest { class TreeReverserUnitTest {
@Test @Test
public void givenTreeWhenReversingRecursivelyThenReversed() { void givenTreeWhenReversingRecursivelyThenReversed() {
TreeReverser reverser = new TreeReverser(); TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree(); TreeNode treeNode = createBinaryTree();
@ -19,7 +19,7 @@ public class TreeReverserUnitTest {
} }
@Test @Test
public void givenTreeWhenReversingIterativelyThenReversed() { void givenTreeWhenReversingIterativelyThenReversed() {
TreeReverser reverser = new TreeReverser(); TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree(); TreeNode treeNode = createBinaryTree();

View File

@ -1,80 +1,81 @@
package com.baeldung.algorithms.balancedbrackets; package com.baeldung.algorithms.balancedbrackets;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class BalancedBracketsUsingDequeUnitTest { import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class BalancedBracketsUsingDequeUnitTest {
private BalancedBracketsUsingDeque balancedBracketsUsingDeque; private BalancedBracketsUsingDeque balancedBracketsUsingDeque;
@Before @BeforeEach
public void setup() { public void setup() {
balancedBracketsUsingDeque = new BalancedBracketsUsingDeque(); balancedBracketsUsingDeque = new BalancedBracketsUsingDeque();
} }
@Test @Test
public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced(null); boolean result = balancedBracketsUsingDeque.isBalanced(null);
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced(""); boolean result = balancedBracketsUsingDeque.isBalanced("");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}"); boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}"); boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}"); boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}"); boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{}("); boolean result = balancedBracketsUsingDeque.isBalanced("{{}(");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}"); boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}"); boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}"); boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }

View File

@ -1,80 +1,81 @@
package com.baeldung.algorithms.balancedbrackets; package com.baeldung.algorithms.balancedbrackets;
import org.junit.Before;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class BalancedBracketsUsingStringUnitTest { class BalancedBracketsUsingStringUnitTest {
private BalancedBracketsUsingString balancedBracketsUsingString; private BalancedBracketsUsingString balancedBracketsUsingString;
@Before @BeforeEach
public void setup() { public void setup() {
balancedBracketsUsingString = new BalancedBracketsUsingString(); balancedBracketsUsingString = new BalancedBracketsUsingString();
} }
@Test @Test
public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced(null); boolean result = balancedBracketsUsingString.isBalanced(null);
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced(""); boolean result = balancedBracketsUsingString.isBalanced("");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("abc[](){}"); boolean result = balancedBracketsUsingString.isBalanced("abc[](){}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}"); boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}"); boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{[(])}"); boolean result = balancedBracketsUsingString.isBalanced("{[(])}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{}("); boolean result = balancedBracketsUsingString.isBalanced("{{}(");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }
@Test @Test
public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); boolean result = balancedBracketsUsingString.isBalanced("{[()]}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}"); boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{{([])}}"); boolean result = balancedBracketsUsingString.isBalanced("{{([])}}");
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test @Test
public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}"); boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}");
assertThat(result).isFalse(); assertThat(result).isFalse();
} }

View File

@ -2,17 +2,17 @@ package com.baeldung.algorithms.boruvka;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.google.common.graph.MutableValueGraph; import com.google.common.graph.MutableValueGraph;
import com.google.common.graph.ValueGraphBuilder; import com.google.common.graph.ValueGraphBuilder;
public class BoruvkaUnitTest { class BoruvkaUnitTest {
private MutableValueGraph<Integer, Integer> graph; private MutableValueGraph<Integer, Integer> graph;
@Before @BeforeEach
public void setup() { public void setup() {
graph = ValueGraphBuilder.undirected() graph = ValueGraphBuilder.undirected()
.build(); .build();
@ -26,7 +26,7 @@ public class BoruvkaUnitTest {
} }
@Test @Test
public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() {
BoruvkaMST boruvkaMST = new BoruvkaMST(graph); BoruvkaMST boruvkaMST = new BoruvkaMST(graph);
MutableValueGraph<Integer, Integer> mst = boruvkaMST.getMST(); MutableValueGraph<Integer, Integer> mst = boruvkaMST.getMST();

View File

@ -1,15 +1,15 @@
package com.baeldung.algorithms.gradientdescent; package com.baeldung.algorithms.gradientdescent;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.function.Function; import java.util.function.Function;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class GradientDescentUnitTest { class GradientDescentUnitTest {
@Test @Test
public void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() {
Function<Double, Double> df = x -> Function<Double, Double> df = x ->
StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x; StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x;
GradientDescent gd = new GradientDescent(); GradientDescent gd = new GradientDescent();

View File

@ -1,13 +1,14 @@
package com.baeldung.algorithms.greedy; package com.baeldung.algorithms.greedy;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class GreedyAlgorithmUnitTest {
class GreedyAlgorithmUnitTest {
private SocialConnector prepareNetwork() { private SocialConnector prepareNetwork() {
SocialConnector sc = new SocialConnector(); SocialConnector sc = new SocialConnector();
@ -35,21 +36,21 @@ public class GreedyAlgorithmUnitTest {
} }
@Test @Test
public void greedyAlgorithmTest() { void greedyAlgorithmTest() {
GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork());
assertEquals(ga.findMostFollowersPath("root"), 5); assertEquals(ga.findMostFollowersPath("root"), 5);
} }
@Test @Test
public void nongreedyAlgorithmTest() { void nongreedyAlgorithmTest() {
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0);
Assertions.assertThrows(IllegalStateException.class, () -> { assertThrows(IllegalStateException.class, () -> {
nga.findMostFollowersPath("root"); nga.findMostFollowersPath("root");
}); });
} }
@Test @Test
public void nongreedyAlgorithmUnboundedTest() { void nongreedyAlgorithmUnboundedTest() {
SocialConnector sc = prepareNetwork(); SocialConnector sc = prepareNetwork();
sc.switchCounter(); sc.switchCounter();
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0);

View File

@ -1,21 +1,23 @@
package com.baeldung.algorithms.kruskal; package com.baeldung.algorithms.kruskal;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import org.junit.Before; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.graph.MutableValueGraph; import com.google.common.graph.MutableValueGraph;
import com.google.common.graph.ValueGraph; import com.google.common.graph.ValueGraph;
import com.google.common.graph.ValueGraphBuilder; import com.google.common.graph.ValueGraphBuilder;
import com.baeldung.algorithms.kruskal.Kruskal; import com.baeldung.algorithms.kruskal.Kruskal;
public class KruskalUnitTest { class KruskalUnitTest {
private MutableValueGraph<Integer, Double> graph; private MutableValueGraph<Integer, Double> graph;
@Before @BeforeEach
public void setup() { public void setup() {
graph = ValueGraphBuilder.undirected().build(); graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(0, 1, 8.0); graph.putEdgeValue(0, 1, 8.0);
@ -28,7 +30,7 @@ public class KruskalUnitTest {
} }
@Test @Test
public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() { void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() {
final Kruskal kruskal = new Kruskal(); final Kruskal kruskal = new Kruskal();
ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph); ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph);
@ -47,7 +49,7 @@ public class KruskalUnitTest {
} }
@Test @Test
public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() { void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() {
final Kruskal kruskal = new Kruskal(); final Kruskal kruskal = new Kruskal();
ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph); ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph);

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertNotNull;
public class LinkedListReversalUnitTest { class LinkedListReversalUnitTest {
@Test @Test
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() { void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList(); ListNode head = constructLinkedList();
ListNode node = head; ListNode node = head;
for (int i = 1; i <= 5; i++) { for (int i = 1; i <= 5; i++) {
@ -25,7 +25,7 @@ public class LinkedListReversalUnitTest {
} }
@Test @Test
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() { void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList(); ListNode head = constructLinkedList();
ListNode node = head; ListNode node = head;
for (int i = 1; i <= 5; i++) { for (int i = 1; i <= 5; i++) {

View File

@ -2,17 +2,17 @@ package com.baeldung.algorithms.minheapmerge;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class MinHeapUnitTest { class MinHeapUnitTest {
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } }; private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 }; private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
@Test @Test
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
int[] resultArray = MinHeap.merge(inputArray); int[] resultArray = MinHeap.merge(inputArray);
assertThat(resultArray.length, is(equalTo(10))); assertThat(resultArray.length, is(equalTo(10)));

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.topkelements; package com.baeldung.algorithms.topkelements;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThat;
public class TopKElementsFinderUnitTest { import org.junit.jupiter.api.Test;
class TopKElementsFinderUnitTest {
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder(); private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder(); private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder(); private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
@ -20,27 +20,27 @@ public class TopKElementsFinderUnitTest {
@Test @Test
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
} }
@Test @Test
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
} }
@Test @Test
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() { void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
} }
@Test @Test
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
} }
@Test @Test
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
} }
} }

View File

@ -0,0 +1,93 @@
package com.baeldung.algorithms.frequentelements;
import java.util.*;
import java.util.stream.Collectors;
public class MostFrequentElementsFinder {
public static List<Integer> findByHashMapAndPriorityQueue(Integer[] array, int n) {
Map<Integer, Integer> countMap = new HashMap<>();
// For each element i in the array, add it to the countMap and increment its count.
for (Integer i : array) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}
// Create a max heap (priority queue) that will prioritize elements with higher counts.
PriorityQueue<Integer> heap = new PriorityQueue<>(
(a, b) -> countMap.get(b) - countMap.get(a));
// Add all the unique elements in the array to the heap.
heap.addAll(countMap.keySet());
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n && !heap.isEmpty(); i++) {
// Poll the highest-count element from the heap and add it to the result list.
result.add(heap.poll());
}
return result;
}
public static List<Integer> findByStream(Integer[] arr, int n) {
return Arrays.stream(arr).collect(Collectors.groupingBy(i -> i, Collectors.counting()))
.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.map(Map.Entry::getKey)
.limit(n)
.collect(Collectors.toList());
}
public static List<Integer> findByTreeMap(Integer[] arr, int n) {
// Create a TreeMap and use a reverse order comparator to sort the entries by frequency in descending order
Map<Integer, Integer> countMap = new TreeMap<>(Collections.reverseOrder());
for (int i : arr) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}
// Create a list of the map entries and sort them by value (i.e. by frequency) in descending order
List<Map.Entry<Integer, Integer>> sortedEntries = new ArrayList<>(countMap.entrySet());
sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
// Extract the n most frequent elements from the sorted list of entries
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n && i < sortedEntries.size(); i++) {
result.add(sortedEntries.get(i).getKey());
}
return result;
}
public static List<Integer> findByBucketSort(Integer[] arr, int n) {
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> freqMap = new HashMap<>();
List<Integer>[] bucket = new List[arr.length + 1];
// Loop through the input array and update the frequency count of each element in the HashMap
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
// Loop through the HashMap and add each element to its corresponding bucket based on its frequency count
for (int num : freqMap.keySet()) {
int freq = freqMap.get(num);
if (bucket[freq] == null) {
bucket[freq] = new ArrayList<>();
}
bucket[freq].add(num);
}
// Loop through the bucket array in reverse order and add the elements to the result list
// until we have found the n most frequent elements
for (int i = bucket.length - 1; i >= 0 && result.size() < n; i--) {
if (bucket[i] != null) {
result.addAll(bucket[i]);
}
}
// Return a sublist of the result list containing only the first n elements
return result.subList(0, n);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.algorithms.frequentelements;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class MostFrequentElementsUnitTest {
private final Integer[] inputArray = {1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9};
private final int n = 3;
private final Integer[] outputArray = {9, 7, 5};
@Test
void givenIntegersArray_UseFindByHashMapAndPriorityQueueMethod_thenReturnMostFrequentElements() {
assertThat(MostFrequentElementsFinder.findByHashMapAndPriorityQueue(inputArray, n)).containsExactly(outputArray);
}
@Test
void givenIntegersArray_UseFindByBucketSortMethod_thenReturnMostFrequentElements() {
assertThat(MostFrequentElementsFinder.findByBucketSort(inputArray, n)).containsExactly(outputArray);
}
@Test
void givenIntegersArray_UseFindByStreamMethod_thenReturnMostFrequentElements() {
assertThat(MostFrequentElementsFinder.findByStream(inputArray, n)).containsExactly(outputArray);
}
@Test
void givenIntegersArray_UseFindByTreeMapMethod_thenReturnMostFrequentElements() {
assertThat(MostFrequentElementsFinder.findByTreeMap(inputArray, n)).containsExactly(outputArray);
}
}

View File

@ -1,63 +1,66 @@
package com.baeldung.algorithms.luhn; package com.baeldung.algorithms.luhn;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class LuhnCheckerUnitTest { import org.junit.jupiter.api.Test;
class LuhnCheckerUnitTest {
@Test @Test
public void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() { void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
String cardNumber = "8649"; String cardNumber = "8649";
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result); assertTrue(result);
} }
@Test @Test
public void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() { void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
String cardNumber = "8642"; String cardNumber = "8642";
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result); assertFalse(result);
} }
@Test @Test
public void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() { void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "0505050505050505"; String cardNumber = "0505050505050505";
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result); assertTrue(result);
} }
@Test @Test
public void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() { void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "75757575757575"; String cardNumber = "75757575757575";
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result); assertTrue(result);
} }
@Test @Test
public void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() { void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(0), 0); assertEquals(0,LuhnChecker.doubleAndSumDigits(0));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(1), 2); assertEquals(2,LuhnChecker.doubleAndSumDigits(1));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(2), 4); assertEquals(4, LuhnChecker.doubleAndSumDigits(2));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(3), 6); assertEquals(6, LuhnChecker.doubleAndSumDigits(3));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(4), 8); assertEquals(8, LuhnChecker.doubleAndSumDigits(4));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(5), 1); assertEquals(1, LuhnChecker.doubleAndSumDigits(5));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(6), 3); assertEquals(3, LuhnChecker.doubleAndSumDigits(6));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(7), 5); assertEquals(5, LuhnChecker.doubleAndSumDigits(7));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(8), 7); assertEquals(7, LuhnChecker.doubleAndSumDigits(8));
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(9), 9); assertEquals(9, LuhnChecker.doubleAndSumDigits(9));
} }
@Test @Test
public void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() { void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
String cardNumber = "test"; String cardNumber = "test";
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result); assertFalse(result);
} }
@Test @Test
public void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() { void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
String cardNumber = null; String cardNumber = null;
boolean result = LuhnChecker.checkLuhn(cardNumber); boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result); assertFalse(result);
} }
} }

View File

@ -1,11 +1,13 @@
package com.baeldung.algorithms.binarysearch; package com.baeldung.algorithms.binarysearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchUnitTest { import org.junit.jupiter.api.Test;
class BinarySearchUnitTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6; int key = 6;
@ -15,27 +17,27 @@ public class BinarySearchUnitTest {
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test @Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch(); BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
} }
@Test @Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch(); BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
} }
@Test @Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch(); BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
} }
@Test @Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch(); BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
} }
} }

View File

@ -1,15 +1,15 @@
package com.baeldung.algorithms.dfs; package com.baeldung.algorithms.dfs;
import org.junit.Test; 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 static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BinaryTreeUnitTest { class BinaryTreeUnitTest {
@Test @Test
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -17,7 +17,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -28,7 +28,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -40,7 +40,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -48,7 +48,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -58,7 +58,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -71,7 +71,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void it_deletes_the_root() { void it_deletes_the_root() {
int value = 12; int value = 12;
BinaryTree bt = new BinaryTree(); BinaryTree bt = new BinaryTree();
bt.add(value); bt.add(value);
@ -82,7 +82,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -92,7 +92,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();
@ -102,7 +102,7 @@ public class BinaryTreeUnitTest {
} }
@Test @Test
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree(); BinaryTree bt = createBinaryTree();

View File

@ -2,12 +2,12 @@ package com.baeldung.algorithms.dfs;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class GraphUnitTest { class GraphUnitTest {
@Test @Test
public void givenDirectedGraph_whenDFS_thenPrintAllValues() { void givenDirectedGraph_whenDFS_thenPrintAllValues() {
Graph graph = createDirectedGraph(); Graph graph = createDirectedGraph();
graph.dfs(0); graph.dfs(0);
System.out.println(); System.out.println();
@ -15,7 +15,7 @@ public class GraphUnitTest {
} }
@Test @Test
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
Graph graph = createDirectedGraph(); Graph graph = createDirectedGraph();
List<Integer> list = graph.topologicalSort(0); List<Integer> list = graph.topologicalSort(0);
System.out.println(list); System.out.println(list);

View File

@ -1,27 +1,28 @@
package com.baeldung.algorithms.interpolationsearch; package com.baeldung.algorithms.interpolationsearch;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class InterpolationSearchUnitTest { import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class InterpolationSearchUnitTest {
private int[] myData; private int[] myData;
@Before @BeforeEach
public void setUp() { public void setUp() {
myData = new int[]{13,21,34,55,69,73,84,101}; myData = new int[]{13,21,34,55,69,73,84,101};
} }
@Test @Test
public void givenSortedArray_whenLookingFor84_thenReturn6() { void givenSortedArray_whenLookingFor84_thenReturn6() {
int pos = InterpolationSearch.interpolationSearch(myData, 84); int pos = InterpolationSearch.interpolationSearch(myData, 84);
assertEquals(6, pos); assertEquals(6, pos);
} }
@Test @Test
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() { void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
int pos = InterpolationSearch.interpolationSearch(myData, 19); int pos = InterpolationSearch.interpolationSearch(myData, 19);
assertEquals(-1, pos); assertEquals(-1, pos);
} }

View File

@ -9,13 +9,13 @@ import java.util.*;
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*; import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
public class KthSmallestUnitTest { class KthSmallestUnitTest {
@Nested @Nested
class Exceptions { class Exceptions {
@Test @Test
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() { void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, null, null); Executable executable1 = () -> findKthSmallestElement(1, null, null);
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
@ -27,7 +27,7 @@ public class KthSmallestUnitTest {
} }
@Test @Test
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() { void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2}); Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{}); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
@ -39,19 +39,19 @@ public class KthSmallestUnitTest {
} }
@Test @Test
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() { void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2}); Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1); assertThrows(IllegalArgumentException.class, executable1);
} }
@Test @Test
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() { void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2}); Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1); assertThrows(IllegalArgumentException.class, executable1);
} }
@Test @Test
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() { void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5}); Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
assertThrows(NoSuchElementException.class, executable1); assertThrows(NoSuchElementException.class, executable1);
} }

View File

@ -1,12 +1,13 @@
package com.baeldung.algorithms.mcts; package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch; import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State; import com.baeldung.algorithms.mcts.montecarlo.State;
@ -15,31 +16,31 @@ import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position; import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree; import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSUnitTest { class MCTSUnitTest {
private Tree gameTree; private Tree gameTree;
private MonteCarloTreeSearch mcts; private MonteCarloTreeSearch mcts;
@Before @BeforeEach
public void initGameTree() { public void initGameTree() {
gameTree = new Tree(); gameTree = new Tree();
mcts = new MonteCarloTreeSearch(); mcts = new MonteCarloTreeSearch();
} }
@Test @Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79; double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01); assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
} }
@Test @Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState(); State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates(); List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0); assertTrue(possibleStates.size() > 0);
} }
@Test @Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board(); Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size(); int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1)); board.performMove(Board.P1, new Position(1, 1));
@ -48,7 +49,7 @@ public class MCTSUnitTest {
} }
@Test @Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board(); Board board = new Board();
int player = Board.P1; int player = Board.P1;
@ -61,11 +62,11 @@ public class MCTSUnitTest {
player = 3 - player; player = 3 - player;
} }
int winStatus = board.checkStatus(); int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW); assertEquals(Board.DRAW, winStatus);
} }
@Test @Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board(); Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch(); MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1); mcts1.setLevel(1);

View File

@ -1,21 +1,22 @@
package com.baeldung.algorithms.quadtree; package com.baeldung.algorithms.quadtree;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List; import java.util.List;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class QuadTreeSearchUnitTest { class QuadTreeSearchUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class); private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class);
private static QuadTree quadTree; private static QuadTree quadTree;
@BeforeClass @BeforeAll
public static void setUp() { public static void setUp() {
Region area = new Region(0, 0, 400, 400); Region area = new Region(0, 0, 400, 400);
quadTree = new QuadTree(area); quadTree = new QuadTree(area);
@ -32,30 +33,30 @@ public class QuadTreeSearchUnitTest {
} }
@Test @Test
public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() { void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() {
Region searchArea = new Region(200, 200, 250, 250); Region searchArea = new Region(200, 200, 250, 250);
List<Point> result = quadTree.search(searchArea, null, ""); List<Point> result = quadTree.search(searchArea, null, "");
LOGGER.debug(result.toString()); LOGGER.debug(result.toString());
LOGGER.debug(quadTree.printSearchTraversePath()); LOGGER.debug(quadTree.printSearchTraversePath());
Assert.assertEquals(1, result.size()); assertEquals(1, result.size());
Assert.assertArrayEquals(new float[] { 245, 238 }, assertArrayEquals(new float[] { 245, 238 },
new float[]{result.get(0).getX(), result.get(0).getY() }, 0); new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
} }
@Test @Test
public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() { void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() {
Region searchArea = new Region(0, 0, 100, 100); Region searchArea = new Region(0, 0, 100, 100);
List<Point> result = quadTree.search(searchArea, null, ""); List<Point> result = quadTree.search(searchArea, null, "");
LOGGER.debug(result.toString()); LOGGER.debug(result.toString());
LOGGER.debug(quadTree.printSearchTraversePath()); LOGGER.debug(quadTree.printSearchTraversePath());
Assert.assertEquals(2, result.size()); assertEquals(2, result.size());
Assert.assertArrayEquals(new float[] { 21, 25 }, assertArrayEquals(new float[] { 21, 25 },
new float[]{result.get(0).getX(), result.get(0).getY() }, 0); new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
Assert.assertArrayEquals(new float[] { 55, 53 }, assertArrayEquals(new float[] { 55, 53 },
new float[]{result.get(1).getX(), result.get(1).getY() }, 0); new float[]{result.get(1).getX(), result.get(1).getY() }, 0);
} }

View File

@ -1,71 +1,72 @@
package com.baeldung.algorithms.suffixtree; package com.baeldung.algorithms.suffixtree;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.List; import java.util.List;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class SuffixTreeUnitTest { class SuffixTreeUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class); private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class);
private static SuffixTree suffixTree; private static SuffixTree suffixTree;
@BeforeClass @BeforeAll
public static void setUp() { public static void setUp() {
suffixTree = new SuffixTree("havanabanana"); suffixTree = new SuffixTree("havanabanana");
printTree(); printTree();
} }
@Test @Test
public void givenSuffixTree_whenSearchingForA_thenReturn6Matches() { void givenSuffixTree_whenSearchingForA_thenReturn6Matches() {
List<String> matches = suffixTree.searchText("a"); List<String> matches = suffixTree.searchText("a");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray()); assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray());
} }
@Test @Test
public void givenSuffixTree_whenSearchingForNab_thenReturn1Match() { void givenSuffixTree_whenSearchingForNab_thenReturn1Match() {
List<String> matches = suffixTree.searchText("nab"); List<String> matches = suffixTree.searchText("nab");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray()); assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray());
} }
@Test @Test
public void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() { void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() {
List<String> matches = suffixTree.searchText("nag"); List<String> matches = suffixTree.searchText("nag");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] {}, matches.toArray()); assertArrayEquals(new String[] {}, matches.toArray());
} }
@Test @Test
public void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() { void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() {
List<String> matches = suffixTree.searchText("ana"); List<String> matches = suffixTree.searchText("ana");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray()); assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray());
} }
@Test @Test
public void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() { void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() {
List<String> matches = suffixTree.searchText("na"); List<String> matches = suffixTree.searchText("na");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray()); assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray());
} }
@Test @Test
public void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() { void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() {
List<String> matches = suffixTree.searchText("x"); List<String> matches = suffixTree.searchText("x");
matches.stream() matches.stream()
.forEach(m -> LOGGER.debug(m)); .forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] {}, matches.toArray()); assertArrayEquals(new String[] {}, matches.toArray());
} }
private static void printTree() { private static void printTree() {

View File

@ -1,23 +1,24 @@
package com.baeldung.algorithms.textsearch; package com.baeldung.algorithms.textsearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
public class TextSearchAlgorithmsUnitTest { class TextSearchAlgorithmsUnitTest {
@Test @Test
public void testStringSearchAlgorithms() { void testStringSearchAlgorithms() {
String text = "This is some nice text."; String text = "This is some nice text.";
String pattern = "some"; String pattern = "some";
int realPosition = text.indexOf(pattern); int realPosition = text.indexOf(pattern);
Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray())); assertEquals(TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray())); assertEquals(TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()), realPosition);
Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray())); assertEquals(TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()) , realPosition);
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray())); assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray())); assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
} }
} }

View File

@ -4,4 +4,5 @@
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting) - [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries) - [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- [Gravity/Bead Sort in Java](https://www.baeldung.com/java-gravity-bead-sort)
- More articles: [[<-- prev]](/algorithms-sorting) - More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -0,0 +1,60 @@
package com.baeldung.algorithms.gravitysort;
public class GravitySort {
public static int findMax(int[] A) {
int max = A[0];
for (int i = 1; i< A.length; i++) {
if (A[i] > max) {
max = A[i];
}
}
return max;
}
public static boolean[][] setupAbacus(int[] A, int m) {
boolean[][] abacus = new boolean[A.length][m];
for (int i = 0; i < abacus.length; i++) {
int number = A[i];
for (int j = 0; j < abacus[0].length && j < number; j++) {
abacus[A.length - 1 - i][j] = true;
}
}
return abacus;
}
public static void dropBeads(boolean[][] abacus, int[] A, int m) {
for (int i = 1; i < A.length; i++) {
for (int j = m - 1; j >= 0; j--) {
if (abacus[i][j] == true) {
int x = i;
while (x > 0 && abacus[x - 1][j] == false) {
boolean temp = abacus[x - 1][j];
abacus[x - 1][j] = abacus[x][j];
abacus[x][j] = temp;
x--;
}
}
}
}
}
public static void transformToList(boolean[][] abacus, int[] A) {
int index = 0;
for (int i = abacus.length - 1; i >= 0; i--) {
int beads = 0;
for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) {
beads++;
}
A[index++] = beads;
}
}
public static void sort(int[] A) {
int m = findMax(A);
boolean[][] abacus = setupAbacus(A, m);
dropBeads(abacus, A, m);
// transform abacus into sorted list
transformToList(abacus, A);
}
}

View File

@ -1,17 +1,19 @@
package com.baeldung.algorithms.bynumber; package com.baeldung.algorithms.bynumber;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
public class NaturalOrderComparatorsUnitTest { class NaturalOrderComparatorsUnitTest {
@Test @Test
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d"); List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
@ -25,7 +27,7 @@ public class NaturalOrderComparatorsUnitTest {
} }
@Test @Test
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d"); List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
@ -39,7 +41,7 @@ public class NaturalOrderComparatorsUnitTest {
} }
@Test @Test
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d"); List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
@ -53,7 +55,7 @@ public class NaturalOrderComparatorsUnitTest {
} }
@Test @Test
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5 List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
@ -66,7 +68,7 @@ public class NaturalOrderComparatorsUnitTest {
} }
@Test @Test
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
List<String> testStrings = Arrays.asList("a", "c", "d", "e"); List<String> testStrings = Arrays.asList("a", "c", "d", "e");
List<String> expected = new ArrayList<>(testStrings); List<String> expected = new ArrayList<>(testStrings);

View File

@ -0,0 +1,16 @@
package com.baeldung.algorithms.gravitysort;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class GravitySortUnitTest {
@Test
void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() {
int[] actual = { 9, 9, 100, 3, 57, 12, 3, 78, 0, 2, 2, 40, 21, 9 };
int[] expected = { 0, 2, 2, 3, 3, 9, 9, 9, 12, 21, 40, 57, 78, 100 };
GravitySort.sort(actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,23 +1,22 @@
package com.baeldung.algorithms.inoutsort; package com.baeldung.algorithms.inoutsort;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class InOutSortUnitTest { class InOutSortUnitTest {
@Test @Test
public void givenArray_whenInPlaceSort_thenReversed() { void givenArray_whenInPlaceSort_thenReversed() {
int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] input = {1, 2, 3, 4, 5, 6, 7};
int[] expected = {7, 6, 5, 4, 3, 2, 1}; int[] expected = {7, 6, 5, 4, 3, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input)); assertArrayEquals(expected, InOutSort.reverseInPlace(input), "the two arrays are not equal");
} }
@Test @Test
public void givenArray_whenOutOfPlaceSort_thenReversed() { void givenArray_whenOutOfPlaceSort_thenReversed() {
int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] input = {1, 2, 3, 4, 5, 6, 7};
int[] expected = {7, 6, 5, 4, 3, 2, 1}; int[] expected = {7, 6, 5, 4, 3, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input)); assertArrayEquals(expected, InOutSort.reverseOutOfPlace(input), "the two arrays are not equal");
} }
} }

View File

@ -1,16 +1,17 @@
package com.baeldung.algorithms.quicksort; package com.baeldung.algorithms.quicksort;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
public class BentleyMcilroyPartitioningUnitTest { import org.junit.jupiter.api.Test;
class BentleyMcilroyPartitioningUnitTest {
@Test @Test
public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() {
int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3};
int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7};
BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1);
Assert.assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
} }

View File

@ -1,15 +1,16 @@
package com.baeldung.algorithms.quicksort; package com.baeldung.algorithms.quicksort;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
public class DNFThreeWayQuickSortUnitTest { import org.junit.jupiter.api.Test;
class DNFThreeWayQuickSortUnitTest {
@Test @Test
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3};
int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7};
DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1);
Assert.assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
} }

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class BubbleSortUnitTest { class BubbleSortUnitTest {
@Test @Test
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] array = { 2, 1, 4, 6, 3, 5 };
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
BubbleSort bubbleSort = new BubbleSort(); BubbleSort bubbleSort = new BubbleSort();
@ -16,7 +16,7 @@ public class BubbleSortUnitTest {
} }
@Test @Test
public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] array = { 2, 1, 4, 6, 3, 5 };
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
BubbleSort bubbleSort = new BubbleSort(); BubbleSort bubbleSort = new BubbleSort();

View File

@ -1,24 +1,26 @@
package com.baeldung.algorithms.bucketsort; package com.baeldung.algorithms.bucketsort;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class IntegerBucketSorterUnitTest { class IntegerBucketSorterUnitTest {
private IntegerBucketSorter sorter; private IntegerBucketSorter sorter;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
sorter = new IntegerBucketSorter(); sorter = new IntegerBucketSorter();
} }
@Test @Test
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() { void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15); List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602); List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
@ -26,7 +28,5 @@ public class IntegerBucketSorterUnitTest {
List<Integer> actual = sorter.sort(unsorted); List<Integer> actual = sorter.sort(unsorted);
assertEquals(expected, actual); assertEquals(expected, actual);
} }
} }

View File

@ -1,16 +1,16 @@
package com.baeldung.algorithms.heapsort; package com.baeldung.algorithms.heapsort;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class HeapUnitTest { class HeapUnitTest {
@Test @Test
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() { void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
// given // given
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2); Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
@ -22,7 +22,7 @@ public class HeapUnitTest {
} }
@Test @Test
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() { void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
// given // given
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2); List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);

View File

@ -1,25 +1,25 @@
package com.baeldung.algorithms.insertionsort; package com.baeldung.algorithms.insertionsort;
import com.baeldung.algorithms.insertionsort.InsertionSort;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class InsertionSortUnitTest { import org.junit.jupiter.api.Test;
class InsertionSortUnitTest {
@Test @Test
public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
int[] input = {6, 2, 3, 4, 5, 1}; int[] input = {6, 2, 3, 4, 5, 1};
InsertionSort.insertionSortImperative(input); InsertionSort.insertionSortImperative(input);
int[] expected = {1, 2, 3, 4, 5, 6}; int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input); assertArrayEquals(expected, input, "the two arrays are not equal");
} }
@Test @Test
public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
int[] input = {6, 4, 5, 2, 3, 1}; int[] input = {6, 4, 5, 2, 3, 1};
InsertionSort.insertionSortRecursive(input); InsertionSort.insertionSortRecursive(input);
int[] expected = {1, 2, 3, 4, 5, 6}; int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input); assertArrayEquals( expected, input, "the two arrays are not equal");
} }
} }

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.mergesort; package com.baeldung.algorithms.mergesort;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class MergeSortUnitTest { class MergeSortUnitTest {
@Test @Test
public void positiveTest() { void positiveTest() {
int[] actual = { 5, 1, 6, 2, 3, 4 }; int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 }; int[] expected = { 1, 2, 3, 4, 5, 6 };
MergeSort.mergeSort(actual, actual.length); MergeSort.mergeSort(actual, actual.length);
Assert.assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
} }

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.quicksort; package com.baeldung.algorithms.quicksort;
import com.baeldung.algorithms.quicksort.QuickSort; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Assert;
import org.junit.Test;
public class QuickSortUnitTest { import org.junit.jupiter.api.Test;
class QuickSortUnitTest {
@Test @Test
public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 }; int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 };
int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
QuickSort.quickSort(actual, 0, actual.length-1); QuickSort.quickSort(actual, 0, actual.length-1);
Assert.assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
} }

View File

@ -1,15 +1,16 @@
package com.baeldung.algorithms.quicksort; package com.baeldung.algorithms.quicksort;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
public class ThreeWayQuickSortUnitTest { import org.junit.jupiter.api.Test;
class ThreeWayQuickSortUnitTest {
@Test @Test
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 }; int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 };
int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 }; int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 };
ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1); ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1);
Assert.assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
} }

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.radixsort; package com.baeldung.algorithms.radixsort;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class RadixSortUnitTest { class RadixSortUnitTest {
@Test @Test
public void givenUnsortedArray_whenRadixSort_thenArraySorted() { void givenUnsortedArray_whenRadixSort_thenArraySorted() {
int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 }; int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 };
RadixSort.sort(numbers); RadixSort.sort(numbers);
int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 }; int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 };

View File

@ -1,25 +1,24 @@
package com.baeldung.algorithms.selectionsort; package com.baeldung.algorithms.selectionsort;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class SelectionSortUnitTest { class SelectionSortUnitTest {
@Test @Test
public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() { void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
int[] input = { 5, 4, 1, 6, 2 }; int[] input = { 5, 4, 1, 6, 2 };
SelectionSort.sortAscending(input); SelectionSort.sortAscending(input);
int[] expected = {1, 2, 4, 5, 6}; int[] expected = {1, 2, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input); assertArrayEquals(expected, input, "the two arrays are not equal");
} }
@Test @Test
public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() { void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
int[] input = { 5, 4, 1, 6, 2 }; int[] input = { 5, 4, 1, 6, 2 };
SelectionSort.sortDescending(input); SelectionSort.sortDescending(input);
int[] expected = {6, 5, 4, 2, 1}; int[] expected = {6, 5, 4, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, input); assertArrayEquals(expected, input, "the two arrays are not equal");
} }
} }

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.shellsort; package com.baeldung.algorithms.shellsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class ShellSortUnitTest { import org.junit.jupiter.api.Test;
class ShellSortUnitTest {
@Test @Test
public void givenUnsortedArray_whenShellSort_thenSortedAsc() { void givenUnsortedArray_whenShellSort_thenSortedAsc() {
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8}; int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
ShellSort.sort(input); ShellSort.sort(input);
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82}; int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
assertArrayEquals("the two arrays are not equal", expected, input); assertArrayEquals( expected, input, "the two arrays are not equal");
} }
} }

View File

@ -21,6 +21,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<auto-service.version>1.0-rc2</auto-service.version> <auto-service.version>1.0-rc2</auto-service.version>
</properties> </properties>

View File

@ -1,7 +0,0 @@
## Apache CXF
This module contains articles about Apache CXF
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)

View File

@ -20,4 +20,8 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<cxf.version>4.0.0</cxf.version>
</properties>
</project> </project>

View File

@ -80,16 +80,20 @@ public class BaeldungIntegrationTest {
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception { private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter(); AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class); AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName)); final FileOutputStream stream = new FileOutputStream(fileName);
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stream);
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType); writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
xmlWriter.close(); xmlWriter.close();
stream.close();
} }
private CourseRepo unmarshalCourseRepo() throws Exception { private CourseRepo unmarshalCourseRepo() throws Exception {
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader(); AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName)); final FileInputStream stream = new FileInputStream(fileName);
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class)); CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
xmlReader.close(); xmlReader.close();
stream.close();
return courseRepo; return courseRepo;
} }
@ -97,7 +101,7 @@ public class BaeldungIntegrationTest {
public void cleanup(){ public void cleanup(){
File testFile = new File(fileName); File testFile = new File(fileName);
if (testFile.exists()) { if (testFile.exists()) {
testFile.delete(); testFile.deleteOnExit();
} }
} }
} }

View File

@ -23,6 +23,16 @@
<artifactId>cxf-rt-transports-http-jetty</artifactId> <artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version> <version>${cxf.version}</version>
</dependency> </dependency>
<dependency>
<groupId>jakarta.xml.ws</groupId>
<artifactId>jakarta.xml.ws-api</artifactId>
<version>${jakarta-xml.version}</version>
</dependency>
<dependency>
<groupId>jakarta.jws</groupId>
<artifactId>jakarta.jws-api</artifactId>
<version>${jakarta.jws.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -37,4 +47,10 @@
</plugins> </plugins>
</build> </build>
<properties>
<cxf.version>4.0.0</cxf.version>
<jakarta-xml.version>4.0.0</jakarta-xml.version>
<jakarta.jws.version>3.0.0</jakarta.jws.version>
</properties>
</project> </project>

View File

@ -2,8 +2,8 @@ package com.baeldung.cxf.introduction;
import java.util.Map; import java.util.Map;
import javax.jws.WebService; import jakarta.jws.WebService;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@WebService @WebService
public interface Baeldung { public interface Baeldung {

View File

@ -3,7 +3,7 @@ package com.baeldung.cxf.introduction;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import javax.jws.WebService; import jakarta.jws.WebService;
@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung") @WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
public class BaeldungImpl implements Baeldung { public class BaeldungImpl implements Baeldung {

View File

@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction; package com.baeldung.cxf.introduction;
import javax.xml.ws.Endpoint; import jakarta.xml.ws.Endpoint;
public class Server { public class Server {
public static void main(String args[]) throws InterruptedException { public static void main(String args[]) throws InterruptedException {

View File

@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction; package com.baeldung.cxf.introduction;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlJavaTypeAdapter(StudentAdapter.class) @XmlJavaTypeAdapter(StudentAdapter.class)
public interface Student { public interface Student {

Some files were not shown because too many files have changed in this diff Show More