repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java | package com.baeldung.algorithms.printtriangles;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class PrintTriangleExamplesUnitTest {
private static Object[][] rightTriangles() {
String expected0 = "";
String expected2 = "*" + System.lineSeparator()
+ "**" + System.lineSeparator();
String expected5 = "*" + System.lineSeparator()
+ "**" + System.lineSeparator()
+ "***" + System.lineSeparator()
+ "****" + System.lineSeparator()
+ "*****" + System.lineSeparator();
String expected7 = "*" + System.lineSeparator()
+ "**" + System.lineSeparator()
+ "***" + System.lineSeparator()
+ "****" + System.lineSeparator()
+ "*****" + System.lineSeparator()
+ "******" + System.lineSeparator()
+ "*******" + System.lineSeparator();
return new Object[][] {
{ 0, expected0 },
{ 2, expected2 },
{ 5, expected5 },
{ 7, expected7 }
};
}
@ParameterizedTest
@MethodSource("rightTriangles")
void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
assertEquals(expected, actual);
}
private static Object[][] isoscelesTriangles() {
String expected0 = "";
String expected2 = " *" + System.lineSeparator()
+ "***" + System.lineSeparator();
String expected5 = " *" + System.lineSeparator()
+ " ***" + System.lineSeparator()
+ " *****" + System.lineSeparator()
+ " *******" + System.lineSeparator()
+ "*********" + System.lineSeparator();
String expected7 = " *" + System.lineSeparator()
+ " ***" + System.lineSeparator()
+ " *****" + System.lineSeparator()
+ " *******" + System.lineSeparator()
+ " *********" + System.lineSeparator()
+ " ***********" + System.lineSeparator()
+ "*************" + System.lineSeparator();
return new Object[][] {
{ 0, expected0 },
{ 2, expected2 },
{ 5, expected5 },
{ 7, expected7 }
};
}
@ParameterizedTest
@MethodSource("isoscelesTriangles")
void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
assertEquals(expected, actual);
}
@ParameterizedTest
@MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
assertEquals(expected, actual);
}
@ParameterizedTest
@MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);
assertEquals(expected, actual);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java | package com.baeldung.algorithms.graphcycledetection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
class GraphCycleDetectionUnitTest {
@Test
public void givenGraph_whenCycleExists_thenReturnTrue() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexC, vertexA);
graph.addEdge(vertexD, vertexC);
assertTrue(graph.hasCycle());
}
@Test
void givenGraph_whenNoCycleExists_thenReturnFalse() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexA, vertexC);
graph.addEdge(vertexD, vertexC);
assertFalse(graph.hasCycle());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/automata/RtFiniteStateMachineLongRunningUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/automata/RtFiniteStateMachineLongRunningUnitTest.java | package com.baeldung.algorithms.automata;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RtFiniteStateMachineLongRunningUnitTest {
@Test
void acceptsSimplePair() {
String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
assertTrue(machine.canStop());
}
@Test
void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
assertTrue(machine.canStop());
}
@Test
void missingColon() {
String json = "{\"key\"\"value\"}";
assertThrows(IllegalArgumentException.class, () -> {
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
});
}
/**
* Builds a finite state machine to validate a simple
* Json object.
* @return
*/
private FiniteStateMachine buildJsonStateMachine() {
State first = new RtState();
State second = new RtState();
State third = new RtState();
State fourth = new RtState();
State fifth = new RtState();
State sixth = new RtState();
State seventh = new RtState();
State eighth = new RtState(true);
first.with(new RtTransition("{", second));
second.with(new RtTransition("\"", third));
//Add transitions with chars 0-9 and a-z
for (int i = 0; i < 26; i++) {
if (i < 10) {
third = third.with(new RtTransition(String.valueOf(i), third));
sixth = sixth.with(new RtTransition(String.valueOf(i), sixth));
}
third = third.with(new RtTransition(String.valueOf((char) ('a' + i)), third));
sixth = sixth.with(new RtTransition(String.valueOf((char) ('a' + i)), sixth));
}
third.with(new RtTransition("\"", fourth));
fourth.with(new RtTransition(":", fifth));
fifth.with(new RtTransition("\"", sixth));
sixth.with(new RtTransition("\"", seventh));
seventh.with(new RtTransition(",", second));
seventh.with(new RtTransition("}", eighth));
return new RtFiniteStateMachine(first);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java | package com.baeldung.algorithms.romannumerals;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class RomanArabicConverterUnitTest {
@Test
void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
String roman2018 = "MMXVIII";
int result = RomanArabicConverter.romanToArabic(roman2018);
assertThat(result).isEqualTo(2018);
}
@Test
void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
int arabic1999 = 1999;
String result = RomanArabicConverter.arabicToRoman(arabic1999);
assertThat(result).isEqualTo("MCMXCIX");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java | package com.baeldung.algorithms.analysis;
import org.junit.jupiter.api.Test;
class AnalysisRunnerLiveTest {
int n = 10;
int total = 0;
@Test
void whenConstantComplexity_thenConstantRuntime() {
System.out.println("**** n = " + n + " ****");
System.out.println();
// Constant Time
System.out.println("**** Constant time ****");
System.out.println("Hey - your input is: " + n);
System.out.println("Running time not dependent on input size!");
System.out.println();
}
@Test
void whenLogarithmicComplexity_thenLogarithmicRuntime() {
// Logarithmic Time
System.out.println("**** Logarithmic Time ****");
for (int i = 1; i < n; i = i * 2) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenLinearComplexity_thenLinearRuntime() {
// Linear Time
System.out.println("**** Linear Time ****");
for (int i = 0; i < n; i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenNLogNComplexity_thenNLogNRuntime() {
// N Log N Time
System.out.println("**** nlogn Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j < n; j = j * 2) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
total++;
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenQuadraticComplexity_thenQuadraticRuntime() {
// Quadratic Time
System.out.println("**** Quadratic Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
total++;
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenCubicComplexity_thenCubicRuntime() {
// Cubic Time
System.out.println("**** Cubic Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k);
total++;
}
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenExponentialComplexity_thenExponentialRuntime() {
// Exponential Time
System.out.println("**** Exponential Time ****");
total = 0;
for (
int i = 1; i <= Math.pow(2, n); i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
void whenFactorialComplexity_thenFactorialRuntime() {
// Factorial Time
System.out.println("**** Factorial Time ****");
total = 0;
for (
int i = 1; i <=
factorial(n); i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
}
static int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java | package com.baeldung.algorithms.enumstatemachine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class LeaveRequestStateUnitTest {
@Test
void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
LeaveRequestState state = LeaveRequestState.Escalated;
assertEquals( "Team Leader", state.responsiblePerson());
}
@Test
void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
LeaveRequestState state = LeaveRequestState.Approved;
assertEquals( "Department Manager" , state.responsiblePerson());
}
@Test
void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
LeaveRequestState state = LeaveRequestState.Submitted;
state = state.nextState();
assertEquals(LeaveRequestState.Escalated, state);
state = state.nextState();
assertEquals(LeaveRequestState.Approved, state);
state = state.nextState();
assertEquals(LeaveRequestState.Approved, state);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checktargetsum/CheckTargetSumUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checktargetsum/CheckTargetSumUnitTest.java | 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));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java | package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.jupiter.api.Test;
class RotateArrayUnitTest {
private RotateArray rotateArray = new RotateArray();
private int[] inputArray;
private int step;
@Test
void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
step = 4;
rotateArray.rotate(inputArray, step);
assertThat(inputArray).containsExactly(new int[] { 4, 5, 6, 7, 1, 2, 3 });
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java | package com.baeldung.algorithms.twopointertechnique;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TwoSumUnitTest {
private TwoSum twoSum = new TwoSum();
private int[] sortedArray;
private int targetValue;
@Test
void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
targetValue = 12;
assertTrue(twoSum.twoSumSlow(sortedArray, targetValue));
}
@Test
void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
targetValue = 20;
assertFalse(twoSum.twoSumSlow(sortedArray, targetValue));
}
@Test
void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
targetValue = 12;
assertTrue(twoSum.twoSum(sortedArray, targetValue));
}
@Test
void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
targetValue = 20;
assertFalse(twoSum.twoSum(sortedArray, targetValue));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java | package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class LinkedListFindMiddleUnitTest {
LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle();
@Test
void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
MyNode<String> head = createNodesList(8);
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("4");
head = createNodesList(9);
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("5");
}
private static MyNode<String> createNodesList(int n) {
MyNode<String> head = new MyNode<String>("1");
MyNode<String> current = head;
for (int i = 2; i <= n; i++) {
MyNode<String> newNode = new MyNode<String>(String.valueOf(i));
current.setNext(newNode);
current = newNode;
}
return head;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java | package com.baeldung.algorithms.checksortedlist;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SortedListCheckerUnitTest {
private List<String> sortedListOfString;
private List<String> unsortedListOfString;
private List<String> singletonList;
private List<Employee> employeesSortedByName;
private List<Employee> employeesNotSortedByName;
@BeforeEach
public void setUp() {
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
singletonList = Collections.singletonList("NY");
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
}
@Test
void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
}
@Test
void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
}
@Test
void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
}
@Test
void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
void givenSortedList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
}
@Test
void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
}
@Test
void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
}
@Test
void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
}
@Test
void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
}
@Test
void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
}
@Test
void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java | package com.baeldung.folding;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class FoldingHashUnitTest {
@Test
void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int value = hasher.hash("Java language", 2, 100_000);
assertEquals(value, 48933);
}
@Test
void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int java = hasher.hash("Java language", 2, 100_000);
final int vaja = hasher.hash("vaJa language", 2, 100_000);
assertTrue(java == vaja);
}
@Test
void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
assertArrayEquals(new int[] { 5 }, value);
}
@Test
void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
assertArrayEquals(new int[] { 1, 2, 3 }, value);
}
@Test
void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
assertArrayEquals(new int[] { 2, 3 }, value);
}
@Test
void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
assertArrayEquals(new int[] { 3, 4, 5 }, value);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java | package com.baeldung.counter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.baeldung.counter.CounterUtil.MutableInteger;
class CounterUnitTest {
@Test
void whenMapWithWrapperAsCounter_runsSuccessfully() {
Map<String, Integer> counterMap = new HashMap<>();
CounterUtil.counterWithWrapperObject(counterMap);
assertEquals(3, counterMap.get("China")
.intValue());
assertEquals(2, counterMap.get("India")
.intValue());
}
@Test
void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
Map<String, Long> counterMap = new HashMap<>();
CounterUtil.counterWithLambdaAndWrapper(counterMap);
assertEquals(3l, counterMap.get("China")
.longValue());
assertEquals(2l, counterMap.get("India")
.longValue());
}
@Test
void whenMapWithMutableIntegerCounter_runsSuccessfully() {
Map<String, MutableInteger> counterMap = new HashMap<>();
CounterUtil.counterWithMutableInteger(counterMap);
assertEquals(3, counterMap.get("China")
.getCount());
assertEquals(2, counterMap.get("India")
.getCount());
}
@Test
void whenMapWithPrimitiveArray_runsSuccessfully() {
Map<String, int[]> counterMap = new HashMap<>();
CounterUtil.counterWithPrimitiveArray(counterMap);
assertEquals(3, counterMap.get("China")[0]);
assertEquals(2, counterMap.get("India")[0]);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterStatistics.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterStatistics.java | package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import com.baeldung.counter.CounterUtil.MutableInteger;
@Fork(value = 1, warmups = 3)
@BenchmarkMode(Mode.All)
public class CounterStatistics {
private static final Map<String, Integer> counterMap = new HashMap<>();
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
static {
CounterUtil.COUNTRY_NAMES = new String[10000];
final String prefix = "NewString";
Random random = new Random();
for (int i=0; i<10000; i++) {
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
}
}
@Benchmark
public void wrapperAsCounter() {
CounterUtil.counterWithWrapperObject(counterMap);
}
@Benchmark
public void lambdaExpressionWithWrapper() {
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
}
@Benchmark
public void parallelStreamWithWrapper() {
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
}
@Benchmark
public void mutableIntegerAsCounter() {
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
}
@Benchmark
public void primitiveArrayAsCounter() {
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUtil.java | algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUtil.java | package com.baeldung.counter;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CounterUtil {
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
}
}
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
Stream.of(COUNTRY_NAMES)
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
Stream.of(COUNTRY_NAMES)
.parallel()
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static class MutableInteger {
int count;
public MutableInteger(int count) {
this.count = count;
}
public void increment() {
this.count++;
}
public int getCount() {
return this.count;
}
}
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
.increment();
}
}
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java | package com.baeldung.algorithms.printtriangles;
import org.apache.commons.lang3.StringUtils;
public class PrintTriangleExamples {
public static String printARightTriangle(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
for (int j = 1; j <= r; j++) {
result.append("*");
}
result.append(System.lineSeparator());
}
return result.toString();
}
public static String printAnIsoscelesTriangle(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
for (int sp = 1; sp <= N - r; sp++) {
result.append(" ");
}
for (int c = 1; c <= (r * 2) - 1; c++) {
result.append("*");
}
result.append(System.lineSeparator());
}
return result.toString();
}
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
result.append(StringUtils.repeat(' ', N - r));
result.append(StringUtils.repeat('*', 2 * r - 1));
result.append(System.lineSeparator());
}
return result.toString();
}
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
StringBuilder result = new StringBuilder();
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
for (int r = 0; r < N; r++) {
result.append(helperString.substring(r, N + 2 * r));
result.append(System.lineSeparator());
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(printARightTriangle(5));
System.out.println(printAnIsoscelesTriangle(5));
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java | package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Graph {
private List<Vertex> vertices;
public Graph() {
this.vertices = new ArrayList<>();
}
public Graph(List<Vertex> vertices) {
this.vertices = vertices;
}
public void addVertex(Vertex vertex) {
this.vertices.add(vertex);
}
public void addEdge(Vertex from, Vertex to) {
from.addNeighbour(to);
}
public boolean hasCycle() {
for (Vertex vertex : vertices) {
if (!vertex.isVisited() && hasCycle(vertex)) {
return true;
}
}
return false;
}
public boolean hasCycle(Vertex sourceVertex) {
sourceVertex.setBeingVisited(true);
for (Vertex neighbour : sourceVertex.getAdjacencyList()) {
if (neighbour.isBeingVisited()) {
// backward edge exists
return true;
} else if (!neighbour.isVisited() && hasCycle(neighbour)) {
return true;
}
}
sourceVertex.setBeingVisited(false);
sourceVertex.setVisited(true);
return false;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java | package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
private String label;
private boolean visited;
private boolean beingVisited;
private List<Vertex> adjacencyList;
public Vertex(String label) {
this.label = label;
this.adjacencyList = new ArrayList<>();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isBeingVisited() {
return beingVisited;
}
public void setBeingVisited(boolean beingVisited) {
this.beingVisited = beingVisited;
}
public List<Vertex> getAdjacencyList() {
return adjacencyList;
}
public void setAdjacencyList(List<Vertex> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public void addNeighbour(Vertex adjacent) {
this.adjacencyList.add(adjacent);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/LastFmService.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/LastFmService.java | package com.baeldung.algorithms.kmeans;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static java.util.stream.Collectors.toList;
public interface LastFmService {
@GET("/2.0/?method=chart.gettopartists&format=json&limit=50")
Call<Artists> topArtists(@Query("page") int page);
@GET("/2.0/?method=artist.gettoptags&format=json&limit=20&autocorrect=1")
Call<Tags> topTagsFor(@Query("artist") String artist);
@GET("/2.0/?method=chart.gettoptags&format=json&limit=100")
Call<TopTags> topTags();
/**
* HTTP interceptor to intercept all HTTP requests and add the API key to them.
*/
class Authenticator implements Interceptor {
private final String apiKey;
Authenticator(String apiKey) {
this.apiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain
.request()
.url()
.newBuilder()
.addQueryParameter("api_key", apiKey)
.build();
Request request = chain
.request()
.newBuilder()
.url(url)
.build();
return chain.proceed(request);
}
}
@JsonAutoDetect(fieldVisibility = ANY)
class TopTags {
private Map<String, Object> tags;
@SuppressWarnings("unchecked")
public Set<String> all() {
List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag");
return topTags
.stream()
.map(e -> ((String) e.get("name")))
.collect(Collectors.toSet());
}
}
@JsonAutoDetect(fieldVisibility = ANY)
class Tags {
@JsonProperty("toptags") private Map<String, Object> topTags;
@SuppressWarnings("unchecked")
public Map<String, Double> all() {
try {
Map<String, Double> all = new HashMap<>();
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
for (Map<String, Object> tag : tags) {
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
}
return all;
} catch (Exception e) {
return Collections.emptyMap();
}
}
}
@JsonAutoDetect(fieldVisibility = ANY)
class Artists {
private Map<String, Object> artists;
@SuppressWarnings("unchecked")
public List<String> all() {
try {
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
return artists
.stream()
.map(e -> ((String) e.get("name")))
.collect(toList());
} catch (Exception e) {
return Collections.emptyList();
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/LastFm.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/LastFm.java | package com.baeldung.algorithms.kmeans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import static java.util.stream.Collectors.toSet;
public class LastFm {
private static OkHttpClient okHttp = new OkHttpClient.Builder()
.addInterceptor(new LastFmService.Authenticator("put your API key here"))
.build();
private static Retrofit retrofit = new Retrofit.Builder()
.client(okHttp)
.addConverterFactory(JacksonConverterFactory.create())
.baseUrl("http://ws.audioscrobbler.com/")
.build();
private static LastFmService lastFm = retrofit.create(LastFmService.class);
private static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws IOException {
List<String> artists = getTop100Artists();
Set<String> tags = getTop100Tags();
List<Record> records = datasetWithTaggedArtists(artists, tags);
Map<Centroid, List<Record>> clusters = KMeans.fit(records, 7, new EuclideanDistance(), 1000);
// Print the cluster configuration
clusters.forEach((key, value) -> {
System.out.println("------------------------------ CLUSTER -----------------------------------");
System.out.println(sortedCentroid(key));
String members = String.join(", ", value
.stream()
.map(Record::getDescription)
.collect(toSet()));
System.out.print(members);
System.out.println();
System.out.println();
});
Map<String, Object> json = convertToD3CompatibleMap(clusters);
System.out.println(mapper.writeValueAsString(json));
}
private static Map<String, Object> convertToD3CompatibleMap(Map<Centroid, List<Record>> clusters) {
Map<String, Object> json = new HashMap<>();
json.put("name", "Musicians");
List<Map<String, Object>> children = new ArrayList<>();
clusters.forEach((key, value) -> {
Map<String, Object> child = new HashMap<>();
child.put("name", dominantGenre(sortedCentroid(key)));
List<Map<String, String>> nested = new ArrayList<>();
for (Record record : value) {
nested.add(Collections.singletonMap("name", record.getDescription()));
}
child.put("children", nested);
children.add(child);
});
json.put("children", children);
return json;
}
private static String dominantGenre(Centroid centroid) {
return centroid
.getCoordinates()
.keySet()
.stream()
.limit(2)
.collect(Collectors.joining(", "));
}
private static Centroid sortedCentroid(Centroid key) {
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
.getCoordinates()
.entrySet());
entries.sort((e1, e2) -> e2
.getValue()
.compareTo(e1.getValue()));
Map<String, Double> sorted = new LinkedHashMap<>();
for (Map.Entry<String, Double> entry : entries) {
sorted.put(entry.getKey(), entry.getValue());
}
return new Centroid(sorted);
}
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
List<Record> records = new ArrayList<>();
for (String artist : artists) {
Map<String, Double> tags = lastFm
.topTagsFor(artist)
.execute()
.body()
.all();
// Only keep popular tags.
tags
.entrySet()
.removeIf(e -> !topTags.contains(e.getKey()));
records.add(new Record(artist, tags));
}
return records;
}
private static Set<String> getTop100Tags() throws IOException {
return lastFm
.topTags()
.execute()
.body()
.all();
}
private static List<String> getTop100Artists() throws IOException {
List<String> artists = new ArrayList<>();
for (int i = 1; i <= 2; i++) {
artists.addAll(lastFm
.topArtists(i)
.execute()
.body()
.all());
}
return artists;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/KMeans.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/KMeans.java | package com.baeldung.algorithms.kmeans;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
/**
* Encapsulates an implementation of KMeans clustering algorithm.
*
* @author Ali Dehghani
*/
public class KMeans {
private KMeans() {
throw new IllegalAccessError("You shouldn't call this constructor");
}
/**
* Will be used to generate random numbers.
*/
private static final Random random = new Random();
/**
* Performs the K-Means clustering algorithm on the given dataset.
*
* @param records The dataset.
* @param k Number of Clusters.
* @param distance To calculate the distance between two items.
* @param maxIterations Upper bound for the number of iterations.
* @return K clusters along with their features.
*/
public static Map<Centroid, List<Record>> fit(List<Record> records, int k, Distance distance, int maxIterations) {
applyPreconditions(records, k, distance, maxIterations);
List<Centroid> centroids = randomCentroids(records, k);
Map<Centroid, List<Record>> clusters = new HashMap<>();
Map<Centroid, List<Record>> lastState = new HashMap<>();
// iterate for a pre-defined number of times
for (int i = 0; i < maxIterations; i++) {
boolean isLastIteration = i == maxIterations - 1;
// in each iteration we should find the nearest centroid for each record
for (Record record : records) {
Centroid centroid = nearestCentroid(record, centroids, distance);
assignToCluster(clusters, record, centroid);
}
// if the assignment does not change, then the algorithm terminates
boolean shouldTerminate = isLastIteration || clusters.equals(lastState);
lastState = clusters;
if (shouldTerminate) {
break;
}
// at the end of each iteration we should relocate the centroids
centroids = relocateCentroids(clusters);
clusters = new HashMap<>();
}
return lastState;
}
/**
* Move all cluster centroids to the average of all assigned features.
*
* @param clusters The current cluster configuration.
* @return Collection of new and relocated centroids.
*/
private static List<Centroid> relocateCentroids(Map<Centroid, List<Record>> clusters) {
return clusters
.entrySet()
.stream()
.map(e -> average(e.getKey(), e.getValue()))
.collect(toList());
}
/**
* Moves the given centroid to the average position of all assigned features. If
* the centroid has no feature in its cluster, then there would be no need for a
* relocation. Otherwise, for each entry we calculate the average of all records
* first by summing all the entries and then dividing the final summation value by
* the number of records.
*
* @param centroid The centroid to move.
* @param records The assigned features.
* @return The moved centroid.
*/
private static Centroid average(Centroid centroid, List<Record> records) {
// if this cluster is empty, then we shouldn't move the centroid
if (records == null || records.isEmpty()) {
return centroid;
}
// Since some records don't have all possible attributes, we initialize
// average coordinates equal to current centroid coordinates
Map<String, Double> average = centroid.getCoordinates();
// The average function works correctly if we clear all coordinates corresponding
// to present record attributes
records
.stream()
.flatMap(e -> e
.getFeatures()
.keySet()
.stream())
.forEach(k -> average.put(k, 0.0));
for (Record record : records) {
record
.getFeatures()
.forEach((k, v) -> average.compute(k, (k1, currentValue) -> v + currentValue));
}
average.forEach((k, v) -> average.put(k, v / records.size()));
return new Centroid(average);
}
/**
* Assigns a feature vector to the given centroid. If this is the first assignment for this centroid,
* first we should create the list.
*
* @param clusters The current cluster configuration.
* @param record The feature vector.
* @param centroid The centroid.
*/
private static void assignToCluster(Map<Centroid, List<Record>> clusters, Record record, Centroid centroid) {
clusters.compute(centroid, (key, list) -> {
if (list == null) {
list = new ArrayList<>();
}
list.add(record);
return list;
});
}
/**
* With the help of the given distance calculator, iterates through centroids and finds the
* nearest one to the given record.
*
* @param record The feature vector to find a centroid for.
* @param centroids Collection of all centroids.
* @param distance To calculate the distance between two items.
* @return The nearest centroid to the given feature vector.
*/
private static Centroid nearestCentroid(Record record, List<Centroid> centroids, Distance distance) {
double minimumDistance = Double.MAX_VALUE;
Centroid nearest = null;
for (Centroid centroid : centroids) {
double currentDistance = distance.calculate(record.getFeatures(), centroid.getCoordinates());
if (currentDistance < minimumDistance) {
minimumDistance = currentDistance;
nearest = centroid;
}
}
return nearest;
}
/**
* Generates k random centroids. Before kicking-off the centroid generation process,
* first we calculate the possible value range for each attribute. Then when
* we're going to generate the centroids, we generate random coordinates in
* the [min, max] range for each attribute.
*
* @param records The dataset which helps to calculate the [min, max] range for
* each attribute.
* @param k Number of clusters.
* @return Collections of randomly generated centroids.
*/
private static List<Centroid> randomCentroids(List<Record> records, int k) {
List<Centroid> centroids = new ArrayList<>();
Map<String, Double> maxs = new HashMap<>();
Map<String, Double> mins = new HashMap<>();
for (Record record : records) {
record
.getFeatures()
.forEach((key, value) -> {
// compares the value with the current max and choose the bigger value between them
maxs.compute(key, (k1, max) -> max == null || value > max ? value : max);
// compare the value with the current min and choose the smaller value between them
mins.compute(key, (k1, min) -> min == null || value < min ? value : min);
});
}
Set<String> attributes = records
.stream()
.flatMap(e -> e
.getFeatures()
.keySet()
.stream())
.collect(toSet());
for (int i = 0; i < k; i++) {
Map<String, Double> coordinates = new HashMap<>();
for (String attribute : attributes) {
double max = maxs.get(attribute);
double min = mins.get(attribute);
coordinates.put(attribute, random.nextDouble() * (max - min) + min);
}
centroids.add(new Centroid(coordinates));
}
return centroids;
}
private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) {
if (records == null || records.isEmpty()) {
throw new IllegalArgumentException("The dataset can't be empty");
}
if (k <= 1) {
throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster");
}
if (distance == null) {
throw new IllegalArgumentException("The distance calculator is required");
}
if (maxIterations <= 0) {
throw new IllegalArgumentException("Max iterations should be a positive number");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Distance.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Distance.java | package com.baeldung.algorithms.kmeans;
import java.util.Map;
/**
* Defines a contract to calculate distance between two feature vectors. The less the
* calculated distance, the more two items are similar to each other.
*/
public interface Distance {
/**
* Calculates the distance between two feature vectors.
*
* @param f1 The first set of features.
* @param f2 The second set of features.
* @return Calculated distance.
* @throws IllegalArgumentException If the given feature vectors are invalid.
*/
double calculate(Map<String, Double> f1, Map<String, Double> f2);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Record.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Record.java | package com.baeldung.algorithms.kmeans;
import java.util.Map;
import java.util.Objects;
/**
* Encapsulates all feature values for a few attributes. Optionally each record
* can be described with the {@link #description} field.
*/
public class Record {
/**
* The record description. For example, this can be the artist name for the famous musician
* example.
*/
private final String description;
/**
* Encapsulates all attributes and their corresponding values, i.e. features.
*/
private final Map<String, Double> features;
public Record(String description, Map<String, Double> features) {
this.description = description;
this.features = features;
}
public Record(Map<String, Double> features) {
this("", features);
}
public String getDescription() {
return description;
}
public Map<String, Double> getFeatures() {
return features;
}
@Override
public String toString() {
String prefix = description == null || description
.trim()
.isEmpty() ? "Record" : description;
return prefix + ": " + features;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
}
@Override
public int hashCode() {
return Objects.hash(getDescription(), getFeatures());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/EuclideanDistance.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/EuclideanDistance.java | package com.baeldung.algorithms.kmeans;
import java.util.Map;
/**
* Calculates the distance between two items using the Euclidean formula.
*/
public class EuclideanDistance implements Distance {
@Override
public double calculate(Map<String, Double> f1, Map<String, Double> f2) {
if (f1 == null || f2 == null) {
throw new IllegalArgumentException("Feature vectors can't be null");
}
double sum = 0;
for (String key : f1.keySet()) {
Double v1 = f1.get(key);
Double v2 = f2.get(key);
if (v1 != null && v2 != null) sum += Math.pow(v1 - v2, 2);
}
return Math.sqrt(sum);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Errors.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Errors.java | package com.baeldung.algorithms.kmeans;
import java.util.List;
import java.util.Map;
/**
* Encapsulates methods to calculates errors between centroid and the cluster members.
*/
public class Errors {
public static double sse(Map<Centroid, List<Record>> clustered, Distance distance) {
double sum = 0;
for (Map.Entry<Centroid, List<Record>> entry : clustered.entrySet()) {
Centroid centroid = entry.getKey();
for (Record record : entry.getValue()) {
double d = distance.calculate(centroid.getCoordinates(), record.getFeatures());
sum += Math.pow(d, 2);
}
}
return sum;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Centroid.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/kmeans/Centroid.java | package com.baeldung.algorithms.kmeans;
import java.util.Map;
import java.util.Objects;
/**
* Encapsulates all coordinates for a particular cluster centroid.
*/
public class Centroid {
/**
* The centroid coordinates.
*/
private final Map<String, Double> coordinates;
public Centroid(Map<String, Double> coordinates) {
this.coordinates = coordinates;
}
public Map<String, Double> getCoordinates() {
return coordinates;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Centroid centroid = (Centroid) o;
return Objects.equals(getCoordinates(), centroid.getCoordinates());
}
@Override
public int hashCode() {
return Objects.hash(getCoordinates());
}
@Override
public String toString() {
return "Centroid " + coordinates;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtState.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtState.java | package com.baeldung.algorithms.automata;
import java.util.ArrayList;
import java.util.List;
/**
* State in a finite state machine.
*/
public final class RtState implements State {
private List<Transition> transitions;
private boolean isFinal;
public RtState() {
this(false);
}
public RtState(final boolean isFinal) {
this.transitions = new ArrayList<>();
this.isFinal = isFinal;
}
public State transit(final CharSequence c) {
return transitions
.stream()
.filter(t -> t.isPossible(c))
.map(Transition::state)
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
}
public boolean isFinal() {
return this.isFinal;
}
@Override
public State with(Transition tr) {
this.transitions.add(tr);
return this;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/State.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/State.java | package com.baeldung.algorithms.automata;
/**
* State. Part of a finite state machine.
*/
public interface State {
/**
* Add a Transition to this state.
* @param tr Given transition.
* @return Modified State.
*/
State with(final Transition tr);
/**
* Follow one of the transitions, to get
* to the next state.
* @param c Character.
* @return State.
* @throws IllegalStateException if the char is not accepted.
*/
State transit(final CharSequence c);
/**
* Can the automaton stop on this state?
* @return true or false
*/
boolean isFinal();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/Transition.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/Transition.java | package com.baeldung.algorithms.automata;
/**
* Transition in a finite State machine.
*/
public interface Transition {
/**
* Is the transition possible with the given character?
* @param c char.
* @return true or false.
*/
boolean isPossible(final CharSequence c);
/**
* The state to which this transition leads.
* @return State.
*/
State state();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java | package com.baeldung.algorithms.automata;
/**
* Finite state machine.
*/
public interface FiniteStateMachine {
/**
* Follow a transition, switch the state of the machine.
* @param c Char.
* @return A new finite state machine with the new state.
*/
FiniteStateMachine switchState(final CharSequence c);
/**
* Is the current state a final one?
* @return true or false.
*/
boolean canStop();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java | package com.baeldung.algorithms.automata;
/**
* Default implementation of a finite state machine.
* This class is immutable and thread-safe.
*/
public final class RtFiniteStateMachine implements FiniteStateMachine {
/**
* Current state.
*/
private State current;
/**
* Ctor.
* @param initial Initial state of this machine.
*/
public RtFiniteStateMachine(final State initial) {
this.current = initial;
}
public FiniteStateMachine switchState(final CharSequence c) {
return new RtFiniteStateMachine(this.current.transit(c));
}
public boolean canStop() {
return this.current.isFinal();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtTransition.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/automata/RtTransition.java | package com.baeldung.algorithms.automata;
/**
* Transition in finite state machine.
*/
public final class RtTransition implements Transition {
private String rule;
private State next;
/**
* Ctor.
* @param rule Rule that a character has to meet
* in order to get to the next state.
* @param next Next state.
*/
public RtTransition (String rule, State next) {
this.rule = rule;
this.next = next;
}
public State state() {
return this.next;
}
public boolean isPossible(CharSequence c) {
return this.rule.equalsIgnoreCase(String.valueOf(c));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java | package com.baeldung.algorithms.romannumerals;
import java.util.List;
class RomanArabicConverter {
public static int romanToArabic(String input) {
String romanNumeral = input.toUpperCase();
int result = 0;
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
int i = 0;
while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) {
RomanNumeral symbol = romanNumerals.get(i);
if (romanNumeral.startsWith(symbol.name())) {
result += symbol.getValue();
romanNumeral = romanNumeral.substring(symbol.name().length());
} else {
i++;
}
}
if (romanNumeral.length() > 0) {
throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral");
}
return result;
}
public static String arabicToRoman(int number) {
if ((number <= 0) || (number > 4000)) {
throw new IllegalArgumentException(number + " is not in range (0,4000]");
}
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
int i = 0;
StringBuilder sb = new StringBuilder();
while (number > 0 && i < romanNumerals.size()) {
RomanNumeral currentSymbol = romanNumerals.get(i);
if (currentSymbol.getValue() <= number) {
sb.append(currentSymbol.name());
number -= currentSymbol.getValue();
} else {
i++;
}
}
return sb.toString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java | package com.baeldung.algorithms.romannumerals;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
enum RomanNumeral {
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
private int value;
RomanNumeral(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static List<RomanNumeral> getReverseSortedValues() {
return Arrays.stream(values())
.sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed())
.collect(Collectors.toList());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java | package com.baeldung.algorithms.enumstatemachine;
public enum LeaveRequestState {
Submitted {
@Override
public LeaveRequestState nextState() {
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
return Escalated;
}
@Override
public String responsiblePerson() {
return "Employee";
}
},
Escalated {
@Override
public LeaveRequestState nextState() {
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
return Approved;
}
@Override
public String responsiblePerson() {
return "Team Leader";
}
},
Approved {
@Override
public LeaveRequestState nextState() {
System.out.println("Approving the Leave Request.");
return this;
}
@Override
public String responsiblePerson() {
return "Department Manager";
}
};
public abstract String responsiblePerson();
public abstract LeaveRequestState nextState();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checktargetsum/CheckTargetSum.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checktargetsum/CheckTargetSum.java | 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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java | package com.baeldung.algorithms.twopointertechnique;
public class RotateArray {
public void rotate(int[] input, int step) {
step %= input.length;
reverse(input, 0, input.length - 1);
reverse(input, 0, step - 1);
reverse(input, step, input.length - 1);
}
private void reverse(int[] input, int start, int end) {
while (start < end) {
int temp = input[start];
input[start] = input[end];
input[end] = temp;
start++;
end--;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java | package com.baeldung.algorithms.twopointertechnique;
public class TwoSum {
public boolean twoSum(int[] input, int targetValue) {
int pointerOne = 0;
int pointerTwo = input.length - 1;
while (pointerOne < pointerTwo) {
int sum = input[pointerOne] + input[pointerTwo];
if (sum == targetValue) {
return true;
} else if (sum < targetValue) {
pointerOne++;
} else {
pointerTwo--;
}
}
return false;
}
public boolean twoSumSlow(int[] input, int targetValue) {
for (int i = 0; i < input.length; i++) {
for (int j = 1; j < input.length; j++) {
if (input[i] + input[j] == targetValue) {
return true;
}
}
}
return false;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java | package com.baeldung.algorithms.twopointertechnique;
public class MyNode<E> {
MyNode<E> next;
E data;
public MyNode(E value) {
data = value;
next = null;
}
public MyNode(E value, MyNode<E> n) {
data = value;
next = n;
}
public void setNext(MyNode<E> n) {
next = n;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java | package com.baeldung.algorithms.twopointertechnique;
public class LinkedListFindMiddle {
public <T> T findMiddle(MyNode<T> head) {
MyNode<T> slowPointer = head;
MyNode<T> fastPointer = head;
while (fastPointer.next != null && fastPointer.next.next != null) {
fastPointer = fastPointer.next.next;
slowPointer = slowPointer.next;
}
return slowPointer.data;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/Employee.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/Employee.java | package com.baeldung.algorithms.checksortedlist;
public class Employee {
long id;
String name;
public Employee() {
}
public Employee(long id, String name) {
super();
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java | package com.baeldung.algorithms.checksortedlist;
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Comparators;
import com.google.common.collect.Ordering;;
public class SortedListChecker {
private SortedListChecker() {
throw new AssertionError();
}
public static boolean checkIfSortedUsingIterativeApproach(List<String> listOfStrings) {
if (isEmpty(listOfStrings) || listOfStrings.size() == 1) {
return true;
}
Iterator<String> iter = listOfStrings.iterator();
String current, previous = iter.next();
while (iter.hasNext()) {
current = iter.next();
if (previous.compareTo(current) > 0) {
return false;
}
previous = current;
}
return true;
}
public static boolean checkIfSortedUsingIterativeApproach(List<Employee> employees, Comparator<Employee> employeeComparator) {
if (isEmpty(employees) || employees.size() == 1) {
return true;
}
Iterator<Employee> iter = employees.iterator();
Employee current, previous = iter.next();
while (iter.hasNext()) {
current = iter.next();
if (employeeComparator.compare(previous, current) > 0) {
return false;
}
previous = current;
}
return true;
}
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) {
return isSortedRecursive(listOfStrings, listOfStrings.size());
}
public static boolean isSortedRecursive(List<String> listOfStrings, int index) {
if (index < 2) {
return true;
} else if (listOfStrings.get(index - 2)
.compareTo(listOfStrings.get(index - 1)) > 0) {
return false;
} else {
return isSortedRecursive(listOfStrings, index - 1);
}
}
public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) {
return Ordering.<String> natural()
.isOrdered(listOfStrings);
}
public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) {
return Ordering.from(employeeComparator)
.isOrdered(employees);
}
public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) {
return Ordering.<String> natural()
.nullsLast()
.isOrdered(listOfStrings);
}
public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) {
return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java | package com.baeldung.folding;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Calculate a hash value for the strings using the folding technique.
*
* The implementation serves only to the illustration purposes and is far
* from being the most efficient.
*
* @author A.Shcherbakov
*
*/
public class FoldingHash {
/**
* Calculate the hash value of a given string.
*
* @param str Assume it is not null
* @param groupSize the group size in the folding technique
* @param maxValue defines a max value that the hash may acquire (exclusive)
* @return integer value from 0 (inclusive) to maxValue (exclusive)
*/
public int hash(String str, int groupSize, int maxValue) {
final int[] codes = this.toAsciiCodes(str);
return IntStream.range(0, str.length())
.filter(i -> i % groupSize == 0)
.mapToObj(i -> extract(codes, i, groupSize))
.map(block -> concatenate(block))
.reduce(0, (a, b) -> (a + b) % maxValue);
}
/**
* Returns a new array of given length whose elements are take from
* the original one starting from the offset.
*
* If the original array has not enough elements, the returning array will contain
* element from the offset till the end of the original array.
*
* @param numbers original array. Assume it is not null.
* @param offset index of the element to start from. Assume it is less than the size of the array
* @param length max size of the resulting array
* @return
*/
public int[] extract(int[] numbers, int offset, int length) {
final int defect = numbers.length - (offset + length);
final int s = defect < 0 ? length + defect : length;
int[] result = new int[s];
for (int index = 0; index < s; index++) {
result[index] = numbers[index + offset];
}
return result;
}
/**
* Concatenate the numbers into a single number as if they were strings.
* Assume that the procedure does not suffer from the overflow.
* @param numbers integers to concatenate
* @return
*/
public int concatenate(int[] numbers) {
final String merged = IntStream.of(numbers)
.mapToObj(number -> "" + number)
.collect(Collectors.joining());
return Integer.parseInt(merged, 10);
}
/**
* Convert the string into its characters' ASCII codes.
* @param str input string
* @return
*/
private int[] toAsciiCodes(String str) {
return str.chars()
.toArray();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java | algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java | package com.baeldung.folding;
/**
* Code snippet for article "A Guide to the Folding Technique".
*
* @author A.Shcherbakov
*
*/
public class Main {
public static void main(String... arg) {
FoldingHash hasher = new FoldingHash();
final String str = "Java language";
System.out.println(hasher.hash(str, 2, 100_000));
System.out.println(hasher.hash(str, 3, 1_000));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/primeundernumber/LargestPrimeFinderUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/primeundernumber/LargestPrimeFinderUnitTest.java | package com.baeldung.algorithms.primeundernumber;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LargestPrimeFinderUnitTest {
@Test
public void givenNormalCases_whenFindPrime_ThenFoundResult() {
assertEquals(7, LargestPrimeFinder.findByBruteForce(10));
assertEquals(97, LargestPrimeFinder.findByBruteForce(100));
assertEquals(7, LargestPrimeFinder.findBySieveOfEratosthenes(10));
assertEquals(97, LargestPrimeFinder.findBySieveOfEratosthenes(100));
}
@Test
public void givenEdgeCases_whenFindPrime_ThenNotFoundResult() {
assertEquals(-1, LargestPrimeFinder.findByBruteForce(0));
assertEquals(-1, LargestPrimeFinder.findByBruteForce(1));
assertEquals(-1, LargestPrimeFinder.findByBruteForce(2));
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(0));
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(1));
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(2));
}
@Test
public void givenLargeInput_whenFindPrime_ThenFoundResult() {
assertEquals(99991, LargestPrimeFinder.findByBruteForce(100000));
assertEquals(99991, LargestPrimeFinder.findBySieveOfEratosthenes(100000));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsUnitTest.java | 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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java | package com.baeldung.algorithms.luhn;
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 org.junit.jupiter.api.Test;
class LuhnCheckerUnitTest {
@Test
void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
String cardNumber = "8649";
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertTrue(result);
}
@Test
void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
String cardNumber = "8642";
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertFalse(result);
}
@Test
void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "0505050505050505";
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertTrue(result);
}
@Test
void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "75757575757575";
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertTrue(result);
}
@Test
void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
assertEquals(0,LuhnChecker.doubleAndSumDigits(0));
assertEquals(2,LuhnChecker.doubleAndSumDigits(1));
assertEquals(4, LuhnChecker.doubleAndSumDigits(2));
assertEquals(6, LuhnChecker.doubleAndSumDigits(3));
assertEquals(8, LuhnChecker.doubleAndSumDigits(4));
assertEquals(1, LuhnChecker.doubleAndSumDigits(5));
assertEquals(3, LuhnChecker.doubleAndSumDigits(6));
assertEquals(5, LuhnChecker.doubleAndSumDigits(7));
assertEquals(7, LuhnChecker.doubleAndSumDigits(8));
assertEquals(9, LuhnChecker.doubleAndSumDigits(9));
}
@Test
void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
String cardNumber = "test";
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertFalse(result);
}
@Test
void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
String cardNumber = null;
boolean result = LuhnChecker.checkLuhn(cardNumber);
assertFalse(result);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/stringrotation/StringRotationUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/stringrotation/StringRotationUnitTest.java | package com.baeldung.algorithms.stringrotation;
import static com.baeldung.algorithms.stringrotation.StringRotation.doubledOriginContainsRotation;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingCommonStartWithOrigin;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingQueue;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingSuffixAndPrefix;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class StringRotationUnitTest {
@Test
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenIsRotation() {
assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenNoRotation() {
assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
assertTrue(isRotationUsingQueue("abcd", "cdab"));
assertTrue(isRotationUsingQueue("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
assertFalse(isRotationUsingQueue("abcd", "bbbb"));
assertFalse(isRotationUsingQueue("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/weightedaverage/WeightedAverageUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/weightedaverage/WeightedAverageUnitTest.java | package com.baeldung.algorithms.weightedaverage;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WeightedAverageUnitTest {
private List<Values> values = Arrays.asList(
new Values(1, 10),
new Values(3, 20),
new Values(5, 30),
new Values(7, 50),
new Values(9, 40)
);
private Double expected = 6.2;
@Test
void twoPass() {
double top = values.stream()
.mapToDouble(v -> v.value * v.weight)
.sum();
double bottom = values.stream()
.mapToDouble(v -> v.weight)
.sum();
double result = top / bottom;
assertEquals(expected, result);
}
@Test
void onePass() {
double top = 0;
double bottom = 0;
for (Values v : values) {
top += (v.value * v.weight);
bottom += v.weight;
}
double result = top / bottom;
assertEquals(expected, result);
}
@Test
void expanding() {
double result = values.stream()
.flatMap(v -> Collections.nCopies(v.weight, v.value).stream())
.mapToInt(v -> v)
.average()
.getAsDouble();
assertEquals(expected, result);
}
@Test
void reduce() {
class WeightedAverage {
final double top;
final double bottom;
public WeightedAverage(double top, double bottom) {
this.top = top;
this.bottom = bottom;
}
double average() {
return top / bottom;
}
}
double result = values.stream()
.reduce(new WeightedAverage(0, 0),
(acc, next) -> new WeightedAverage(
acc.top + (next.value * next.weight),
acc.bottom + next.weight),
(left, right) -> new WeightedAverage(
left.top + right.top,
left.bottom + right.bottom))
.average();
assertEquals(expected, result);
}
@Test
void customCollector() {
class WeightedAverage implements Collector<Values, WeightedAverage.RunningTotals, Double> {
class RunningTotals {
double top;
double bottom;
public RunningTotals() {
this.top = 0;
this.bottom = 0;
}
}
@Override
public Supplier<RunningTotals> supplier() {
return RunningTotals::new;
}
@Override
public BiConsumer<RunningTotals, Values> accumulator() {
return (current, next) -> {
current.top += (next.value * next.weight);
current.bottom += next.weight;
};
}
@Override
public BinaryOperator<RunningTotals> combiner() {
return (left, right) -> {
left.top += right.top;
left.bottom += right.bottom;
return left;
};
}
@Override
public Function<RunningTotals, Double> finisher() {
return rt -> rt.top / rt.bottom;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.singleton(Characteristics.UNORDERED);
}
}
double result = values.stream()
.collect(new WeightedAverage());
assertEquals(expected, result);
}
private static class Values {
int value;
int weight;
public Values(int value, int weight) {
this.value = value;
this.weight = weight;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java | package com.baeldung.algorithms.pixelarray;
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
import static org.junit.Assert.*;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class GetPixelArrayUnitTest {
@Test
public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
BufferedImage sampleImage = null;
try {
sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
} catch (IOException e) {
throw new RuntimeException(e);
}
int[][] firstResult = get2DPixelArraySlow(sampleImage);
int[][] secondResult = get2DPixelArrayFast(sampleImage);
assertTrue(Arrays.deepEquals(firstResult, secondResult));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/findmissingnumber/FindMissingNumberUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/findmissingnumber/FindMissingNumberUnitTest.java | package com.baeldung.algorithms.findmissingnumber;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class FindMissingNumberUnitTest {
private int[] numbers;
int N;
@BeforeEach
void setup() {
numbers = new int[] { 1, 4, 5, 2, 7, 8, 6, 9 };
N = numbers.length + 1;
}
@Test
void givenIntegersArray_whenUseArithmeticSumToFindMissingNumber_thenGetMissingNumber() {
int expectedSum = (N * (N + 1)) / 2;
int actualSum = Arrays.stream(numbers).sum();
int missingNumber = expectedSum - actualSum;
assertEquals(3, missingNumber);
}
@Test
void givenIntegersArray_whenUseXorToFindMissingNumber_thenGetMissingNumber() {
int xorValue = IntStream.rangeClosed(1, N).reduce(0, (a, b) -> a ^ b);
xorValue = Arrays.stream(numbers).reduce(xorValue, (x, y) -> x ^ y);
assertEquals(3, xorValue);
}
@Test
void givenIntegersArray_whenUseSortingToFindMissingNumber_thenGetMissingNumber() {
Arrays.sort(numbers);
int missingNumber = -1;
for (int index = 0; index < numbers.length; index++) {
if (numbers[index] != index + 1) {
missingNumber = index + 1;
break;
}
}
assertEquals(3, missingNumber);
}
@Test
void givenIntegersArray_whenTrackUsingBooleanArrayToFindMissingNumber_thenGetMissingNumber() {
boolean[] present = new boolean[N];
int missingNumber = -1;
Arrays.stream(numbers).forEach(number -> present[number - 1] = true);
for (int index = 0; index < present.length; index++) {
if (!present[index]) {
missingNumber = index + 1;
break;
}
}
assertEquals(3, missingNumber);
}
@Test
void givenIntegersArray_whenUseBitSetToFindMissingNumber_thenGetMissingNumber() {
BitSet bitSet = new BitSet(N);
for (int num : numbers) {
bitSet.set(num);
}
int missingNumber = bitSet.nextClearBit(1);
assertEquals(3, missingNumber);
}
@Test
void givenIntegersArrayWithMultipleMissingNumbers_whenUseBitSetToFindMultipleMissingNumbers_thenGetMultipleMissingNumbers() {
int[] numbersWithMultipleMissing = new int[] { 1, 5, 2, 8, 9 };
int N = Arrays.stream(numbersWithMultipleMissing)
.max()
.getAsInt();
BitSet allBitSet = new BitSet(N + 1);
IntStream.rangeClosed(1, N)
.forEach(allBitSet::set);
BitSet presentBitSet = new BitSet(N + 1);
Arrays.stream(numbersWithMultipleMissing)
.forEach(presentBitSet::set);
allBitSet.and(presentBitSet);
List<Integer> result = IntStream.rangeClosed(1, N)
.filter(i -> !allBitSet.get(i))
.boxed()
.sorted()
.collect(Collectors.toList());
assertEquals(result, Arrays.asList(3, 4, 6, 7));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounterUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounterUnitTest.java | package com.baeldung.algorithms.uniquedigit;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UniqueDigitCounterUnitTest {
@Test
public void givenNotNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(3, UniqueDigitCounter.countWithSet(122333));
assertEquals(1, UniqueDigitCounter.countWithSet(0));
assertEquals(2, UniqueDigitCounter.countWithSet(101));
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(122333));
assertEquals(1, UniqueDigitCounter.countWithBitManipulation(0));
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(101));
assertEquals(3, UniqueDigitCounter.countWithStreamApi(122333));
assertEquals(1, UniqueDigitCounter.countWithStreamApi(0));
assertEquals(2, UniqueDigitCounter.countWithStreamApi(101));
}
@Test
public void givenNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(3, UniqueDigitCounter.countWithSet(-122333));
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(-122333));
assertEquals(3, UniqueDigitCounter.countWithStreamApi(-122333));
}
@Test
public void givenLargeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(2, UniqueDigitCounter.countWithSet(1000000000));
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(1000000000));
assertEquals(2, UniqueDigitCounter.countWithStreamApi(1000000000));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java | algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java | package com.baeldung.algorithms.rotatearray;
import static com.baeldung.algorithms.rotatearray.RotateArray.bruteForce;
import static com.baeldung.algorithms.rotatearray.RotateArray.cyclicReplacement;
import static com.baeldung.algorithms.rotatearray.RotateArray.reverse;
import static com.baeldung.algorithms.rotatearray.RotateArray.withExtraArray;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class RotateArrayUnitTest {
private final int[] arr = { 1, 2, 3, 4, 5, 6 };
private final int rotationLtArrayLength = 1;
private final int rotationGtArrayLength = arr.length + 2;
private final int[] ltArrayLengthRotation = { 6, 1, 2, 3, 4, 5 };
private final int[] gtArrayLengthRotation = { 5, 6, 1, 2, 3, 4 };
@Test
void givenInputArray_whenNoRotationOrEmptyArray_thenThrowIllegalArgumentException() {
final int noRotation = 0;
final int someRotation = arr.length - 1;
assertThrows(IllegalArgumentException.class, () -> bruteForce(arr, noRotation));
assertThrows(IllegalArgumentException.class, () -> withExtraArray(arr, noRotation));
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(arr, noRotation));
assertThrows(IllegalArgumentException.class, () -> reverse(arr, noRotation));
assertThrows(IllegalArgumentException.class, () -> bruteForce(null, someRotation));
assertThrows(IllegalArgumentException.class, () -> withExtraArray(null, someRotation));
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(null, someRotation));
assertThrows(IllegalArgumentException.class, () -> reverse(null, someRotation));
}
@Test
void givenInputArray_whenUseBruteForceRotationLtArrayLength_thenRotateArrayOk() {
bruteForce(arr, rotationLtArrayLength);
assertArrayEquals(ltArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseBruteForceRotationGtArrayLength_thenRotateArrayOk() {
bruteForce(arr, rotationGtArrayLength);
assertArrayEquals(gtArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseBruteForceRotationEqArrayLength_thenDoNothing() {
int[] expected = arr.clone();
bruteForce(arr, arr.length);
assertArrayEquals(expected, arr);
}
@Test
void givenInputArray_whenUseExtraArrayRotationLtArrayLength_thenRotateArrayOk() {
withExtraArray(arr, rotationLtArrayLength);
assertArrayEquals(ltArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseExtraArrayRotationGtArrayLength_thenRotateArrayOk() {
withExtraArray(arr, rotationGtArrayLength);
assertArrayEquals(gtArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseExtraArrayWithRotationEqArrayLength_thenDoNothing() {
int[] clone = arr.clone();
withExtraArray(arr, arr.length);
assertArrayEquals(clone, arr);
}
@Test
void givenInputArray_whenUseCyclicReplacementRotationLtArrayLength_thenRotateArrayOk() {
cyclicReplacement(arr, rotationLtArrayLength);
assertArrayEquals(ltArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseCyclicReplacementRotationGtArrayLength_thenRotateArrayOk() {
cyclicReplacement(arr, rotationGtArrayLength);
assertArrayEquals(gtArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseCyclicReplacementRotationEqArrayLength_thenDoNothing() {
int[] clone = arr.clone();
cyclicReplacement(arr, arr.length);
assertArrayEquals(clone, arr);
}
@Test
void givenInputArray_whenUseReverseRotationLtArrayLength_thenRotateArrayOk() {
reverse(arr, rotationLtArrayLength);
assertArrayEquals(ltArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseReverseRotationGtArrayLength_thenRotateArrayOk() {
reverse(arr, rotationGtArrayLength);
assertArrayEquals(gtArrayLengthRotation, arr);
}
@Test
void givenInputArray_whenUseReverseRotationEqArrayLength_thenDoNothing() {
int[] clone = arr.clone();
reverse(arr, arr.length);
assertArrayEquals(clone, arr);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/primeundernumber/LargestPrimeFinder.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/primeundernumber/LargestPrimeFinder.java | package com.baeldung.algorithms.primeundernumber;
import java.util.Arrays;
public class LargestPrimeFinder {
public static int findByBruteForce(int n) {
for (int i = n - 1; i >= 2; i--) {
if (isPrime(i)) {
return i;
}
}
return -1; // Return -1 if no prime number is found
}
public static boolean isPrime(int number) {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static int findBySieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
for (int p = 2; p*p < n; p++) {
if (isPrime[p]) {
for (int i = p * p; i < n; i += p) {
isPrime[i] = false;
}
}
}
for (int i = n - 1; i >= 2; i--) {
if (isPrime[i]) {
return i;
}
}
return -1;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java | 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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/luhn/LuhnChecker.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/luhn/LuhnChecker.java | package com.baeldung.algorithms.luhn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuhnChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(LuhnChecker.class);
/*
* Starting from the rightmost digit, we add all the digits together, performing
* a special step for every second digit.
*
* If the result is not divisible by 10, then the card number must not be valid.
*
* We can form a number that passes the Luhn Check by subtracting the result of
* the Luhn algorithm from 10.
*
* This is how the final digit of a credit card is calculated.
*/
public static boolean checkLuhn(String cardNumber) {
int sum = 0;
try {
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if ((cardNumber.length() - i) % 2 == 0) {
digit = doubleAndSumDigits(digit);
}
sum += digit;
}
LOGGER.info("Luhn Algorithm sum of digits is " + sum);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException - Card number probably contained some non-numeric characters, returning false");
return false;
} catch (NullPointerException e) {
LOGGER.error("Null pointer - Card number was probably null, returning false");
return false;
}
boolean result = sum % 10 == 0;
LOGGER.info("Luhn check result (sum divisible by 10): " + result);
return result;
}
/*
* We apply this method to every second number from the right of the card
* number. First, we double the digit, then we sum the digits.
*
* Note: subtracting 9 is equivalent to doubling and summing digits (when
* starting with a single digit) 0-4 -> produce single digit when doubled
* 5*2 = 10 -> 1+0 = 1 = 10-9
* 6*2 = 12 -> 1+3 = 3 = 12-9
* 7*2 = 14 -> 1+5 = 5 = 14-9
* 8*2 = 16 -> 1+7 = 7 = 16-9
* 9*2 = 18 -> 1+9 = 9 = 18-9
*/
public static int doubleAndSumDigits(int digit) {
int ret = digit * 2;
if (ret > 9) {
ret -= 9;
}
return ret;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/stringrotation/StringRotation.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/stringrotation/StringRotation.java | package com.baeldung.algorithms.stringrotation;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class StringRotation {
public static boolean doubledOriginContainsRotation(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return origin.concat(origin)
.contains(rotation);
}
return false;
}
public static boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
if (origin.length() == rotation.length()) {
List<Integer> indexes = IntStream.range(0, origin.length())
.filter(i -> rotation.charAt(i) == origin.charAt(0))
.boxed()
.collect(Collectors.toList());
for (int startingAt : indexes) {
if (isRotation(startingAt, rotation, origin)) {
return true;
}
}
}
return false;
}
static boolean isRotation(int startingAt, String rotation, String origin) {
for (int i = 0; i < origin.length(); i++) {
if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
return false;
}
}
return true;
}
public static boolean isRotationUsingQueue(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return checkWithQueue(origin, rotation);
}
return false;
}
static boolean checkWithQueue(String origin, String rotation) {
if (origin.length() == rotation.length()) {
Queue<Character> originQueue = getCharactersQueue(origin);
Queue<Character> rotationQueue = getCharactersQueue(rotation);
int k = rotation.length();
while (k > 0 && null != rotationQueue.peek()) {
k--;
char ch = rotationQueue.peek();
rotationQueue.remove();
rotationQueue.add(ch);
if (rotationQueue.equals(originQueue)) {
return true;
}
}
}
return false;
}
static Queue<Character> getCharactersQueue(String origin) {
return origin.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toCollection(LinkedList::new));
}
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return checkPrefixAndSuffix(origin, rotation);
}
return false;
}
static boolean checkPrefixAndSuffix(String origin, String rotation) {
if (origin.length() == rotation.length()) {
for (int i = 0; i < origin.length(); i++) {
if (origin.charAt(i) == rotation.charAt(0)) {
if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
if (checkOriginPrefixWithRotationSuffix(origin, rotation, i))
return true;
}
}
}
}
return false;
}
private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
return origin.substring(i)
.equals(rotation.substring(0, origin.length() - i));
}
private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
return origin.substring(0, i)
.equals(rotation.substring(origin.length() - i));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java | package com.baeldung.algorithms.pixelarray;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class GetPixelArray {
public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
int width = sampleImage.getWidth();
int height = sampleImage.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = sampleImage.getRGB(col, row);
}
}
return result;
}
public static int[][] get2DPixelArrayFast(BufferedImage image) {
final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int numberOfValues = 4;
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
// Getting the values for each pixel from the pixelData array.
int argb = 0;
argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int numberOfValues = 3;
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
int argb = 0;
argb += -16777216; // 255 alpha value (fully opaque)
argb += ((int) pixelData[valueIndex] & 0xff); // blue value
argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounter.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounter.java | package com.baeldung.algorithms.uniquedigit;
import java.util.HashSet;
import java.util.Set;
public class UniqueDigitCounter {
public static int countWithSet(int number) {
number = Math.abs(number);
Set<Character> uniqueDigits = new HashSet<>();
String numberStr = String.valueOf(number);
for (char digit : numberStr.toCharArray()) {
uniqueDigits.add(digit);
}
return uniqueDigits.size();
}
public static int countWithBitManipulation(int number) {
if (number == 0) {
return 1;
}
number = Math.abs(number);
int mask = 0;
while (number > 0) {
int digit = number % 10;
mask |= 1 << digit;
number /= 10;
}
return Integer.bitCount(mask);
}
public static long countWithStreamApi(int number) {
return String.valueOf(Math.abs(number)).chars().distinct().count();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java | algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java | package com.baeldung.algorithms.rotatearray;
/**
* To speed up the rotation, we narrow k rotations to the remainder of k divided by the array length, or k module the array length.
* Therefore, a large rotation number will be translated into the relative smallest rotation.
* All solutions replace the original array, although they might use an extra array to compute the rotation.
*/
public class RotateArray {
private RotateArray() {
throw new IllegalStateException("Rotate array algorithm utility methods class");
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void bruteForce(int[] arr, int k) {
checkInvalidInput(arr, k);
k %= arr.length;
int temp;
int previous;
for (int i = 0; i < k; i++) {
previous = arr[arr.length - 1];
for (int j = 0; j < arr.length; j++) {
temp = arr[j];
arr[j] = previous;
previous = temp;
}
}
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void withExtraArray(int[] arr, int k) {
checkInvalidInput(arr, k);
int[] extraArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
extraArray[(i + k) % arr.length] = arr[i];
}
System.arraycopy(extraArray, 0, arr, 0, arr.length);
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void cyclicReplacement(int[] arr, int k) {
checkInvalidInput(arr, k);
k = k % arr.length;
int count = 0;
for (int start = 0; count < arr.length; start++) {
int current = start;
int prev = arr[start];
do {
int next = (current + k) % arr.length;
int temp = arr[next];
arr[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void reverse(int[] arr, int k) {
checkInvalidInput(arr, k);
k %= arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
private static void checkInvalidInput(int[] arr, int rotation) {
if (rotation < 1 || arr == null)
throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java | package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class EnglishAlphabetLettersUnitTest {
@Test
void givenString_whenContainsAllCharacter_thenTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
}
@Test
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java | package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
public class LongestSubstringNonRepeatingCharactersUnitTest {
@Test
void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstringBruteForce(""));
assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
}
@Test
void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstring(""));
assertEquals("A", getUniqueCharacterSubstring("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java | package com.baeldung.algorithms.string;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class SubstringPalindromeUnitTest {
private static final String INPUT_BUBBLE = "bubble";
private static final String INPUT_CIVIC = "civic";
private static final String INPUT_INDEED = "indeed";
private static final String INPUT_ABABAC = "ababac";
Set<String> EXPECTED_PALINDROME_BUBBLE = new HashSet<String>() {
{
add("b");
add("u");
add("l");
add("e");
add("bb");
add("bub");
}
};
Set<String> EXPECTED_PALINDROME_CIVIC = new HashSet<String>() {
{
add("civic");
add("ivi");
add("i");
add("c");
add("v");
}
};
Set<String> EXPECTED_PALINDROME_INDEED = new HashSet<String>() {
{
add("i");
add("n");
add("d");
add("e");
add("ee");
add("deed");
}
};
Set<String> EXPECTED_PALINDROME_ABABAC = new HashSet<String>() {
{
add("a");
add("b");
add("c");
add("aba");
add("bab");
add("ababa");
}
};
private SubstringPalindrome palindrome = new SubstringPalindrome();
@Test
public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
}
@Test
public void whenUsingCenterApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
}
@Test
public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/support/MayFailRule.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/support/MayFailRule.java | package com.baeldung.algorithms.support;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* JUnit custom rule for managing tests that may fail due to heuristics or
* randomness. In order to use this, just instantiate this object as a public
* field inside the test class and annotate it with {@link Rule}.
*
* @author Donato Rimenti
*
*/
public class MayFailRule implements TestRule {
/*
* (non-Javadoc)
*
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
* org.junit.runner.Description)
*/
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable e) {
// Ignore the exception since we expect this.
}
}
};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java | package com.baeldung.algorithms.multiswarm;
/**
* Specific fitness function implementation to solve the League of Legends
* problem. This is the problem statement: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is armor.
* Health costs 2.5 gold per unit, and Armor costs 18 gold per unit. You have
* 3600 gold, and you need to optimize the effectiveness E of your health and
* armor to survive as long as possible against the enemy team's attacks. How
* much of each should you buy? <br>
* <br>
*
* @author Donato Rimenti
*
*/
public class LolFitnessFunction implements FitnessFunction {
/*
* (non-Javadoc)
*
* @see
* com.baeldung.algorithms.multiswarm.FitnessFunction#getFitness(long[])
*/
@Override
public double getFitness(long[] particlePosition) {
long health = particlePosition[0];
long armor = particlePosition[1];
// No negatives values accepted.
if (health < 0 && armor < 0) {
return -(health * armor);
} else if (health < 0) {
return health;
} else if (armor < 0) {
return armor;
}
// Checks if the solution is actually feasible provided our gold.
double cost = (health * 2.5) + (armor * 18);
if (cost > 3600) {
return 3600 - cost;
} else {
// Check how good is the solution.
long fitness = (health * (100 + armor)) / 100;
return fitness;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java | package com.baeldung.algorithms.multiswarm;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.algorithms.support.MayFailRule;
/**
* Test for {@link Multiswarm}.
*
* @author Donato Rimenti
*
*/
public class MultiswarmUnitTest {
/**
* Rule for handling expected failures. We use this since this test may
* actually fail due to bad luck in the random generation.
*/
@Rule
public MayFailRule mayFailRule = new MayFailRule();
/**
* Tests the multiswarm algorithm with a generic problem. The problem is the
* following: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is
* armor. Health costs 2.5 gold per unit, and Armor costs 18 gold per unit.
* You have 3600 gold, and you need to optimize the effectiveness E of your
* health and armor to survive as long as possible against the enemy team's
* attacks. How much of each should you buy? <br>
* <br>
* The solution is H = 1080, A = 50 for a total fitness of 1620. Tested with
* 50 swarms each with 1000 particles.
*/
@Test
public void givenMultiswarm_whenThousandIteration_thenSolutionFound() {
Multiswarm multiswarm = new Multiswarm(50, 1000, new LolFitnessFunction());
// Iterates 1000 times through the main loop and prints the result.
for (int i = 0; i < 1000; i++) {
multiswarm.mainLoop();
}
System.out.println("Best fitness found: " + multiswarm.getBestFitness() + "[" + multiswarm.getBestPosition()[0]
+ "," + multiswarm.getBestPosition()[1] + "]");
Assert.assertEquals(1080, multiswarm.getBestPosition()[0]);
Assert.assertEquals(50, multiswarm.getBestPosition()[1]);
Assert.assertEquals(1620, (int) multiswarm.getBestFitness());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsCombinatoricsLibUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsCombinatoricsLibUnitTest.java | package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class StringPermutationsCombinatoricsLibUnitTest {
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.hasSize(numberOfPermutations);
}
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 60",
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.hasSize(numberOfPermutations);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsApacheUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsApacheUnitTest.java | package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class StringPermutationsApacheUnitTest {
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final List<String> permutations = permutationGenerator.eagerPermutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.hasSize(numberOfPermutations);
}
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final List<String> permutations = permutationGenerator.lazyPermutationWithoutRepetitions(string);
int size = permutations.size();
assertThat(size)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.isEqualTo(numberOfPermutations);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/HelperUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/HelperUnitTest.java | package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class HelperUnitTest {
@ParameterizedTest
@MethodSource("stringProvider")
void toListTest(String value, List<Character> expected) {
final List<Character> actual = Helper.toCharacterList(value);
assertThat(expected).isEqualTo(actual);
}
@ParameterizedTest
@MethodSource("stringProvider")
void toStringTest(String expected, List<Character> value) {
final String actual = Helper.toString(value);
assertThat(expected).isEqualTo(actual);
}
static Stream<Arguments> stringProvider() {
return Stream.of(
Arguments.of("hello", Arrays.asList('h', 'e', 'l', 'l', 'o')),
Arguments.of("abc", Arrays.asList('a','b','c')),
Arguments.of("12345", Arrays.asList('1', '2', '3', '4', '5'))
);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsGuavaUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/stringpermutation/StringPermutationsGuavaUnitTest.java | package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class StringPermutationsGuavaUnitTest {
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.hasSize(numberOfPermutations);
}
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 60",
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.hasSize(numberOfPermutations);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveIntegerUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveIntegerUnitTest.java | package com.baeldung.algorithms.smallestinteger;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SmallestMissingPositiveIntegerUnitTest {
@Test
void givenArrayWithThreeMissing_whenSearchInSortedArray_thenThree() {
int[] input = new int[] {0, 1, 2, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInSortedArray_thenOne() {
int[] input = new int[] {0, 2, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInSortedArray_thenArrayLength() {
int[] input = new int[] {0, 1, 2, 3, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(input.length);
}
@Test
void givenArrayWithThreeMissing_whenSearchInUnsortedArraySortingFirst_thenThree() {
int[] input = new int[] {1, 4, 0, 5, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArraySortingFirst_thenOne() {
int[] input = new int[] {4, 2, 0, 5};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArraySortingFirst_thenArrayLength() {
int[] input = new int[] {4, 5, 1, 3, 0, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(input.length);
}
@Test
void givenArrayWithThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenThree() {
int[] input = new int[] {1, 4, 0, 5, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenOne() {
int[] input = new int[] {4, 2, 0, 5};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArrayBooleanArray_thenArrayLength() {
int[] input = new int[] {4, 5, 1, 3, 0, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(input.length);
}
@Test
void givenArrayWithoutZero_whenSearchInUnsortedArrayBooleanArray_thenZero() {
int[] input = new int[] {11, 13, 14, 15};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(0);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/hillclimbing/HillClimbingAlgorithmUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/hillclimbing/HillClimbingAlgorithmUnitTest.java | package com.baeldung.algorithms.hillclimbing;
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 java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class HillClimbingAlgorithmUnitTest {
private Stack<String> initStack;
private Stack<String> goalStack;
@BeforeEach
public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" };
initStack = new Stack<>();
for (String block : blockArr)
initStack.push(block);
goalStack = new Stack<>();
for (String block : goalBlockArr)
goalStack.push(block);
}
@Test
void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
HillClimbing hillClimbing = new HillClimbing();
List<State> path;
try {
path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
assertNotNull(path);
assertEquals(path.get(path.size() - 1)
.getState()
.get(0), goalStack);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack);
State currentState = new State(initList);
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
State nextState = hillClimbing.findNextState(currentState, goalStack);
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookupUnitTest.java | algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookupUnitTest.java | package com.baeldung.algorithms.middleelementlookup;
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.Node;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
class MiddleElementLookupUnitTest {
@Test
void whenFindingMiddleLinkedList_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(4))
.get());
}
@Test
void whenFindingMiddleFromHead_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(4))
.get());
}
@Test
void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(4))
.get());
}
@Test
void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(4))
.get());
}
@Test
void whenListEmptyOrNull_thenMiddleNotFound() {
// null list
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(null)
.isPresent());
// empty LinkedList
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(new LinkedList<>())
.isPresent());
// LinkedList with nulls
LinkedList<String> nullsList = new LinkedList<>();
nullsList.add(null);
nullsList.add(null);
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(nullsList)
.isPresent());
// nodes with null values
assertFalse(MiddleElementLookup
.findMiddleElementFromHead(new Node(null))
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(new Node(null))
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(new Node(null))
.isPresent());
}
private static LinkedList<String> createLinkedList(int n) {
LinkedList<String> list = new LinkedList<>();
for (int i = 1; i <= n; i++) {
list.add(String.valueOf(i));
}
return list;
}
private static Node createNodesList(int n) {
Node head = new Node("1");
Node current = head;
for (int i = 2; i <= n; i++) {
Node newNode = new Node(String.valueOf(i));
current.setNext(newNode);
current = newNode;
}
return head;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java | package com.baeldung.algorithms.string;
public class EnglishAlphabetLetters {
public static boolean checkStringForAllTheLetters(String input) {
boolean[] visited = new boolean[26];
int index = 0;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
index = input.charAt(id) - 'a';
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
index = input.charAt(id) - 'A';
}
visited[index] = true;
}
for (int id = 0; id < 26; id++) {
if (!visited[id]) {
return false;
}
}
return true;
}
public static boolean checkStringForAllLetterUsingStream(String input) {
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
return c == 26;
}
public static void main(String[] args) {
checkStringForAllLetterUsingStream("intit");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java | package com.baeldung.algorithms.string;
import java.util.HashSet;
import java.util.Set;
public class SubstringPalindrome {
public Set<String> findAllPalindromesUsingCenter(String input) {
final Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
palindromes.addAll(findPalindromes(input, i, i + 1));
palindromes.addAll(findPalindromes(input, i, i));
}
return palindromes;
}
private Set<String> findPalindromes(String input, int low, int high) {
Set<String> result = new HashSet<>();
while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
result.add(input.substring(low, high + 1));
low--;
high++;
}
return result;
}
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++)
if (isPalindrome(input.substring(i, j))) {
palindromes.add(input.substring(i, j));
}
}
return palindromes;
}
private boolean isPalindrome(String input) {
StringBuilder plain = new StringBuilder(input);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(input);
}
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
Set<String> palindromes = new HashSet<>();
String formattedInput = "@" + input + "#";
char inputCharArr[] = formattedInput.toCharArray();
int max;
int radius[][] = new int[2][input.length() + 1];
for (int j = 0; j <= 1; j++) {
radius[j][0] = max = 0;
int i = 1;
while (i <= input.length()) {
palindromes.add(Character.toString(inputCharArr[i]));
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
max++;
radius[j][i] = max;
int k = 1;
while ((radius[j][i - k] != max - k) && (k < max)) {
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
k++;
}
max = Math.max(max - k, 0);
i += k;
}
}
for (int i = 1; i <= input.length(); i++) {
for (int j = 0; j <= 1; j++) {
for (max = radius[j][i]; max > 0; max--) {
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
}
}
}
return palindromes;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java | package com.baeldung.algorithms.string;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LongestSubstringNonRepeatingCharacters {
public static String getUniqueCharacterSubstringBruteForce(String input) {
String output = "";
for (int start = 0; start < input.length(); start++) {
Set<Character> visited = new HashSet<>();
int end = start;
for (; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.contains(currChar)) {
break;
} else {
visited.add(currChar);
}
}
if (output.length() < end - start + 1) {
output = input.substring(start, end);
}
}
return output;
}
public static String getUniqueCharacterSubstring(String input) {
Map<Character, Integer> visited = new HashMap<>();
String output = "";
for (int start = 0, end = 0; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.containsKey(currChar)) {
start = Math.max(visited.get(currChar) + 1, start);
}
if (output.length() < end - start + 1) {
output = input.substring(start, end + 1);
}
visited.put(currChar, end);
}
return output;
}
public static void main(String[] args) {
if(args.length > 0) {
System.out.println(getUniqueCharacterSubstring(args[0]));
} else {
System.err.println("This program expects command-line input. Please try again!");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java | package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Particle}.
*
* @author Donato Rimenti
*
*/
public class Swarm {
/**
* The particles of this swarm.
*/
private Particle[] particles;
/**
* The best position found within the particles of this swarm.
*/
private long[] bestPosition;
/**
* The best fitness score found within the particles of this swarm.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* Instantiates a new Swarm.
*
* @param numParticles
* the number of particles of the swarm
*/
public Swarm(int numParticles) {
particles = new Particle[numParticles];
for (int i = 0; i < numParticles; i++) {
long[] initialParticlePosition = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
long[] initialParticleSpeed = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
particles[i] = new Particle(initialParticlePosition, initialParticleSpeed);
}
}
/**
* Gets the {@link #particles}.
*
* @return the {@link #particles}
*/
public Particle[] getParticles() {
return particles;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + Arrays.hashCode(particles);
result = prime * result + ((random == null) ? 0 : random.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Swarm other = (Swarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (!Arrays.equals(particles, other.particles))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java | package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Multiswarm {
/**
* The swarms managed by this multiswarm.
*/
private Swarm[] swarms;
/**
* The best position found within all the {@link #swarms}.
*/
private long[] bestPosition;
/**
* The best fitness score found within all the {@link #swarms}.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* The fitness function used to determine how good is a particle.
*/
private FitnessFunction fitnessFunction;
/**
* Instantiates a new Multiswarm.
*
* @param numSwarms
* the number of {@link #swarms}
* @param particlesPerSwarm
* the number of particle for each {@link #swarms}
* @param fitnessFunction
* the {@link #fitnessFunction}
*/
public Multiswarm(int numSwarms, int particlesPerSwarm, FitnessFunction fitnessFunction) {
this.fitnessFunction = fitnessFunction;
this.swarms = new Swarm[numSwarms];
for (int i = 0; i < numSwarms; i++) {
swarms[i] = new Swarm(particlesPerSwarm);
}
}
/**
* Main loop of the algorithm. Iterates all particles of all
* {@link #swarms}. For each particle, computes the new fitness and checks
* if a new best position has been found among itself, the swarm and all the
* swarms and finally updates the particle position and speed.
*/
public void mainLoop() {
for (Swarm swarm : swarms) {
for (Particle particle : swarm.getParticles()) {
long[] particleOldPosition = particle.getPosition().clone();
// Calculate the particle fitness.
particle.setFitness(fitnessFunction.getFitness(particleOldPosition));
// Check if a new best position has been found for the particle
// itself, within the swarm and the multiswarm.
if (particle.getFitness() > particle.getBestFitness()) {
particle.setBestFitness(particle.getFitness());
particle.setBestPosition(particleOldPosition);
if (particle.getFitness() > swarm.getBestFitness()) {
swarm.setBestFitness(particle.getFitness());
swarm.setBestPosition(particleOldPosition);
if (swarm.getBestFitness() > bestFitness) {
bestFitness = swarm.getBestFitness();
bestPosition = swarm.getBestPosition().clone();
}
}
}
// Updates the particle position by adding the speed to the
// actual position.
long[] position = particle.getPosition();
long[] speed = particle.getSpeed();
position[0] += speed[0];
position[1] += speed[1];
// Updates the particle speed.
speed[0] = getNewParticleSpeedForIndex(particle, swarm, 0);
speed[1] = getNewParticleSpeedForIndex(particle, swarm, 1);
}
}
}
/**
* Computes a new speed for a given particle of a given swarm on a given
* axis. The new speed is computed using the formula:
*
* <pre>
* ({@link Constants#INERTIA_FACTOR} * {@link Particle#getSpeed()}) +
* (({@link Constants#COGNITIVE_WEIGHT} * random(0,1)) * ({@link Particle#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#SOCIAL_WEIGHT} * random(0,1)) * ({@link Swarm#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#GLOBAL_WEIGHT} * random(0,1)) * ({@link #bestPosition} - {@link Particle#getPosition()}))
* </pre>
*
* @param particle
* the particle whose new speed needs to be computed
* @param swarm
* the swarm which contains the particle
* @param index
* the index of the particle axis whose speeds needs to be
* computed
* @return the new speed of the particle passed on the given axis
*/
private int getNewParticleSpeedForIndex(Particle particle, Swarm swarm, int index) {
return (int) ((Constants.INERTIA_FACTOR * particle.getSpeed()[index])
+ (randomizePercentage(Constants.COGNITIVE_WEIGHT)
* (particle.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.SOCIAL_WEIGHT)
* (swarm.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.GLOBAL_WEIGHT)
* (bestPosition[index] - particle.getPosition()[index])));
}
/**
* Returns a random number between 0 and the value passed as argument.
*
* @param value
* the value to randomize
* @return a random value between 0 and the one passed as argument
*/
private double randomizePercentage(double value) {
return random.nextDouble() * value;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
result = prime * result + ((random == null) ? 0 : random.hashCode());
result = prime * result + Arrays.hashCode(swarms);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Multiswarm other = (Multiswarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (fitnessFunction == null) {
if (other.fitnessFunction != null)
return false;
} else if (!fitnessFunction.equals(other.fitnessFunction))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
if (!Arrays.equals(swarms, other.swarms))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java | package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
/**
* Represents a particle, the basic component of a {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Particle {
/**
* The current position of this particle.
*/
private long[] position;
/**
* The speed of this particle.
*/
private long[] speed;
/**
* The fitness of this particle for the current position.
*/
private double fitness;
/**
* The best position found by this particle.
*/
private long[] bestPosition;
/**
* The best fitness found by this particle.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* Instantiates a new Particle.
*
* @param initialPosition
* the initial {@link #position}
* @param initialSpeed
* the initial {@link #speed}
*/
public Particle(long[] initialPosition, long[] initialSpeed) {
this.position = initialPosition;
this.speed = initialSpeed;
}
/**
* Gets the {@link #position}.
*
* @return the {@link #position}
*/
public long[] getPosition() {
return position;
}
/**
* Gets the {@link #speed}.
*
* @return the {@link #speed}
*/
public long[] getSpeed() {
return speed;
}
/**
* Gets the {@link #fitness}.
*
* @return the {@link #fitness}
*/
public double getFitness() {
return fitness;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #position}.
*
* @param position
* the new {@link #position}
*/
public void setPosition(long[] position) {
this.position = position;
}
/**
* Sets the {@link #speed}.
*
* @param speed
* the new {@link #speed}
*/
public void setSpeed(long[] speed) {
this.speed = speed;
}
/**
* Sets the {@link #fitness}.
*
* @param fitness
* the new {@link #fitness}
*/
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java | package com.baeldung.algorithms.multiswarm;
/**
* Constants used by the Multi-swarm optimization algorithms.
*
* @author Donato Rimenti
*
*/
public class Constants {
/**
* The inertia factor encourages a particle to continue moving in its
* current direction.
*/
public static final double INERTIA_FACTOR = 0.729;
/**
* The cognitive weight encourages a particle to move toward its historical
* best-known position.
*/
public static final double COGNITIVE_WEIGHT = 1.49445;
/**
* The social weight encourages a particle to move toward the best-known
* position found by any of the particle’s swarm-mates.
*/
public static final double SOCIAL_WEIGHT = 1.49445;
/**
* The global weight encourages a particle to move toward the best-known
* position found by any particle in any swarm.
*/
public static final double GLOBAL_WEIGHT = 0.3645;
/**
* Upper bound for the random generation. We use it to reduce the
* computation time since we can rawly estimate it.
*/
public static final int PARTICLE_UPPER_BOUND = 10000000;
/**
* Private constructor for utility class.
*/
private Constants() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java | package com.baeldung.algorithms.multiswarm;
/**
* Interface for a fitness function, used to decouple the main algorithm logic
* from the specific problem solution.
*
* @author Donato Rimenti
*
*/
public interface FitnessFunction {
/**
* Returns the fitness of a particle given its position.
*
* @param particlePosition
* the position of the particle
* @return the fitness of the particle
*/
public double getFitness(long[] particlePosition);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsCombinatoricsLib.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsCombinatoricsLib.java | package com.baeldung.algorithms.stringpermutation;
import java.util.List;
import java.util.stream.Collectors;
import org.paukov.combinatorics3.Generator;
import org.paukov.combinatorics3.PermutationGenerator.TreatDuplicatesAs;
public class StringPermutationsCombinatoricsLib {
public List<String> permutationWithoutRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple()
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<String> permutationWithRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple(TreatDuplicatesAs.IDENTICAL)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsApache.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsApache.java | package com.baeldung.algorithms.stringpermutation;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.iterators.PermutationIterator;
public class StringPermutationsApache {
public List<String> eagerPermutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return CollectionUtils.permutations(characters)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<String> lazyPermutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
final PermutationIterator<Character> permutationIterator = new PermutationIterator<>(characters);
final List<String> result = new ArrayList<>();
while (permutationIterator.hasNext()) {
result.add(Helper.toString(permutationIterator.next()));
}
return result;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/Helper.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/Helper.java | package com.baeldung.algorithms.stringpermutation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class Helper {
private Helper() {
}
static List<Character> toCharacterList(final String string) {
return string.chars().mapToObj(s -> ((char) s)).collect(Collectors.toList());
}
static String toString(Collection<Character> collection) {
return collection.stream().map(Object::toString).collect(Collectors.joining());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsGuava.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/stringpermutation/StringPermutationsGuava.java | package com.baeldung.algorithms.stringpermutation;
import com.google.common.collect.Collections2;
import java.util.List;
import java.util.stream.Collectors;
public class StringPermutationsGuava {
public List<String> permutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.permutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<String> permutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.orderedPermutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveInteger.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveInteger.java | package com.baeldung.algorithms.smallestinteger;
import java.util.Arrays;
public class SmallestMissingPositiveInteger {
public static int searchInSortedArray(int[] input) {
for (int i = 0; i < input.length; i++) {
if (i != input[i]) {
return i;
}
}
return input.length;
}
public static int searchInUnsortedArraySortingFirst(int[] input) {
Arrays.sort(input);
return searchInSortedArray(input);
}
public static int searchInUnsortedArrayBooleanArray(int[] input) {
boolean[] flags = new boolean[input.length];
for (int number : input) {
if (number < flags.length) {
flags[number] = true;
}
}
for (int i = 0; i < flags.length; i++) {
if (!flags[i]) {
return i;
}
}
return flags.length;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/hillclimbing/State.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/hillclimbing/State.java | package com.baeldung.algorithms.hillclimbing;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class State {
private List<Stack<String>> state;
private int heuristics;
public State(List<Stack<String>> state) {
this.state = state;
}
State(List<Stack<String>> state, int heuristics) {
this.state = state;
this.heuristics = heuristics;
}
State(State state) {
if (state != null) {
this.state = new ArrayList<>();
for (Stack s : state.getState()) {
Stack s1;
s1 = (Stack) s.clone();
this.state.add(s1);
}
this.heuristics = state.getHeuristics();
}
}
public List<Stack<String>> getState() {
return state;
}
public int getHeuristics() {
return heuristics;
}
public void setHeuristics(int heuristics) {
this.heuristics = heuristics;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java | package com.baeldung.algorithms.hillclimbing;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Stack;
public class HillClimbing {
public static void main(String[] args) {
HillClimbing hillClimbing = new HillClimbing();
String blockArr[] = { "B", "C", "D", "A" };
Stack<String> startState = hillClimbing.getStackWithValues(blockArr);
String goalBlockArr[] = { "A", "B", "C", "D" };
Stack<String> goalState = hillClimbing.getStackWithValues(goalBlockArr);
try {
List<State> solutionSequence = hillClimbing.getRouteWithHillClimbing(startState, goalState);
solutionSequence.forEach(HillClimbing::printEachStep);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printEachStep(State state) {
List<Stack<String>> stackList = state.getState();
System.out.println("----------------");
stackList.forEach(stack -> {
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
System.out.println(" ");
});
}
private Stack<String> getStackWithValues(String[] blocks) {
Stack<String> stack = new Stack<>();
for (String block : blocks)
stack.push(block);
return stack;
}
/**
* This method prepares path from init state to goal state
*/
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
List<Stack<String>> initStateStackList = new ArrayList<>();
initStateStackList.add(initStateStack);
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
State initState = new State(initStateStackList, initStateHeuristics);
List<State> resultPath = new ArrayList<>();
resultPath.add(new State(initState));
State currentState = initState;
boolean noStateFound = false;
while (!currentState.getState()
.get(0)
.equals(goalStateStack) || noStateFound) {
noStateFound = true;
State nextState = findNextState(currentState, goalStateStack);
if (nextState != null) {
noStateFound = false;
currentState = nextState;
resultPath.add(new State(nextState));
}
}
return resultPath;
}
/**
* This method finds new state from current state based on goal and
* heuristics
*/
public State findNextState(State currentState, Stack<String> goalStateStack) {
List<Stack<String>> listOfStacks = currentState.getState();
int currentStateHeuristics = currentState.getHeuristics();
return listOfStacks.stream()
.map(stack -> {
return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
}
/**
* This method applies operations on the current state to get a new state
*/
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
State tempState;
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
String block = stack.pop();
if (stack.size() == 0)
tempStackList.remove(stack);
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
if (tempState == null) {
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
}
if (tempState == null)
stack.push(block);
return tempState;
}
/**
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into a new stack
*/
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
State newState = null;
Stack<String> newStack = new Stack<>();
newStack.push(block);
currentStackList.add(newStack);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
newState = new State(currentStackList, newStateHeuristics);
} else {
currentStackList.remove(newStack);
}
return newState;
}
/**
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into one of the other stacks to explore new
* states
*/
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
Optional<State> newState = currentStackList.stream()
.filter(stack -> stack != currentStack)
.map(stack -> {
return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst();
return newState.orElse(null);
}
/**
* This method pushes a block to the stack and returns new state if its closer to goal
*/
private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) {
stack.push(block);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
return new State(currentStackList, newStateHeuristics);
}
stack.pop();
return null;
}
/**
* This method returns heuristics value for given state with respect to goal
* state
*/
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
Integer heuristicValue;
heuristicValue = currentState.stream()
.mapToInt(stack -> {
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
})
.sum();
return heuristicValue;
}
/**
* This method returns heuristics value for a particular stack
*/
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
int stackHeuristics = 0;
boolean isPositioneCorrect = true;
int goalStartIndex = 0;
for (String currentBlock : stack) {
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
stackHeuristics += goalStartIndex;
} else {
stackHeuristics -= goalStartIndex;
isPositioneCorrect = false;
}
goalStartIndex++;
}
return stackHeuristics;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java | package com.baeldung.algorithms.middleelementlookup;
public class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return this.data;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java | algorithms-modules/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java | package com.baeldung.algorithms.middleelementlookup;
import java.util.LinkedList;
import java.util.Optional;
public class MiddleElementLookup {
public static Optional<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
if (linkedList == null || linkedList.isEmpty()) {
return Optional.empty();
}
return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2));
}
public static Optional<String> findMiddleElementFromHead(Node head) {
if (head == null) {
return Optional.empty();
}
// calculate the size of the list
Node current = head;
int size = 1;
while (current.hasNext()) {
current = current.next();
size++;
}
// iterate till the middle element
current = head;
for (int i = 0; i < (size - 1) / 2; i++) {
current = current.next();
}
return Optional.ofNullable(current.data());
}
public static Optional<String> findMiddleElementFromHead1PassRecursively(Node head) {
if (head == null) {
return Optional.empty();
}
MiddleAuxRecursion middleAux = new MiddleAuxRecursion();
findMiddleRecursively(head, middleAux);
return Optional.ofNullable(middleAux.middle.data());
}
private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
if (node == null) {
// reached the end
middleAux.length = middleAux.length / 2;
return;
}
middleAux.length++;
findMiddleRecursively(node.next(), middleAux);
if (middleAux.length == 0) {
// found the middle
middleAux.middle = node;
}
middleAux.length--;
}
public static Optional<String> findMiddleElementFromHead1PassIteratively(Node head) {
if (head == null) {
return Optional.empty();
}
Node slowPointer = head;
Node fastPointer = head;
while (fastPointer.hasNext() && fastPointer.next()
.hasNext()) {
fastPointer = fastPointer.next()
.next();
slowPointer = slowPointer.next();
}
return Optional.ofNullable(slowPointer.data());
}
private static class MiddleAuxRecursion {
Node middle;
int length = 0;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/permutation/StringPermutationUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/permutation/StringPermutationUnitTest.java | package com.baeldung.algorithms.permutation;
import static com.baeldung.algorithms.permutation.StringPermutation.isPermutationInclusion;
import static com.baeldung.algorithms.permutation.StringPermutation.isPermutationWithMap;
import static com.baeldung.algorithms.permutation.StringPermutation.isPermutationWithOneCounter;
import static com.baeldung.algorithms.permutation.StringPermutation.isPermutationWithSorting;
import static com.baeldung.algorithms.permutation.StringPermutation.isPermutationWithTwoCounters;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class StringPermutationUnitTest {
@Test
void givenTwoStringsArePermutation_whenSortingCharsArray_thenPermutation() {
assertTrue(isPermutationWithSorting("baeldung", "luaebngd"));
assertTrue(isPermutationWithSorting("hello world", "world hello"));
}
@Test
void givenTwoStringsAreNotPermutation_whenSortingCharsArray_thenNotPermutation() {
assertFalse(isPermutationWithSorting("baeldung", "luaebgd"));
assertFalse(isPermutationWithSorting("baeldung", "luaebngq"));
}
@Test
void givenTwoStringsArePermutation_whenTwoCountersCharsFrequencies_thenPermutation() {
assertTrue(isPermutationWithTwoCounters("baeldung", "luaebngd"));
assertTrue(isPermutationWithTwoCounters("hello world", "world hello"));
}
@Test
void givenTwoStringsAreNotPermutation_whenTwoCountersCharsFrequencies_thenNotPermutation() {
assertFalse(isPermutationWithTwoCounters("baeldung", "luaebgd"));
assertFalse(isPermutationWithTwoCounters("baeldung", "luaebngq"));
}
@Test
void givenTwoStringsArePermutation_whenOneCounterCharsFrequencies_thenPermutation() {
assertTrue(isPermutationWithOneCounter("baeldung", "luaebngd"));
assertTrue(isPermutationWithOneCounter("hello world", "world hello"));
}
@Test
void givenTwoStringsAreNotPermutation_whenOneCounterCharsFrequencies_thenNotPermutation() {
assertFalse(isPermutationWithOneCounter("baeldung", "luaebgd"));
assertFalse(isPermutationWithOneCounter("baeldung", "luaebngq"));
}
@Test
void givenTwoStringsArePermutation_whenCountCharsFrequenciesWithMap_thenPermutation() {
assertTrue(isPermutationWithMap("baelduňg", "luaebňgd"));
assertTrue(isPermutationWithMap("hello world", "world hello"));
}
@Test
void givenTwoStringsAreNotPermutation_whenCountCharsFrequenciesWithMap_thenNotPermutation() {
assertFalse(isPermutationWithMap("baelduňg", "luaebgd"));
assertFalse(isPermutationWithMap("baeldung", "luaebngq"));
assertFalse(isPermutationWithMap("baeldung", "luaebngg"));
}
@Test
void givenTwoStrings_whenIncludePermutation_thenPermutation() {
assertTrue(isPermutationInclusion("baeldung", "ea"));
assertTrue(isPermutationInclusion("baeldung", "ae"));
}
@Test
void givenTwoStrings_whenNotIncludePermutation_thenNotPermutation() {
assertFalse(isPermutationInclusion("baeldung", "au"));
assertFalse(isPermutationInclusion("baeldung", "baeldunga"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java | package com.baeldung.algorithms.minimax;
import static org.junit.jupiter.api.Assertions.assertFalse;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class MinimaxUnitTest {
private Tree gameTree;
private MiniMax miniMax;
@BeforeEach
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
assertNotNull(gameTree);
}
@Test
void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);
miniMax.constructTree(8);
result = miniMax.checkWin();
assertFalse(result);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java | package com.baeldung.algorithms.kthlargest;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class FindKthLargestUnitTest {
private FindKthLargest findKthLargest;
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
@BeforeEach
public void setup() {
findKthLargest = new FindKthLargest();
}
@Test
void givenIntArray_whenFindSecondLargestWithoutSorting_thenGetResult() throws Exception {
assertThat(findKthLargest.findSecondLargestWithoutSorting(arr)).isEqualTo(9);
}
@Test
void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
}
@Test
void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
}
@Test
void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
}
@Test
void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/successivepairs/SuccessivePairsUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/successivepairs/SuccessivePairsUnitTest.java | package com.baeldung.algorithms.successivepairs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class SuccessivePairsUnitTest {
@Test
public void givenEmptyStream_whenUsingSimpleEntry_thenCollectPairs() {
Stream<Integer> stream = Stream.empty();
List<SimpleEntry<Integer, Integer>> pairs = SuccessivePairs.collectSuccessivePairs(stream);
assertTrue(pairs.isEmpty());
}
@Test
public void givenSingleElement_whenUsingSimpleEntry_thenCollectPairs() {
Stream<Integer> stream = Stream.of(1);
List<SimpleEntry<Integer, Integer>> pairs = SuccessivePairs.collectSuccessivePairs(stream);
assertTrue(pairs.isEmpty());
}
@Test
public void givenMultipleElementStream_whenUsingSimpleEntry_thenCollectPairs() {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
List<SimpleEntry<Integer, Integer>> pairs = SuccessivePairs.collectSuccessivePairs(stream);
assertEquals(4, pairs.size());
assertEquals(new SimpleEntry<>(1, 2), pairs.get(0));
assertEquals(new SimpleEntry<>(2, 3), pairs.get(1));
assertEquals(new SimpleEntry<>(3, 4), pairs.get(2));
assertEquals(new SimpleEntry<>(4, 5), pairs.get(3));
}
@Test
public void givenStreamWithDuplicate_whenUsingSimpleEntry_thenCollectPairs() {
Stream<Integer> stream = Stream.of(1, 1, 2, 2, 3, 3);
List<SimpleEntry<Integer, Integer>> pairs = SuccessivePairs.collectSuccessivePairs(stream);
assertEquals(5, pairs.size());
assertEquals(new SimpleEntry<>(1, 1), pairs.get(0));
assertEquals(new SimpleEntry<>(1, 2), pairs.get(1));
assertEquals(new SimpleEntry<>(2, 2), pairs.get(2));
assertEquals(new SimpleEntry<>(2, 3), pairs.get(3));
assertEquals(new SimpleEntry<>(3, 3), pairs.get(4));
}
@Test
public void givenStreamWithLetters_whenUsingStatefulTransform_thenCollectPairs() {
Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
List<List<String>> result = SuccessivePairs.pairwise(stream)
.collect(Collectors.toList());
List<List<String>> expected = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("b", "c"), Arrays.asList("c", "d"), Arrays.asList("d", "e"));
assertEquals(expected, result);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/findclosestvalue/FindTheClosestNumberToAGivenValueUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/findclosestvalue/FindTheClosestNumberToAGivenValueUnitTest.java | package com.baeldung.algorithms.findclosestvalue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.jupiter.api.Test;
public class FindTheClosestNumberToAGivenValueUnitTest {
private static final List<Integer> UNSORTED_LIST = List.of(8, 100, 6, 89, -23, 77);
private static final List<Integer> SORTED_LIST = List.of(-23, 6, 8, 77, 89, 100);
public static int findClosestByLoop(List<Integer> numbers, int target) {
int closest = numbers.get(0);
int minDistance = Math.abs(target - closest);
for (int num : numbers) {
int distance = Math.abs(target - num);
if (distance < minDistance) {
closest = num;
minDistance = distance;
}
}
return closest;
}
@Test
void givenUnsortedList_whenFindClosestByLoop_thenCorrect() {
assertEquals(-23, findClosestByLoop(UNSORTED_LIST, -100));
assertEquals(100, findClosestByLoop(UNSORTED_LIST, 500));
assertEquals(89, findClosestByLoop(UNSORTED_LIST, 89));
assertEquals(77, findClosestByLoop(UNSORTED_LIST, 70));
assertEquals(8, findClosestByLoop(UNSORTED_LIST, 7));
}
public static int findClosestByStream(List<Integer> numbers, int target) {
return numbers.stream()
.min(Comparator.comparingInt(o -> Math.abs(o - target)))
.get();
}
@Test
void givenUnsortedList_whenFindClosestByStream_thenCorrect() {
assertEquals(-23, findClosestByStream(UNSORTED_LIST, -100));
assertEquals(100, findClosestByStream(UNSORTED_LIST, 500));
assertEquals(89, findClosestByStream(UNSORTED_LIST, 89));
assertEquals(77, findClosestByStream(UNSORTED_LIST, 70));
assertEquals(8, findClosestByStream(UNSORTED_LIST, 7));
}
public static int findClosestByBiSearch(List<Integer> sortedNumbers, int target) {
int first = sortedNumbers.get(0);
if (target <= first) {
return first;
}
int last = sortedNumbers.get(sortedNumbers.size() - 1);
if (target >= last) {
return last;
}
int pos = Collections.binarySearch(sortedNumbers, target);
if (pos > 0) {
return sortedNumbers.get(pos);
}
int insertPos = -(pos + 1);
int pre = sortedNumbers.get(insertPos - 1);
int after = sortedNumbers.get(insertPos);
return Math.abs(pre - target) <= Math.abs(after - target) ? pre : after;
}
@Test
void givenSortedList_whenFindTheClosestNumberUsingStream_thenCorrect() {
assertEquals(-23, findClosestByBiSearch(SORTED_LIST, -100));
assertEquals(100, findClosestByBiSearch(SORTED_LIST, 500));
assertEquals(89, findClosestByBiSearch(SORTED_LIST, 89));
assertEquals(77, findClosestByBiSearch(SORTED_LIST, 70));
assertEquals(6, findClosestByBiSearch(SORTED_LIST, 7));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/countoccurence/CountOccurrenceUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/countoccurence/CountOccurrenceUnitTest.java | package com.baeldung.algorithms.countoccurence;
import static com.baeldung.algorithms.countoccurence.CountOccurrence.countOccurrencesWithCounter;
import static com.baeldung.algorithms.countoccurence.CountOccurrence.countOccurrencesWithMap;
import static com.baeldung.algorithms.countoccurence.CountOccurrence.countOccurrencesWithStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class CountOccurrenceUnitTest {
@Test
void givenArrayOfIntegers_whenCountOccurrenceWithCounter_thenCounterIndexIsOccurrence() {
int[] counter = countOccurrencesWithCounter(new int[] { 2, 3, 1, 1, 3, 4, 5, 6, 7, 8 }, 10);
assertEquals(2, counter[3]);
}
@Test
void givenArrayOfIntegers_whenCountOccurrenceWithMap_thenMapValueIsOccurrence() {
Map<Integer, Integer> counter = countOccurrencesWithMap(new Integer[] { 2, 3, 1, -1, 3, 4, 5, 6, 7, 8, -1 });
assertEquals(2, counter.get(-1));
}
@Test
void givenArrayOfString_whenCountOccurrenceWithMap_thenMapValueIsOccurrence() {
Map<String, Integer> counter = countOccurrencesWithMap(new String[] { "apple", "orange", "banana", "apple" });
assertEquals(2, counter.get("apple"));
}
@Test
void givenArrayOfString_whenCountOccurrenceWithStream_thenMapValueIsOccurrence() {
Map<String, Long> counter = countOccurrencesWithStream(new String[] { "apple", "orange", "banana", "apple" });
assertEquals(2, counter.get("apple"));
}
@Test
void givenArrayOfIntegers_whenCountOccurrenceWithStream_thenMapValueIsOccurrence() {
Map<Integer, Long> counter = countOccurrencesWithStream(new Integer[] { 2, 3, 1, -1, 3, 4, 5, 6, 7, 8, -1 });
assertEquals(2, counter.get(-1));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/subarray/SubarrayMeanBruteForceUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/subarray/SubarrayMeanBruteForceUnitTest.java | package com.baeldung.algorithms.subarray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SubarrayMeanBruteForceUnitTest {
@Test
void givenMultipleTestCases_thenReturnTheCorrectCount() {
int[][] testCases = {
{5, 3, 6, 2},
{1, 1, 1},
{2, 2, 2, 2},
{1, 2, 3, 4},
{},
};
int[] targets = {4, 1, 3, 2, 0};
int[] expected = {3, 6, 0, 2, 0};
for (int i = 0; i < testCases.length; i++) {
int actual = SubarrayMeansBruteForce.countSubarraysWithMean(testCases[i], targets[i]);
assertEquals(expected[i], actual, "Test case " + (i + 1));
}
}
@Test
void givenSingleValueWithSameTargetMean_thenCountCorrectly() {
int[] arr = {5};
assertEquals(1, SubarrayMeansBruteForce.countSubarraysWithMean(arr, 5));
assertEquals(0, SubarrayMeansBruteForce.countSubarraysWithMean(arr, 0));
}
@Test
void givenMultipleZeros_thenReturnPermutationCount() {
int[] arr = {0, 0, 0, 0};
assertEquals(10, SubarrayMeansBruteForce.countSubarraysWithMean(arr, 0));
assertEquals(0, SubarrayMeansBruteForce.countSubarraysWithMean(arr, 1));
}
@Test
void givenLargeNumbers_thenReturnCountCorrectly() {
int[] arr = {1_000_000_000, 2_000_000_000};
assertEquals(1, SubarrayMeansBruteForce.countSubarraysWithMean(arr, 1_500_000_000));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/subarray/SubarrayMeanPrefixSumsUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/subarray/SubarrayMeanPrefixSumsUnitTest.java | package com.baeldung.algorithms.subarray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SubarrayMeanPrefixSumsUnitTest {
@Test
void givenMultipleTestCases_thenReturnTheCorrectCount() {
int[][] testCases = {
{5, 3, 6, 2},
{1, 1, 1},
{2, 2, 2, 2},
{1, 2, 3, 4},
{},
};
int[] targets = {4, 1, 3, 2, 0};
int[] expected = {3, 6, 0, 2, 0};
for (int i = 0; i < testCases.length; i++) {
int actual = SubarrayMeansPrefixSums.countSubarraysWithMean(testCases[i], targets[i]);
assertEquals(expected[i], actual, "Test case " + (i + 1));
}
}
@Test
void givenSingleValueWithSameTargetMean_whenMeanIs5_thenReturn1() {
int[] arr = {5};
assertEquals(1, SubarrayMeansPrefixSums.countSubarraysWithMean(arr, 5));
assertEquals(0, SubarrayMeansPrefixSums.countSubarraysWithMean(arr, 0));
}
@Test
void givenMultipleZeros_thenReturnPermutationCount() {
int[] arr = {0, 0, 0, 0};
assertEquals(10, SubarrayMeansPrefixSums.countSubarraysWithMean(arr, 0));
assertEquals(0, SubarrayMeansPrefixSums.countSubarraysWithMean(arr, 1));
}
@Test
void givenLargeNumbers_thenCountCorrectly() {
int[] arr = {1_000_000_000, 2_000_000_000};
assertEquals(1, SubarrayMeansPrefixSums.countSubarraysWithMean(arr, 1_500_000_000));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java | package com.baeldung.algorithms.editdistance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class EditDistanceUnitTest {
@ParameterizedTest
@MethodSource("provideArguments")
void testEditDistance_RecursiveImplementation(String x, String y, int result) {
assertEquals(result, EditDistanceRecursive.calculate(x, y));
}
@ParameterizedTest
@MethodSource("provideArguments")
void testEditDistance_givenDynamicProgrammingImplementation(String x, String y, int result) {
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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/modearray/ModeOfArrayUnitTest.java | algorithms-modules/algorithms-miscellaneous-9/src/test/java/com/baeldung/algorithms/modearray/ModeOfArrayUnitTest.java | package com.baeldung.algorithms.modearray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class ModeOfArrayUnitTest {
@Test
public void givenArray_whenFindUsingFrequencyCount_thenOutputMode() {
int[] nums = { 1, 2, 2, 3, 3, 4, 4, 4, 5 };
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int maxFrequency = 0;
for (int frequency : frequencyMap.values()) {
if (frequency > maxFrequency) {
maxFrequency = frequency;
}
}
Set<Integer> modes = new HashSet<>();
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() == maxFrequency) {
modes.add(entry.getKey());
}
}
Set<Integer> expected = new HashSet<>(Arrays.asList(4));
assertEquals(expected, modes);
}
@Test
public void givenArray_whenFindUsingSorting_thenOutputMode() {
int[] nums = { 1, 2, 2, 3, 3, 4, 4, 4, 5 };
Arrays.sort(nums);
int maxCount = 1;
int currentCount = 1;
Set<Integer> modes = new HashSet<>();
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
currentCount++;
} else {
currentCount = 1;
}
if (currentCount > maxCount) {
maxCount = currentCount;
modes.clear();
modes.add(nums[i]);
} else if (currentCount == maxCount) {
modes.add(nums[i]);
}
}
if (nums.length == 1) {
modes.add(nums[0]);
}
Set<Integer> expected = new HashSet<>(Arrays.asList(4));
assertEquals(expected, modes);
}
@Test
public void givenArray_whenFindUsingTreeMap_thenOutputMode() {
int[] nums = { 1, 2, 2, 3, 3, 4, 4, 4, 5 };
Map<Integer, Integer> frequencyMap = new TreeMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int maxFrequency = 0;
for (int frequency : frequencyMap.values()) {
if (frequency > maxFrequency) {
maxFrequency = frequency;
}
}
Set<Integer> modes = new HashSet<>();
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() == maxFrequency) {
modes.add(entry.getKey());
}
}
Set<Integer> expected = new HashSet<>(Arrays.asList(4));
assertEquals(expected, modes);
}
@Test
public void givenArray_whenFindUsingStream_thenOutputMode() {
int[] nums = { 1, 2, 2, 3, 3, 4, 4, 4, 5 };
Map<Integer, Long> frequencyMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
long maxFrequency = Collections.max(frequencyMap.values());
Set<Integer> modes = frequencyMap.entrySet()
.stream()
.filter(entry -> entry.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
Set<Integer> expected = new HashSet<>(Arrays.asList(4));
assertEquals(expected, modes);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.