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-2/src/main/java/com/baeldung/algorithms/astar/RouteNode.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/RouteNode.java
package com.baeldung.algorithms.astar; import java.util.StringJoiner; class RouteNode<T extends GraphNode> implements Comparable<RouteNode> { private final T current; private T previous; private double routeScore; private double estimatedScore; RouteNode(T current) { this(current, null, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } RouteNode(T current, T previous, double routeScore, double estimatedScore) { this.current = current; this.previous = previous; this.routeScore = routeScore; this.estimatedScore = estimatedScore; } T getCurrent() { return current; } T getPrevious() { return previous; } double getRouteScore() { return routeScore; } double getEstimatedScore() { return estimatedScore; } void setPrevious(T previous) { this.previous = previous; } void setRouteScore(double routeScore) { this.routeScore = routeScore; } void setEstimatedScore(double estimatedScore) { this.estimatedScore = estimatedScore; } @Override public int compareTo(RouteNode other) { if (this.estimatedScore > other.estimatedScore) { return 1; } else if (this.estimatedScore < other.estimatedScore) { return -1; } else { return 0; } } @Override public String toString() { return new StringJoiner(", ", RouteNode.class.getSimpleName() + "[", "]").add("current=" + current) .add("previous=" + previous).add("routeScore=" + routeScore).add("estimatedScore=" + estimatedScore) .toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/Graph.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/Graph.java
package com.baeldung.algorithms.astar; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class Graph<T extends GraphNode> { private final Set<T> nodes; private final Map<String, Set<String>> connections; public Graph(Set<T> nodes, Map<String, Set<String>> connections) { this.nodes = nodes; this.connections = connections; } public T getNode(String id) { return nodes.stream() .filter(node -> node.getId().equals(id)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No node found with ID")); } public Set<T> getConnections(T node) { return connections.get(node.getId()).stream() .map(this::getNode) .collect(Collectors.toSet()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/Scorer.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/Scorer.java
package com.baeldung.algorithms.astar; public interface Scorer<T extends GraphNode> { double computeCost(T from, T to); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/RouteFinder.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/RouteFinder.java
package com.baeldung.algorithms.astar; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j public class RouteFinder<T extends GraphNode> { private final Graph<T> graph; private final Scorer<T> nextNodeScorer; private final Scorer<T> targetScorer; public RouteFinder(Graph<T> graph, Scorer<T> nextNodeScorer, Scorer<T> targetScorer) { this.graph = graph; this.nextNodeScorer = nextNodeScorer; this.targetScorer = targetScorer; } public List<T> findRoute(T from, T to) { Map<T, RouteNode<T>> allNodes = new HashMap<>(); Queue<RouteNode> openSet = new PriorityQueue<>(); RouteNode<T> start = new RouteNode<>(from, null, 0d, targetScorer.computeCost(from, to)); allNodes.put(from, start); openSet.add(start); while (!openSet.isEmpty()) { log.debug("Open Set contains: " + openSet.stream().map(RouteNode::getCurrent).collect(Collectors.toSet())); RouteNode<T> next = openSet.poll(); log.debug("Looking at node: " + next); if (next.getCurrent().equals(to)) { log.debug("Found our destination!"); List<T> route = new ArrayList<>(); RouteNode<T> current = next; do { route.add(0, current.getCurrent()); current = allNodes.get(current.getPrevious()); } while (current != null); log.debug("Route: " + route); return route; } graph.getConnections(next.getCurrent()).forEach(connection -> { double newScore = next.getRouteScore() + nextNodeScorer.computeCost(next.getCurrent(), connection); RouteNode<T> nextNode = allNodes.getOrDefault(connection, new RouteNode<>(connection)); allNodes.put(connection, nextNode); if (nextNode.getRouteScore() > newScore) { nextNode.setPrevious(next.getCurrent()); nextNode.setRouteScore(newScore); nextNode.setEstimatedScore(newScore + targetScorer.computeCost(connection, to)); openSet.add(nextNode); log.debug("Found a better route to node: " + nextNode); } }); } throw new IllegalStateException("No route found"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/GraphNode.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/GraphNode.java
package com.baeldung.algorithms.astar; public interface GraphNode { String getId(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/underground/Station.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/underground/Station.java
package com.baeldung.algorithms.astar.underground; import java.util.StringJoiner; import com.baeldung.algorithms.astar.GraphNode; public class Station implements GraphNode { private final String id; private final String name; private final double latitude; private final double longitude; public Station(String id, String name, double latitude, double longitude) { this.id = id; this.name = name; this.latitude = latitude; this.longitude = longitude; } @Override public String getId() { return id; } public String getName() { return name; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override public String toString() { return new StringJoiner(", ", Station.class.getSimpleName() + "[", "]").add("id='" + id + "'") .add("name='" + name + "'").add("latitude=" + latitude).add("longitude=" + longitude).toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/underground/HaversineScorer.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/astar/underground/HaversineScorer.java
package com.baeldung.algorithms.astar.underground; import com.baeldung.algorithms.astar.Scorer; public class HaversineScorer implements Scorer<Station> { @Override public double computeCost(Station from, Station to) { double R = 6372.8; // In kilometers double dLat = Math.toRadians(to.getLatitude() - from.getLatitude()); double dLon = Math.toRadians(to.getLongitude() - from.getLongitude()); double lat1 = Math.toRadians(from.getLatitude()); double lat2 = Math.toRadians(to.getLatitude()); double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java
package com.baeldung.algorithms.bubblesort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class BubbleSortUnitTest { @Test void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.bubbleSort(array); assertArrayEquals(array, sortedArray); } @Test void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.optimizedBubbleSort(array); assertArrayEquals(array, sortedArray); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/counting/CountingSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/counting/CountingSortUnitTest.java
package com.baeldung.algorithms.counting; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class CountingSortUnitTest { @Test void countElements_GivenAnArray_ShouldCalculateTheFrequencyArrayAsExpected() { int k = 5; int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 }; int[] c = CountingSort.countElements(input, k); int[] expected = { 1, 2, 4, 6, 8, 11 }; assertArrayEquals(expected, c); } @Test void sort_GivenAnArray_ShouldSortTheInputAsExpected() { int k = 5; int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 }; int[] sorted = CountingSort.sort(input, k); // Our sorting algorithm and Java's should return the same result Arrays.sort(input); assertArrayEquals(input, sorted); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java
package com.baeldung.algorithms.selectionsort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class SelectionSortUnitTest { @Test void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() { int[] input = { 5, 4, 1, 6, 2 }; SelectionSort.sortAscending(input); int[] expected = {1, 2, 4, 5, 6}; assertArrayEquals(expected, input, "the two arrays are not equal"); } @Test void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() { int[] input = { 5, 4, 1, 6, 2 }; SelectionSort.sortDescending(input); int[] expected = {6, 5, 4, 2, 1}; assertArrayEquals(expected, input, "the two arrays are not equal"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java
package com.baeldung.algorithms.quicksort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class BentleyMcilroyPartitioningUnitTest { @Test void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java
package com.baeldung.algorithms.quicksort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class DNFThreeWayQuickSortUnitTest { @Test void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java
package com.baeldung.algorithms.heapsort; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class HeapUnitTest { @Test void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() { // given Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2); // when int head = heap.pop(); // then assertThat(head).isEqualTo(1); } @Test void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() { // given List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2); // when List<Integer> sortedElements = Heap.sort(elements); // then assertThat(sortedElements).isEqualTo(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-sorting-2/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java
package com.baeldung.algorithms.radixsort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class RadixSortUnitTest { @Test void givenUnsortedArray_whenRadixSort_thenArraySorted() { int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 }; RadixSort.sort(numbers); int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 }; assertArrayEquals(numbersSorted, numbers); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java
package com.baeldung.algorithms.insertionsort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class InsertionSortUnitTest { @Test void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { int[] input = {6, 2, 3, 4, 5, 1}; InsertionSort.insertionSortImperative(input); int[] expected = {1, 2, 3, 4, 5, 6}; assertArrayEquals(expected, input, "the two arrays are not equal"); } @Test void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { int[] input = {6, 4, 5, 2, 3, 1}; InsertionSort.insertionSortRecursive(input); int[] expected = {1, 2, 3, 4, 5, 6}; assertArrayEquals( expected, input, "the two arrays are not equal"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java
algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java
package com.baeldung.algorithms.bynumber; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class NaturalOrderComparatorsUnitTest { @Test void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d"); testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4"); assertEquals(expected, testStrings); } @Test void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d"); testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4"); assertEquals(expected, testStrings); } @Test void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d"); testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4"); assertEquals(expected, testStrings); } @Test void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5 List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" ); testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); assertEquals(expected, testStrings); } @Test void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { List<String> testStrings = Arrays.asList("a", "c", "d", "e"); List<String> expected = new ArrayList<>(testStrings); testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); assertEquals(expected, testStrings); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java
package com.baeldung.algorithms.bubblesort; import java.util.stream.IntStream; public class BubbleSort { void bubbleSort(Integer[] arr) { int n = arr.length; IntStream.range(0, n - 1) .flatMap(i -> IntStream.range(1, n - i)) .forEach(j -> { if (arr[j - 1] > arr[j]) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } }); } void optimizedBubbleSort(Integer[] arr) { int i = 0, n = arr.length; boolean swapNeeded = true; while (i < n - 1 && swapNeeded) { swapNeeded = false; for (int j = 1; j < n - i; j++) { if (arr[j - 1] > arr[j]) { int temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; swapNeeded = true; } } if (!swapNeeded) break; i++; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/counting/CountingSort.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/counting/CountingSort.java
package com.baeldung.algorithms.counting; import java.util.Arrays; import java.util.stream.IntStream; public class CountingSort { public static int[] sort(int[] input, int k) { verifyPreconditions(input, k); if (input.length == 0) return input; int[] c = countElements(input, k); int[] sorted = new int[input.length]; for (int i = input.length - 1; i >= 0; i--) { int current = input[i]; sorted[c[current] - 1] = current; c[current] -= 1; } return sorted; } static int[] countElements(int[] input, int k) { int[] c = new int[k + 1]; Arrays.fill(c, 0); for (int i : input) { c[i] += 1; } for (int i = 1; i < c.length; i++) { c[i] += c[i - 1]; } return c; } private static void verifyPreconditions(int[] input, int k) { if (input == null) { throw new IllegalArgumentException("Input is required"); } int min = IntStream.of(input).min().getAsInt(); int max = IntStream.of(input).max().getAsInt(); if (min < 0 || max > k) { throw new IllegalArgumentException("The input numbers should be between zero and " + k); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/selectionsort/SelectionSort.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/selectionsort/SelectionSort.java
package com.baeldung.algorithms.selectionsort; public class SelectionSort { public static void sortAscending(final int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minElementIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[minElementIndex] > arr[j]) { minElementIndex = j; } } if (minElementIndex != i) { int temp = arr[i]; arr[i] = arr[minElementIndex]; arr[minElementIndex] = temp; } } } public static void sortDescending(final int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int maxElementIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[maxElementIndex] < arr[j]) { maxElementIndex = j; } } if (maxElementIndex != i) { int temp = arr[i]; arr[i] = arr[maxElementIndex]; arr[maxElementIndex] = temp; } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java
package com.baeldung.algorithms.quicksort; public class SortingUtils { public static void swap(int[] array, int position1, int position2) { if (position1 != position2) { int temp = array[position1]; array[position1] = array[position2]; array[position2] = temp; } } public static int compare(int num1, int num2) { if (num1 > num2) return 1; else if (num1 < num2) return -1; else return 0; } public static void printArray(int[] array) { if (array == null) { return; } for (int e : array) { System.out.print(e + " "); } System.out.println(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java
package com.baeldung.algorithms.quicksort; public class Partition { private int left; private int right; public Partition(int left, int right) { super(); this.left = left; this.right = right; } public int getLeft() { return left; } public void setLeft(int left) { this.left = left; } public int getRight() { return right; } public void setRight(int right) { this.right = right; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java
package com.baeldung.algorithms.quicksort; import static com.baeldung.algorithms.quicksort.SortingUtils.swap; public class BentleyMcIlroyPartioning { public static Partition partition(int input[], int begin, int end) { int left = begin, right = end; int leftEqualKeysCount = 0, rightEqualKeysCount = 0; int partitioningValue = input[end]; while (true) { while (input[left] < partitioningValue) left++; while (input[right] > partitioningValue) { if (right == begin) break; right--; } if (left == right && input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; left++; } if (left >= right) { break; } swap(input, left, right); if (input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; } if (input[right] == partitioningValue) { swap(input, right, end - rightEqualKeysCount); rightEqualKeysCount++; } left++; right--; } right = left - 1; for (int k = begin; k < begin + leftEqualKeysCount; k++, right--) { if (right >= begin + leftEqualKeysCount) swap(input, k, right); } for (int k = end; k > end - rightEqualKeysCount; k--, left++) { if (left <= end - rightEqualKeysCount) swap(input, left, k); } return new Partition(right + 1, left - 1); } public static void quicksort(int input[], int begin, int end) { if (end <= begin) return; Partition middlePartition = partition(input, begin, end); quicksort(input, begin, middlePartition.getLeft() - 1); quicksort(input, middlePartition.getRight() + 1, end); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java
package com.baeldung.algorithms.quicksort; import static com.baeldung.algorithms.quicksort.SortingUtils.compare; import static com.baeldung.algorithms.quicksort.SortingUtils.swap; public class DutchNationalFlagPartioning { public static Partition partition(int[] input, int begin, int end) { int lt = begin, current = begin, gt = end; int partitioningValue = input[begin]; while (current <= gt) { int compareCurrent = compare(input[current], partitioningValue); switch (compareCurrent) { case -1: swap(input, current++, lt++); break; case 0: current++; break; case 1: swap(input, current, gt--); break; } } return new Partition(lt, gt); } public static void quicksort(int[] input, int begin, int end) { if (end <= begin) return; Partition middlePartition = partition(input, begin, end); quicksort(input, begin, middlePartition.getLeft() - 1); quicksort(input, middlePartition.getRight() + 1, end); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/heapsort/Heap.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/heapsort/Heap.java
package com.baeldung.algorithms.heapsort; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Heap<E extends Comparable<E>> { private List<E> elements = new ArrayList<>(); public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) { Heap<E> heap = of(elements); List<E> result = new ArrayList<>(); while (!heap.isEmpty()) { result.add(heap.pop()); } return result; } public static <E extends Comparable<E>> Heap<E> of(E... elements) { return of(Arrays.asList(elements)); } public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) { Heap<E> result = new Heap<>(); for (E element : elements) { result.add(element); } return result; } public void add(E e) { elements.add(e); int elementIndex = elements.size() - 1; while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) { int parentIndex = parentIndex(elementIndex); swap(elementIndex, parentIndex); elementIndex = parentIndex; } } public E pop() { if (isEmpty()) { throw new IllegalStateException("You cannot pop from an empty heap"); } E result = elementAt(0); int lasElementIndex = elements.size() - 1; swap(0, lasElementIndex); elements.remove(lasElementIndex); int elementIndex = 0; while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) { int smallerChildIndex = smallerChildIndex(elementIndex); swap(elementIndex, smallerChildIndex); elementIndex = smallerChildIndex; } return result; } public boolean isEmpty() { return elements.isEmpty(); } private boolean isRoot(int index) { return index == 0; } private int smallerChildIndex(int index) { int leftChildIndex = leftChildIndex(index); int rightChildIndex = rightChildIndex(index); if (!isValidIndex(rightChildIndex)) { return leftChildIndex; } if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) { return leftChildIndex; } return rightChildIndex; } private boolean isLeaf(int index) { return !isValidIndex(leftChildIndex(index)); } private boolean isCorrectParent(int index) { return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index)); } private boolean isCorrectChild(int index) { return isCorrect(parentIndex(index), index); } private boolean isCorrect(int parentIndex, int childIndex) { if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) { return true; } return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0; } private boolean isValidIndex(int index) { return index < elements.size(); } private void swap(int index1, int index2) { E element1 = elementAt(index1); E element2 = elementAt(index2); elements.set(index1, element2); elements.set(index2, element1); } private E elementAt(int index) { return elements.get(index); } private int parentIndex(int index) { return (index - 1) / 2; } private int leftChildIndex(int index) { return 2 * index + 1; } private int rightChildIndex(int index) { return 2 * index + 2; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/radixsort/RadixSort.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/radixsort/RadixSort.java
package com.baeldung.algorithms.radixsort; import java.util.Arrays; public class RadixSort { public static void sort(int numbers[]) { int maximumNumber = findMaximumNumberIn(numbers); int numberOfDigits = calculateNumberOfDigitsIn(maximumNumber); int placeValue = 1; while (numberOfDigits-- > 0) { applyCountingSortOn(numbers, placeValue); placeValue *= 10; } } private static void applyCountingSortOn(int[] numbers, int placeValue) { int range = 10; // radix or the base int length = numbers.length; int[] frequency = new int[range]; int[] sortedValues = new int[length]; for (int i = 0; i < length; i++) { int digit = (numbers[i] / placeValue) % range; frequency[digit]++; } for (int i = 1; i < range; i++) { frequency[i] += frequency[i - 1]; } for (int i = length - 1; i >= 0; i--) { int digit = (numbers[i] / placeValue) % range; sortedValues[frequency[digit] - 1] = numbers[i]; frequency[digit]--; } System.arraycopy(sortedValues, 0, numbers, 0, length); } private static int calculateNumberOfDigitsIn(int number) { return (int) Math.log10(number) + 1; // valid only if number > 0 } private static int findMaximumNumberIn(int[] arr) { return Arrays.stream(arr).max().getAsInt(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java
package com.baeldung.algorithms.insertionsort; public class InsertionSort { public static void insertionSortImperative(int[] input) { for (int i = 1; i < input.length; i++) { int key = input[i]; int j = i - 1; while (j >= 0 && input[j] > key) { input[j + 1] = input[j]; j = j - 1; } input[j + 1] = key; } } public static void insertionSortRecursive(int[] input) { insertionSortRecursive(input, input.length); } private static void insertionSortRecursive(int[] input, int i) { // base case if (i <= 1) { return; } // sort the first i - 1 elements of the array insertionSortRecursive(input, i - 1); // then find the correct position of the element at position i int key = input[i - 1]; int j = i - 2; // shifting the elements from their position by 1 while (j >= 0 && input[j] > key) { input[j + 1] = input[j]; j = j - 1; } // inserting the key at the appropriate position input[j + 1] = key; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java
algorithms-modules/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java
package com.baeldung.algorithms.bynumber; import java.util.Comparator; public final class NaturalOrderComparators { private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]"; private NaturalOrderComparators() { throw new AssertionError("Let's keep this static"); } public static Comparator<String> createNaturalOrderRegexComparator() { return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber); } private static double parseStringToNumber(String input){ final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, ""); if("".equals(digitsOnly)) return 0; try{ return Double.parseDouble(digitsOnly); }catch (NumberFormatException nfe){ return 0; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java
package com.baeldung.algorithms.mergesort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class MergeSortUnitTest { @Test void positiveTest() { int[] actual = { 5, 1, 6, 2, 3, 4 }; int[] expected = { 1, 2, 3, 4, 5, 6 }; MergeSort.mergeSort(actual, actual.length); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java
package com.baeldung.algorithms.quicksort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class QuickSortUnitTest { @Test void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 }; int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; QuickSort.quickSort(actual, 0, actual.length-1); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java
package com.baeldung.algorithms.quicksort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class ThreeWayQuickSortUnitTest { @Test public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 }; int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 }; ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AlphanumericSortUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AlphanumericSortUnitTest.java
package com.baeldung.algorithms.stringsort; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; class AlphanumericSortUnitTest { @Test void givenAlphanumericString_whenLexicographicSort_thenSortLettersFirst() { String stringToSort = "C4B3A21"; String sorted = AlphanumericSort.lexicographicSort(stringToSort); assertThat(sorted).isEqualTo("1234ABC"); } @Test void givenAlphanumericArrayOfStrings_whenAlphanumericSort_thenSortNaturalOrder() { String[] arrayToSort = {"file2", "file10", "file0", "file1", "file20"}; String[] sorted = AlphanumericSort.naturalAlphanumericSort(arrayToSort); assertThat(Arrays.toString(sorted)).isEqualTo("[file0, file1, file2, file10, file20]"); } @Test void givenAlphanumericArrayOfStrings_whenAlphanumericCaseInsensitveSort_thenSortNaturalOrder() { String[] arrayToSort = {"a2", "A10", "b1", "B3", "A2"}; String[] sorted = AlphanumericSort.naturalAlphanumericCaseInsensitiveSort(arrayToSort); assertThat(Arrays.toString(sorted)).isEqualTo("[A2, a2, A10, b1, B3]"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java
package com.baeldung.algorithms.stringsort; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class AnagramValidatorUnitTest { @Test void givenValidAnagrams_whenSorted_thenEqual() { boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali"); assertTrue(isValidAnagram); } @Test void givenNotValidAnagrams_whenSorted_thenNotEqual() { boolean isValidAnagram = AnagramValidator.isValid("abc", "def"); assertFalse(isValidAnagram); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java
package com.baeldung.algorithms.stringsort; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; class SortStringUnitTest { @Test void givenString_whenSort_thenSorted() { String abcd = "bdca"; char[] chars = abcd.toCharArray(); Arrays.sort(chars); String sorted = new String(chars); assertThat(sorted).isEqualTo("abcd"); } @Test void givenString_whenSortJava8_thenSorted() { String sorted = "bdca".chars() .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); assertThat(sorted).isEqualTo("abcd"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/countinginversions/CountingInversionsUnitTest.java
algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/countinginversions/CountingInversionsUnitTest.java
package com.baeldung.algorithms.countinginversions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class CountingInversionsUnitTest { @Test void givenArray_whenCountingInversions_thenReturnCorrectCount() { int[] input = {3, 1, 2}; int expectedInversions = 2; int actualInversions = countInversionsBruteForce(input); assertEquals(expectedInversions, actualInversions); } int countInversionsBruteForce(int[] array) { int inversionCount = 0; for (int i = 0; i < array.length - 1; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { inversionCount++; } } } return inversionCount; } @Test void givenArray_whenCountingInversionsWithOptimizedMethod_thenReturnCorrectCount() { int[] inputArray = {3, 1, 2}; int expectedInversions = 2; int actualInversions = countInversionsDivideAndConquer(inputArray); assertEquals(expectedInversions, actualInversions); } int countInversionsDivideAndConquer(int[] array) { if (array == null || array.length <= 1) { return 0; } return mergeSortAndCount(array, 0, array.length - 1); } int mergeSortAndCount(int[] array, int left, int right) { if (left >= right) { return 0; } int mid = left + (right - left) / 2; int inversions = mergeSortAndCount(array, left, mid) + mergeSortAndCount(array, mid + 1, right); inversions += mergeAndCount(array, left, mid, right); return inversions; } int mergeAndCount(int[] array, int left, int mid, int right) { int[] leftArray = new int[mid - left + 1]; int[] rightArray = new int[right - mid]; System.arraycopy(array, left, leftArray, 0, mid - left + 1); System.arraycopy(array, mid + 1, rightArray, 0, right - mid); int i = 0, j = 0, k = left, inversions = 0; while (i < leftArray.length && j < rightArray.length) { if (leftArray[i] <= rightArray[j]) { array[k++] = leftArray[i++]; } else { array[k++] = rightArray[j++]; inversions += leftArray.length - i; } } while (i < leftArray.length) { array[k++] = leftArray[i++]; } while (j < rightArray.length) { array[k++] = rightArray[j++]; } return inversions; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
package com.baeldung.algorithms.mergesort; public class MergeSort { public static void main(String[] args) { int[] a = { 5, 1, 6, 2, 3, 4 }; mergeSort(a, a.length); for (int i = 0; i < a.length; i++) System.out.println(a[i]); } public static void mergeSort(int[] a, int n) { if (n < 2) return; int mid = n / 2; int[] l = new int[mid]; int[] r = new int[n - mid]; for (int i = 0; i < mid; i++) { l[i] = a[i]; } for (int i = mid; i < n; i++) { r[i - mid] = a[i]; } mergeSort(l, mid); mergeSort(r, n - mid); merge(a, l, r, mid, n - mid); } public static void merge(int[] a, int[] l, int[] r, int left, int right) { int i = 0, j = 0, k = 0; while (i < left && j < right) { if (l[i] <= r[j]) a[k++] = l[i++]; else a[k++] = r[j++]; } while (i < left) a[k++] = l[i++]; while (j < right) a[k++] = r[j++]; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java
algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java
package com.baeldung.algorithms.quicksort; public class ThreeWayQuickSort { public static void threeWayQuickSort(int[] a, int begin, int end) { if (end <= begin) return; // partition int i = begin; int less = begin; int greater = end; while (i <= greater){ if (a[i] < a[less]) { int tmp = a[i]; a[i] = a[less]; a[less] = tmp; i++; less++; } else if (a[less] < a[i]) { int tmp = a[i]; a[i] = a[greater]; a[greater] = tmp; greater--; } else { i++; } } threeWayQuickSort(a, begin, less - 1); threeWayQuickSort(a, greater + 1, end); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java
algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java
package com.baeldung.algorithms.quicksort; public class QuickSort { public static void quickSort(int arr[], int begin, int end) { if (begin < end) { int partitionIndex = partition(arr, begin, end); // Recursively sort elements of the 2 sub-arrays quickSort(arr, begin, partitionIndex-1); quickSort(arr, partitionIndex+1, end); } } private static int partition(int arr[], int begin, int end) { int pivot = arr[end]; int i = (begin-1); for (int j=begin; j<end; j++) { if (arr[j] <= pivot) { i++; int swapTemp = arr[i]; arr[i] = arr[j]; arr[j] = swapTemp; } } int swapTemp = arr[i+1]; arr[i+1] = arr[end]; arr[end] = swapTemp; return i+1; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AlphanumericSort.java
algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AlphanumericSort.java
package com.baeldung.algorithms.stringsort; import java.util.Arrays; import java.util.Comparator; public class AlphanumericSort { public static String lexicographicSort(String input) { char[] stringChars = input.toCharArray(); Arrays.sort(stringChars); return new String(stringChars); } public static String[] naturalAlphanumericSort(String[] arrayToSort) { Arrays.sort(arrayToSort, new Comparator<String>() { @Override public int compare(String s1, String s2) { return extractInt(s1) - extractInt(s2); } private int extractInt(String str) { String num = str.replaceAll("\\D+", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); } }); return arrayToSort; } public static String[] naturalAlphanumericCaseInsensitiveSort(String[] arrayToSort) { Arrays.sort(arrayToSort, Comparator.comparing((String s) -> s.replaceAll("\\d", "").toLowerCase()) .thenComparingInt(s -> { String num = s.replaceAll("\\D+", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); }) .thenComparing(Comparator.naturalOrder())); return arrayToSort; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java
algorithms-modules/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java
package com.baeldung.algorithms.stringsort; import java.util.Arrays; public class AnagramValidator { public static boolean isValid(String text, String anagram) { text = prepare(text); anagram = prepare(anagram); String sortedText = sort(text); String sortedAnagram = sort(anagram); return sortedText.equals(sortedAnagram); } private static String sort(String text) { char[] chars = prepare(text).toCharArray(); Arrays.sort(chars); return new String(chars); } private static String prepare(String text) { return text.toLowerCase() .trim() .replaceAll("\\s+", ""); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
package com.baeldung.algorithms; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; class AntColonyOptimizationLongRunningUnitTest { @Test void testGenerateRandomMatrix() { AntColonyOptimization antTSP = new AntColonyOptimization(5); assertNotNull(antTSP.generateRandomMatrix(5)); } @Test void testStartAntOptimization() { AntColonyOptimization antTSP = new AntColonyOptimization(5); assertNotNull(antTSP.solve()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
package com.baeldung.algorithms; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; class BinaryGeneticAlgorithmLongRunningUnitTest { @Test void testGA() { SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
package com.baeldung.algorithms; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; class SimulatedAnnealingLongRunningUnitTest { @Test void testSimulateAnnealing() { assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
package com.baeldung.algorithms; import java.util.Scanner; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; public class RunAlgorithm { public static void main(String[] args) throws InstantiationException, IllegalAccessException { Scanner in = new Scanner(System.in); System.out.println("Run algorithm:"); System.out.println("1 - Simulated Annealing"); System.out.println("2 - Simple Genetic Algorithm"); System.out.println("3 - Ant Colony"); int decision = in.nextInt(); switch (decision) { case 1: System.out.println( "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); break; case 2: SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); break; case 3: AntColonyOptimization antColony = new AntColonyOptimization(21); antColony.startAntOptimization(); break; default: System.out.println("Unknown option"); break; } in.close(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
package com.baeldung.algorithms.ga.ant_colony; public class Ant { protected int trailSize; protected int trail[]; protected boolean visited[]; public Ant(int tourSize) { this.trailSize = tourSize; this.trail = new int[tourSize]; this.visited = new boolean[tourSize]; } protected void visitCity(int currentIndex, int city) { trail[currentIndex + 1] = city; visited[city] = true; } protected boolean visited(int i) { return visited[i]; } protected double trailLength(double graph[][]) { double length = graph[trail[trailSize - 1]][trail[0]]; for (int i = 0; i < trailSize - 1; i++) { length += graph[trail[i]][trail[i + 1]]; } return length; } protected void clear() { for (int i = 0; i < trailSize; i++) visited[i] = false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
package com.baeldung.algorithms.ga.ant_colony; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.OptionalInt; import java.util.Random; import java.util.stream.IntStream; public class AntColonyOptimization { private double c = 1.0; private double alpha = 1; private double beta = 5; private double evaporation = 0.5; private double Q = 500; private double antFactor = 0.8; private double randomFactor = 0.01; private int maxIterations = 1000; private int numberOfCities; private int numberOfAnts; private double graph[][]; private double trails[][]; private List<Ant> ants = new ArrayList<>(); private Random random = new Random(); private double probabilities[]; private int currentIndex; private int[] bestTourOrder; private double bestTourLength; public AntColonyOptimization(int noOfCities) { graph = generateRandomMatrix(noOfCities); numberOfCities = graph.length; numberOfAnts = (int) (numberOfCities * antFactor); trails = new double[numberOfCities][numberOfCities]; probabilities = new double[numberOfCities]; IntStream.range(0, numberOfAnts) .forEach(i -> ants.add(new Ant(numberOfCities))); } /** * Generate initial solution */ public double[][] generateRandomMatrix(int n) { double[][] randomMatrix = new double[n][n]; IntStream.range(0, n) .forEach(i -> IntStream.range(0, n) .forEach(j -> randomMatrix[i][j] = Math.abs(random.nextInt(100) + 1))); return randomMatrix; } /** * Perform ant optimization */ public void startAntOptimization() { IntStream.rangeClosed(1, 3) .forEach(i -> { System.out.println("Attempt #" + i); solve(); }); } /** * Use this method to run the main logic */ public int[] solve() { setupAnts(); clearTrails(); IntStream.range(0, maxIterations) .forEach(i -> { moveAnts(); updateTrails(); updateBest(); }); System.out.println("Best tour length: " + (bestTourLength - numberOfCities)); System.out.println("Best tour order: " + Arrays.toString(bestTourOrder)); return bestTourOrder.clone(); } /** * Prepare ants for the simulation */ private void setupAnts() { IntStream.range(0, numberOfAnts) .forEach(i -> { ants.forEach(ant -> { ant.clear(); ant.visitCity(-1, random.nextInt(numberOfCities)); }); }); currentIndex = 0; } /** * At each iteration, move ants */ private void moveAnts() { IntStream.range(currentIndex, numberOfCities - 1) .forEach(i -> { ants.forEach(ant -> ant.visitCity(currentIndex, selectNextCity(ant))); currentIndex++; }); } /** * Select next city for each ant */ private int selectNextCity(Ant ant) { int t = random.nextInt(numberOfCities - currentIndex); if (random.nextDouble() < randomFactor) { OptionalInt cityIndex = IntStream.range(0, numberOfCities) .filter(i -> i == t && !ant.visited(i)) .findFirst(); if (cityIndex.isPresent()) { return cityIndex.getAsInt(); } } calculateProbabilities(ant); double r = random.nextDouble(); double total = 0; for (int i = 0; i < numberOfCities; i++) { total += probabilities[i]; if (total >= r) { return i; } } throw new RuntimeException("There are no other cities"); } /** * Calculate the next city picks probabilites */ public void calculateProbabilities(Ant ant) { int i = ant.trail[currentIndex]; double pheromone = 0.0; for (int l = 0; l < numberOfCities; l++) { if (!ant.visited(l)) { pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta); } } for (int j = 0; j < numberOfCities; j++) { if (ant.visited(j)) { probabilities[j] = 0.0; } else { double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta); probabilities[j] = numerator / pheromone; } } } /** * Update trails that ants used */ private void updateTrails() { for (int i = 0; i < numberOfCities; i++) { for (int j = 0; j < numberOfCities; j++) { trails[i][j] *= evaporation; } } for (Ant a : ants) { double contribution = Q / a.trailLength(graph); for (int i = 0; i < numberOfCities - 1; i++) { trails[a.trail[i]][a.trail[i + 1]] += contribution; } trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution; } } /** * Update the best solution */ private void updateBest() { if (bestTourOrder == null) { bestTourOrder = ants.get(0).trail; bestTourLength = ants.get(0) .trailLength(graph); } for (Ant a : ants) { if (a.trailLength(graph) < bestTourLength) { bestTourLength = a.trailLength(graph); bestTourOrder = a.trail.clone(); } } } /** * Clear trails after simulation */ private void clearTrails() { IntStream.range(0, numberOfCities) .forEach(i -> { IntStream.range(0, numberOfCities) .forEach(j -> trails[i][j] = c); }); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
package com.baeldung.algorithms.ga.jenetics; import static java.util.Objects.requireNonNull; import org.jenetics.util.ISeq; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class SpringsteenRecord { String name; double price; ISeq<String> songs; public SpringsteenRecord(String name, double price, ISeq<String> songs) { this.name = requireNonNull(name); this.price = price; this.songs = requireNonNull(songs); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
package com.baeldung.algorithms.ga.jenetics; import java.util.Random; import java.util.stream.Collector; import org.jenetics.util.RandomRegistry; public class KnapsackItem { public double size; public double value; public KnapsackItem(double size, double value) { this.size = size; this.value = value; } protected static KnapsackItem random() { Random r = RandomRegistry.getRandom(); return new KnapsackItem(r.nextDouble() * 100, r.nextDouble() * 100); } protected static Collector<KnapsackItem, ?, KnapsackItem> toSum() { return Collector.of(() -> new double[2], (a, b) -> { a[0] += b.size; a[1] += b.value; } , (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; } , r -> new KnapsackItem(r[0], r[1])); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
package com.baeldung.algorithms.ga.jenetics; import static java.lang.Math.PI; import static java.lang.Math.abs; import static java.lang.Math.sin; import static org.jenetics.engine.EvolutionResult.toBestPhenotype; import static org.jenetics.engine.limit.bySteadyFitness; import java.util.stream.IntStream; import org.jenetics.EnumGene; import org.jenetics.Optimize; import org.jenetics.PartiallyMatchedCrossover; import org.jenetics.Phenotype; import org.jenetics.SwapMutator; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionStatistics; import org.jenetics.engine.codecs; public class TravelingSalesman { private static final int STOPS = 50; private static final double[][] ADJACENCE = matrix(STOPS); private static double[][] matrix(int stops) { final double radius = 100.0; double[][] matrix = new double[stops][stops]; for (int i = 0; i < stops; ++i) { for (int j = 0; j < stops; ++j) { matrix[i][j] = chord(stops, abs(i - j), radius); } } return matrix; } private static double chord(int stops, int i, double r) { return 2.0 * r * abs(sin(PI * i / stops)); } private static double dist(final int[] path) { return IntStream.range(0, STOPS) .mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]]) .sum(); } public static void main(String[] args) { final Engine<EnumGene<Integer>, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS)) .optimize(Optimize.MINIMUM) .maximalPhenotypeAge(11) .populationSize(500) .alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35)) .build(); final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); final Phenotype<EnumGene<Integer>, Double> best = engine.stream() .limit(bySteadyFitness(15)) .limit(250) .peek(statistics) .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
package com.baeldung.algorithms.ga.jenetics; import static org.jenetics.engine.EvolutionResult.toBestPhenotype; import static org.jenetics.engine.limit.bySteadyFitness; import java.util.stream.Stream; import org.jenetics.BitChromosome; import org.jenetics.BitGene; import org.jenetics.Mutator; import org.jenetics.Phenotype; import org.jenetics.RouletteWheelSelector; import org.jenetics.SinglePointCrossover; import org.jenetics.TournamentSelector; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionStatistics; //The main class. public class Knapsack { public static void main(String[] args) { int nItems = 15; double ksSize = nItems * 100.0 / 3.0; KnapsackFF ff = new KnapsackFF(Stream.generate(KnapsackItem::random) .limit(nItems) .toArray(KnapsackItem[]::new), ksSize); Engine<BitGene, Double> engine = Engine.builder(ff, BitChromosome.of(nItems, 0.5)) .populationSize(500) .survivorsSelector(new TournamentSelector<>(5)) .offspringSelector(new RouletteWheelSelector<>()) .alterers(new Mutator<>(0.115), new SinglePointCrossover<>(0.16)) .build(); EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); Phenotype<BitGene, Double> best = engine.stream() .limit(bySteadyFitness(7)) .limit(100) .peek(statistics) .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
package com.baeldung.algorithms.ga.jenetics; import org.jenetics.BitChromosome; import org.jenetics.BitGene; import org.jenetics.Genotype; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionResult; import org.jenetics.util.Factory; public class SimpleGeneticAlgorithm { private static Integer eval(Genotype<BitGene> gt) { return gt.getChromosome() .as(BitChromosome.class) .bitCount(); } public static void main(String[] args) { Factory<Genotype<BitGene>> gtf = Genotype.of(BitChromosome.of(10, 0.5)); System.out.println("Before the evolution:\n" + gtf); Engine<BitGene, Integer> engine = Engine.builder(SimpleGeneticAlgorithm::eval, gtf) .build(); Genotype<BitGene> result = engine.stream() .limit(500) .collect(EvolutionResult.toBestGenotype()); System.out.println("After the evolution:\n" + result); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
package com.baeldung.algorithms.ga.jenetics; import static java.util.Objects.requireNonNull; import java.util.Random; import java.util.function.Function; import org.jenetics.EnumGene; import org.jenetics.Mutator; import org.jenetics.PartiallyMatchedCrossover; import org.jenetics.Phenotype; import org.jenetics.engine.Codec; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionResult; import org.jenetics.engine.Problem; import org.jenetics.engine.codecs; import org.jenetics.engine.limit; import org.jenetics.util.ISeq; import org.jenetics.util.LCG64ShiftRandom; public class SubsetSum implements Problem<ISeq<Integer>, EnumGene<Integer>, Integer> { private ISeq<Integer> basicSet; private int size; public SubsetSum(ISeq<Integer> basicSet, int size) { this.basicSet = requireNonNull(basicSet); this.size = size; } @Override public Function<ISeq<Integer>, Integer> fitness() { return subset -> Math.abs(subset.stream() .mapToInt(Integer::intValue) .sum()); } @Override public Codec<ISeq<Integer>, EnumGene<Integer>> codec() { return codecs.ofSubSet(basicSet, size); } public static SubsetSum of(int n, int k, Random random) { return new SubsetSum(random.doubles() .limit(n) .mapToObj(d -> (int) ((d - 0.5) * n)) .collect(ISeq.toISeq()), k); } public static void main(String[] args) { SubsetSum problem = of(500, 15, new LCG64ShiftRandom(101010)); Engine<EnumGene<Integer>, Integer> engine = Engine.builder(problem) .minimizing() .maximalPhenotypeAge(5) .alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3)) .build(); Phenotype<EnumGene<Integer>, Integer> result = engine.stream() .limit(limit.bySteadyFitness(55)) .collect(EvolutionResult.toBestPhenotype()); System.out.print(result); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
package com.baeldung.algorithms.ga.jenetics; import java.util.function.Function; import org.jenetics.BitChromosome; import org.jenetics.BitGene; import org.jenetics.Genotype; public class KnapsackFF implements Function<Genotype<BitGene>, Double> { private KnapsackItem[] items; private double size; public KnapsackFF(KnapsackItem[] items, double size) { this.items = items; this.size = size; } @Override public Double apply(Genotype<BitGene> gt) { KnapsackItem sum = ((BitChromosome) gt.getChromosome()).ones() .mapToObj(i -> items[i]) .collect(KnapsackItem.toSum()); return sum.size <= this.size ? sum.value : 0; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
package com.baeldung.algorithms.ga.jenetics; import static java.util.Objects.requireNonNull; import java.util.function.Function; import java.util.stream.Collectors; import org.jenetics.BitGene; import org.jenetics.engine.Codec; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionResult; import org.jenetics.engine.Problem; import org.jenetics.engine.codecs; import org.jenetics.util.ISeq; public class SpringsteenProblem implements Problem<ISeq<SpringsteenRecord>, BitGene, Double> { private ISeq<SpringsteenRecord> records; private double maxPricePerUniqueSong; public SpringsteenProblem(ISeq<SpringsteenRecord> records, double maxPricePerUniqueSong) { this.records = requireNonNull(records); this.maxPricePerUniqueSong = maxPricePerUniqueSong; } @Override public Function<ISeq<SpringsteenRecord>, Double> fitness() { return SpringsteenRecords -> { double cost = SpringsteenRecords.stream() .mapToDouble(r -> r.price) .sum(); int uniqueSongCount = SpringsteenRecords.stream() .flatMap(r -> r.songs.stream()) .collect(Collectors.toSet()) .size(); double pricePerUniqueSong = cost / uniqueSongCount; return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0; }; } @Override public Codec<ISeq<SpringsteenRecord>, BitGene> codec() { return codecs.ofSubSet(records); } public static void main(String[] args) { double maxPricePerUniqueSong = 2.5; SpringsteenProblem springsteen = new SpringsteenProblem( ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")), new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")), new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))), maxPricePerUniqueSong); Engine<BitGene, Double> engine = Engine.builder(springsteen) .build(); ISeq<SpringsteenRecord> result = springsteen.codec() .decoder() .apply(engine.stream() .limit(10) .collect(EvolutionResult.toBestGenotype())); double cost = result.stream() .mapToDouble(r -> r.price) .sum(); int uniqueSongCount = result.stream() .flatMap(r -> r.songs.stream()) .collect(Collectors.toSet()) .size(); double pricePerUniqueSong = cost / uniqueSongCount; System.out.println("Overall cost: " + cost); System.out.println("Unique songs: " + uniqueSongCount); System.out.println("Cost per song: " + pricePerUniqueSong); System.out.println("Records: " + result.map(r -> r.name) .toString(", ")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
package com.baeldung.algorithms.ga.binary; import lombok.Data; @Data public class SimpleGeneticAlgorithm { private static final double uniformRate = 0.5; private static final double mutationRate = 0.025; private static final int tournamentSize = 5; private static final boolean elitism = true; private static byte[] solution = new byte[64]; public boolean runAlgorithm(int populationSize, String solution) { if (solution.length() != SimpleGeneticAlgorithm.solution.length) { throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); } setSolution(solution); Population myPop = new Population(populationSize, true); int generationCount = 1; while (myPop.getFittest().getFitness() < getMaxFitness()) { System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); myPop = evolvePopulation(myPop); generationCount++; } System.out.println("Solution found!"); System.out.println("Generation: " + generationCount); System.out.println("Genes: "); System.out.println(myPop.getFittest()); return true; } public Population evolvePopulation(Population pop) { int elitismOffset; Population newPopulation = new Population(pop.getIndividuals().size(), false); if (elitism) { newPopulation.getIndividuals().add(0, pop.getFittest()); elitismOffset = 1; } else { elitismOffset = 0; } for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { Individual indiv1 = tournamentSelection(pop); Individual indiv2 = tournamentSelection(pop); Individual newIndiv = crossover(indiv1, indiv2); newPopulation.getIndividuals().add(i, newIndiv); } for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { mutate(newPopulation.getIndividual(i)); } return newPopulation; } private Individual crossover(Individual indiv1, Individual indiv2) { Individual newSol = new Individual(); for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { if (Math.random() <= uniformRate) { newSol.setSingleGene(i, indiv1.getSingleGene(i)); } else { newSol.setSingleGene(i, indiv2.getSingleGene(i)); } } return newSol; } private void mutate(Individual indiv) { for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { if (Math.random() <= mutationRate) { byte gene = (byte) Math.round(Math.random()); indiv.setSingleGene(i, gene); } } } private Individual tournamentSelection(Population pop) { Population tournament = new Population(tournamentSize, false); for (int i = 0; i < tournamentSize; i++) { int randomId = (int) (Math.random() * pop.getIndividuals().size()); tournament.getIndividuals().add(i, pop.getIndividual(randomId)); } Individual fittest = tournament.getFittest(); return fittest; } protected static int getFitness(Individual individual) { int fitness = 0; for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { if (individual.getSingleGene(i) == solution[i]) { fitness++; } } return fitness; } protected int getMaxFitness() { int maxFitness = solution.length; return maxFitness; } protected void setSolution(String newSolution) { solution = new byte[newSolution.length()]; for (int i = 0; i < newSolution.length(); i++) { String character = newSolution.substring(i, i + 1); if (character.contains("0") || character.contains("1")) { solution[i] = Byte.parseByte(character); } else { solution[i] = 0; } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
package com.baeldung.algorithms.ga.binary; import lombok.Data; @Data public class Individual { protected int defaultGeneLength = 64; private byte[] genes = new byte[defaultGeneLength]; private int fitness = 0; public Individual() { for (int i = 0; i < genes.length; i++) { byte gene = (byte) Math.round(Math.random()); genes[i] = gene; } } protected byte getSingleGene(int index) { return genes[index]; } protected void setSingleGene(int index, byte value) { genes[index] = value; fitness = 0; } public int getFitness() { if (fitness == 0) { fitness = SimpleGeneticAlgorithm.getFitness(this); } return fitness; } @Override public String toString() { String geneString = ""; for (int i = 0; i < genes.length; i++) { geneString += getSingleGene(i); } return geneString; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
package com.baeldung.algorithms.ga.binary; import java.util.ArrayList; import java.util.List; import lombok.Data; @Data public class Population { private List<Individual> individuals; public Population(int size, boolean createNew) { individuals = new ArrayList<>(); if (createNew) { createNewPopulation(size); } } protected Individual getIndividual(int index) { return individuals.get(index); } protected Individual getFittest() { Individual fittest = individuals.get(0); for (int i = 0; i < individuals.size(); i++) { if (fittest.getFitness() <= getIndividual(i).getFitness()) { fittest = getIndividual(i); } } return fittest; } private void createNewPopulation(int size) { for (int i = 0; i < size; i++) { Individual newIndividual = new Individual(); individuals.add(i, newIndividual); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
package com.baeldung.algorithms.ga.annealing; import lombok.Data; @Data public class City { private int x; private int y; public City() { this.x = (int) (Math.random() * 500); this.y = (int) (Math.random() * 500); } public double distanceToCity(City city) { int x = Math.abs(getX() - city.getX()); int y = Math.abs(getY() - city.getY()); return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
package com.baeldung.algorithms.ga.annealing; import java.util.ArrayList; import java.util.Collections; import lombok.Data; @Data public class Travel { private ArrayList<City> travel = new ArrayList<>(); private ArrayList<City> previousTravel = new ArrayList<>(); public Travel(int numberOfCities) { for (int i = 0; i < numberOfCities; i++) { travel.add(new City()); } } public void generateInitialTravel() { if (travel.isEmpty()) { new Travel(10); } Collections.shuffle(travel); } public void swapCities() { int a = generateRandomIndex(); int b = generateRandomIndex(); previousTravel = new ArrayList<>(travel); City x = travel.get(a); City y = travel.get(b); travel.set(a, y); travel.set(b, x); } public void revertSwap() { travel = previousTravel; } private int generateRandomIndex() { return (int) (Math.random() * travel.size()); } public City getCity(int index) { return travel.get(index); } public int getDistance() { int distance = 0; for (int index = 0; index < travel.size(); index++) { City starting = getCity(index); City destination; if (index + 1 < travel.size()) { destination = getCity(index + 1); } else { destination = getCity(0); } distance += starting.distanceToCity(destination); } return distance; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
algorithms-modules/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
package com.baeldung.algorithms.ga.annealing; public class SimulatedAnnealing { private static Travel travel = new Travel(10); public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) { System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate); double t = startingTemperature; travel.generateInitialTravel(); double bestDistance = travel.getDistance(); System.out.println("Initial distance of travel: " + bestDistance); Travel bestSolution = travel; Travel currentSolution = bestSolution; for (int i = 0; i < numberOfIterations; i++) { if (t > 0.1) { currentSolution.swapCities(); double currentDistance = currentSolution.getDistance(); if (currentDistance < bestDistance) { bestDistance = currentDistance; } else if (Math.exp((bestDistance - currentDistance) / t) < Math.random()) { currentSolution.revertSwap(); } t *= coolingRate; } else { continue; } if (i % 100 == 0) { System.out.println("Iteration #" + i); } } return bestDistance; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageByCircularBufferUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageByCircularBufferUnitTest.java
package com.baeldung.algorithms.movingaverages; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MovingAverageByCircularBufferUnitTest { @Test public void whenInitialAverageIsCalculated_shouldReturnNAN() { MovingAverageByCircularBuffer ma = new MovingAverageByCircularBuffer(5); assertEquals(Double.NaN, ma.getMovingAverage(), 0.001); } @Test public void whenValuesAreAdded_shouldUpdateAverageCorrectly() { MovingAverageByCircularBuffer ma = new MovingAverageByCircularBuffer(3); ma.add(10); assertEquals(10.0, ma.getMovingAverage(), 0.001); ma.add(20); assertEquals(15.0, ma.getMovingAverage(), 0.001); ma.add(30); assertEquals(20.0, ma.getMovingAverage(), 0.001); } @Test public void whenWindowSizeIsFull_shouldOverrideTheOldestValue() { MovingAverageByCircularBuffer ma = new MovingAverageByCircularBuffer(2); ma.add(10); ma.add(20); assertEquals(15.0, ma.getMovingAverage(), 0.001); ma.add(30); assertEquals(25.0, ma.getMovingAverage(), 0.001); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageWithApacheCommonsMathUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageWithApacheCommonsMathUnitTest.java
package com.baeldung.algorithms.movingaverages; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MovingAverageWithApacheCommonsMathUnitTest { @Test public void whenInitialAverageIsCalculated_shouldReturnNAN() { MovingAverageWithApacheCommonsMath movingAverageCalculator = new MovingAverageWithApacheCommonsMath(5); assertEquals(Double.NaN, movingAverageCalculator.getMovingAverage(), 0.001); } @Test public void whenValuesAreAdded_shouldUpdateAverageCorrectly() { MovingAverageWithApacheCommonsMath movingAverageCalculator = new MovingAverageWithApacheCommonsMath(3); movingAverageCalculator.add(10); assertEquals(10.0, movingAverageCalculator.getMovingAverage(), 0.001); movingAverageCalculator.add(20); assertEquals(15.0, movingAverageCalculator.getMovingAverage(), 0.001); movingAverageCalculator.add(30); assertEquals(20.0, movingAverageCalculator.getMovingAverage(), 0.001); } @Test public void whenWindowSizeIsFull_shouldDropTheOldestValue() { MovingAverageWithApacheCommonsMath ma = new MovingAverageWithApacheCommonsMath(2); ma.add(10); ma.add(20); assertEquals(15.0, ma.getMovingAverage(), 0.001); ma.add(30); assertEquals(25.0, ma.getMovingAverage(), 0.001); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/ExponentialMovingAverageUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/ExponentialMovingAverageUnitTest.java
package com.baeldung.algorithms.movingaverages; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ExponentialMovingAverageUnitTest { @Test(expected = IllegalArgumentException.class) public void whenAlphaIsInvalid_shouldThrowException() { new ExponentialMovingAverage(0); } @Test public void whenFirstValueIsAdded_shouldHaveExponentialMovingAverageSameAsValue() { ExponentialMovingAverage ema = new ExponentialMovingAverage(0.5); assertEquals(10.0, ema.calculateEMA(10.0), 0.001); } @Test public void whenValuesAreAdded_shouldUpdateExponentialMovingAverageCorrectly() { ExponentialMovingAverage ema = new ExponentialMovingAverage(0.4); assertEquals(10.0, ema.calculateEMA(10.0), 0.001); assertEquals(14.0, ema.calculateEMA(20.0), 0.001); assertEquals(20.4, ema.calculateEMA(30.0), 0.001); } @Test public void whenAlphaIsCloserToOne_exponentialMovingAverageShouldRespondFasterToChanges() { ExponentialMovingAverage ema1 = new ExponentialMovingAverage(0.2); ExponentialMovingAverage ema2 = new ExponentialMovingAverage(0.8); assertEquals(10.0, ema1.calculateEMA(10.0), 0.001); assertEquals(10.0, ema2.calculateEMA(10.0), 0.001); assertEquals(12.0, ema1.calculateEMA(20.0), 0.001); assertEquals(18.0, ema2.calculateEMA(20.0), 0.001); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageWithStreamBasedApproachUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/movingaverages/MovingAverageWithStreamBasedApproachUnitTest.java
package com.baeldung.algorithms.movingaverages; import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class MovingAverageWithStreamBasedApproachUnitTest { @Test public void whenEmptyDataIsPassed_shouldReturnZero() { double[] data = {}; int windowSize = 3; double expectedAverage = 0; MovingAverageWithStreamBasedApproach calculator = new MovingAverageWithStreamBasedApproach(windowSize); double actualAverage = calculator.calculateAverage(data); assertEquals(expectedAverage, actualAverage); } @Test public void whenValidDataIsPassed_shouldReturnCorrectAverage() { double[] data = {10, 20, 30, 40, 50}; int windowSize = 3; double expectedAverage = 40; MovingAverageWithStreamBasedApproach calculator = new MovingAverageWithStreamBasedApproach(windowSize); double actualAverage = calculator.calculateAverage(data); assertEquals(expectedAverage, actualAverage); } @Test public void whenValidDataIsPassedWithLongerWindowSize_shouldReturnCorrectAverage() { double[] data = {10, 20, 30, 40, 50}; int windowSize = 5; double expectedAverage = 30; MovingAverageWithStreamBasedApproach calculator = new MovingAverageWithStreamBasedApproach(windowSize); double actualAverage = calculator.calculateAverage(data); assertEquals(expectedAverage, actualAverage); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/parentnodebinarytree/BinaryTreeParentNodeFinderUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/parentnodebinarytree/BinaryTreeParentNodeFinderUnitTest.java
package com.baeldung.algorithms.parentnodebinarytree; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertNull; class BinaryTreeParentNodeFinderUnitTest { private TreeNode subject; @BeforeEach void setUp() { subject = new TreeNode(8); subject.insert(5); subject.insert(12); subject.insert(3); subject.insert(7); subject.insert(1); subject.insert(4); subject.insert(11); subject.insert(14); subject.insert(13); subject.insert(16); } @Test void givenBinaryTree_whenFindParentNode_thenReturnCorrectParentNode() { assertEquals(8, subject.parent(5).value); assertEquals(5, subject.parent(3).value); assertEquals(5, subject.parent(7).value); assertEquals(3, subject.parent(4).value); assertEquals(3, subject.parent(1).value); assertEquals(8, subject.parent(12).value); assertEquals(12, subject.parent(14).value); assertEquals(12, subject.parent(11).value); assertEquals(14, subject.parent(16).value); assertEquals(14, subject.parent(13).value); assertThrows(NoSuchElementException.class, () -> subject.parent(1231)); assertThrows(NoSuchElementException.class, () -> subject.parent(8)); } @Test void givenBinaryTree_whenFindParentNodeIteratively_thenReturnCorrectParentNode() { assertEquals(8, subject.iterativeParent(5).value); assertEquals(5, subject.iterativeParent(3).value); assertEquals(5, subject.iterativeParent(7).value); assertEquals(3, subject.iterativeParent(4).value); assertEquals(3, subject.iterativeParent(1).value); assertEquals(8, subject.iterativeParent(12).value); assertEquals(12, subject.iterativeParent(14).value); assertEquals(12, subject.iterativeParent(11).value); assertEquals(14, subject.iterativeParent(16).value); assertEquals(14, subject.iterativeParent(13).value); assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(1231)); assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(8)); } @Test void givenParentKeeperBinaryTree_whenGetParent_thenReturnCorrectParent() { ParentKeeperTreeNode subject = new ParentKeeperTreeNode(8); subject.insert(5); subject.insert(12); subject.insert(3); subject.insert(7); subject.insert(1); subject.insert(4); subject.insert(11); subject.insert(14); subject.insert(13); subject.insert(16); assertNull(subject.parent); assertEquals(8, subject.left.parent.value); assertEquals(8, subject.right.parent.value); assertEquals(5, subject.left.left.parent.value); assertEquals(5, subject.left.right.parent.value); // tests for other nodes } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/happynumber/HappyNumberUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/happynumber/HappyNumberUnitTest.java
package com.baeldung.algorithms.happynumber; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Test; class HappyNumberDecider { public static boolean isHappyNumber(int n) { Set<Integer> checkedNumbers = new HashSet<>(); while (true) { n = sumDigitsSquare(n); if (n == 1) { return true; } if (checkedNumbers.contains(n)) { return false; } checkedNumbers.add(n); } } public static boolean isHappyNumberFloyd(int n) { int slow = n; int fast = n; do { slow = sumDigitsSquare(slow); fast = sumDigitsSquare(sumDigitsSquare(fast)); } while (slow != fast); return slow == 1; } private static int sumDigitsSquare(int n) { int squareSum = 0; while (n != 0) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum; } } public class HappyNumberUnitTest { @Test void whenUsingIsHappyNumber_thenGetTheExpectedResult() { assertTrue(HappyNumberDecider.isHappyNumber(7)); assertTrue(HappyNumberDecider.isHappyNumber(10)); assertTrue(HappyNumberDecider.isHappyNumber(13)); assertTrue(HappyNumberDecider.isHappyNumber(19)); assertTrue(HappyNumberDecider.isHappyNumber(23)); assertFalse(HappyNumberDecider.isHappyNumber(4)); assertFalse(HappyNumberDecider.isHappyNumber(6)); assertFalse(HappyNumberDecider.isHappyNumber(11)); assertFalse(HappyNumberDecider.isHappyNumber(15)); assertFalse(HappyNumberDecider.isHappyNumber(20)); } @Test void whenUsingIsHappyNumber2_thenGetTheExpectedResult() { assertTrue(HappyNumberDecider.isHappyNumberFloyd(7)); assertTrue(HappyNumberDecider.isHappyNumberFloyd(10)); assertTrue(HappyNumberDecider.isHappyNumberFloyd(13)); assertTrue(HappyNumberDecider.isHappyNumberFloyd(19)); assertTrue(HappyNumberDecider.isHappyNumberFloyd(23)); assertFalse(HappyNumberDecider.isHappyNumberFloyd(4)); assertFalse(HappyNumberDecider.isHappyNumberFloyd(6)); assertFalse(HappyNumberDecider.isHappyNumberFloyd(11)); assertFalse(HappyNumberDecider.isHappyNumberFloyd(15)); assertFalse(HappyNumberDecider.isHappyNumberFloyd(20)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/skiplist/SkipListUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/skiplist/SkipListUnitTest.java
package com.baeldung.algorithms.skiplist; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class SkipListUnitTest { @Test public void givenSkipList_WhenInsert_ThenSearchFound() { SkipList skipList = new SkipList(); skipList.insert(3); assertTrue(skipList.search(3), "Should find 3"); assertFalse(skipList.search(99), "Should not find 99"); } @Test public void givenSkipList_WhenDeleteElement_ThenRemoveFromList() { SkipList skipList = new SkipList(); skipList.insert(3); skipList.insert(7); skipList.delete(3); assertFalse(skipList.search(3), "3 should have been deleted"); skipList.delete(99); assertTrue(skipList.search(7), "7 should still exist"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/eastersunday/EasterDateCalculatorUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/eastersunday/EasterDateCalculatorUnitTest.java
package com.baeldung.algorithms.eastersunday; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import org.junit.jupiter.api.Test; public class EasterDateCalculatorUnitTest { @Test void givenEasterInMarch_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(2024)); } @Test void givenEasterInApril_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(2004)); } @Test void givenEdgeCases_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981)); assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954)); } @Test void givenEasterInMarch_whenComputeEasterDateWithButcherMeeusAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithButcherMeeusAlgorithm(2024)); } @Test void givenEasterInApril_whenComputeEasterDateWithButcherMeeusAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithButcherMeeusAlgorithm(2004)); // The following are added just to notice that there is no need for a special case with this algorithm assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981)); assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954)); } @Test void givenEasterInMarch_whenComputeEasterDateWithConwayAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithConwayAlgorithm(2024)); } @Test void givenEasterInApril_whenComputeEasterDateWithConwayAlgorithm_thenCorrectResult() { assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithConwayAlgorithm(2004)); // The following are added just to notice that there is no need for a special case with this algorithm assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981)); assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigitsUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigitsUnitTest.java
package com.baeldung.algorithms.largestNumberRemovingK; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class LargestNumberRemoveKDigitsUnitTest { @Test public void givenNumber_UsingArithmeticRemoveKDigits_thenReturnLargestNumber(){ Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(9461, 1), 961); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(463, 2), 6); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98625410, 6), 98); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(20, 2), 0); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98989, 4), 9); } @Test public void givenNumber_UsingStackRemoveKDigits_thenReturnLargestNumber(){ Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(9461, 1), 961); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(463, 2), 6); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98625410, 6), 98); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(20, 2), 0); Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98989, 4), 9); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/jugglersequence/JugglerSequenceUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/jugglersequence/JugglerSequenceUnitTest.java
package com.baeldung.algorithms.jugglersequence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; class JugglerSequenceGenerator { public static List<Integer> byLoop(int n) { if (n <= 0) { throw new IllegalArgumentException("The initial integer must be greater than zero."); } List<Integer> seq = new ArrayList<>(); int current = n; seq.add(current); while (current != 1) { int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current)); seq.add(next); current = next; } return seq; } public static List<Integer> byRecursion(int n) { if (n <= 0) { throw new IllegalArgumentException("The initial integer must be greater than zero."); } List<Integer> seq = new ArrayList<>(); fillSeqRecursively(n, seq); return seq; } private static void fillSeqRecursively(int current, List<Integer> result) { result.add(current); if (current == 1) { return; } int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current)); fillSeqRecursively(next, result); } } public class JugglerSequenceUnitTest { @Test void whenGeneratingJugglerSeqUsingLoop_thenGetTheExpectedResult() { assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byLoop(0)); assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(3)); assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byLoop(4)); assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(9)); assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(21)); assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byLoop(42)); } @Test void whenGeneratingJugglerSeqUsingRecursion_thenGetTheExpectedResult() { assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byRecursion(0)); assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(3)); assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byRecursion(4)); assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(9)); assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(21)); assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byRecursion(42)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/Piece.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/Piece.java
package com.baeldung.algorithms.connect4; public enum Piece { PLAYER_1, PLAYER_2 }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java
package com.baeldung.algorithms.connect4; import java.util.ArrayList; import java.util.List; public class GameBoard { private final List<List<Piece>> columns; private final int rows; public GameBoard(int columns, int rows) { this.rows = rows; this.columns = new ArrayList<>(); for (int i = 0; i < columns; ++i) { this.columns.add(new ArrayList<>()); } } public int getRows() { return rows; } public int getColumns() { return columns.size(); } public Piece getCell(int x, int y) { assert(x >= 0 && x < getColumns()); assert(y >= 0 && y < getRows()); List<Piece> column = columns.get(x); if (column.size() > y) { return column.get(y); } else { return null; } } public boolean move(int x, Piece player) { assert(x >= 0 && x < getColumns()); List<Piece> column = columns.get(x); if (column.size() >= this.rows) { throw new IllegalArgumentException("That column is full"); } column.add(player); return checkWin(x, column.size() - 1, player); } private boolean checkWin(int x, int y, Piece player) { // Vertical line if (checkLine(x, y, 0, -1, player)) { return true; } for (int offset = 0; offset < 4; ++offset) { // Horizontal line if (checkLine(x - 3 + offset, y, 1, 0, player)) { return true; } // Leading diagonal if (checkLine(x - 3 + offset, y + 3 - offset, 1, -1, player)) { return true; } // Trailing diagonal if (checkLine(x - 3 + offset, y - 3 + offset, 1, 1, player)) { return true; } } return false; } private boolean checkLine(int x1, int y1, int xDiff, int yDiff, Piece player) { for (int i = 0; i < 4; ++i) { int x = x1 + (xDiff * i); int y = y1 + (yDiff * i); if (x < 0 || x > columns.size() - 1) { return false; } if (y < 0 || y > rows - 1) { return false; } if (player != getCell(x, y)) { return false; } } return true; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (int y = getRows() - 1; y >= 0; --y) { for (int x = 0; x < getColumns(); ++x) { Piece piece = getCell(x, y); result.append("|"); if (piece == null) { result.append(" "); } else if (piece == Piece.PLAYER_1) { result.append("X"); } else if (piece == Piece.PLAYER_2) { result.append("O"); } } result.append("|\n"); for (int i = 0; i < getColumns(); ++i) { result.append("+-"); } result.append("+\n"); } return result.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java
package com.baeldung.algorithms.connect4; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class GameUnitTest { @Test public void blankGame() { GameBoard gameBoard = new GameBoard(8, 6); System.out.println(gameBoard); } @Test public void playedGame() { GameBoard gameBoard = new GameBoard(8, 6); assertFalse(gameBoard.move(3, Piece.PLAYER_1)); assertFalse(gameBoard.move(2, Piece.PLAYER_2)); assertFalse(gameBoard.move(4, Piece.PLAYER_1)); assertFalse(gameBoard.move(3, Piece.PLAYER_2)); assertFalse(gameBoard.move(5, Piece.PLAYER_1)); assertFalse(gameBoard.move(6, Piece.PLAYER_2)); assertFalse(gameBoard.move(5, Piece.PLAYER_1)); assertFalse(gameBoard.move(4, Piece.PLAYER_2)); assertFalse(gameBoard.move(5, Piece.PLAYER_1)); assertFalse(gameBoard.move(5, Piece.PLAYER_2)); assertFalse(gameBoard.move(6, Piece.PLAYER_1)); assertTrue(gameBoard.move(4, Piece.PLAYER_2)); System.out.println(gameBoard); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java
package com.baeldung.algorithms.mergeintervals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class MergeIntervalsUnitTest { private List<Interval> intervals = new ArrayList<>(Arrays.asList( // @formatter:off new Interval(3, 5), new Interval(13, 20), new Interval(11, 15), new Interval(15, 16), new Interval(1, 3), new Interval(4, 5), new Interval(16, 17) // @formatter:on )); private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList( // @formatter:off new Interval(1, 5), new Interval(11, 20) // @formatter:on )); @Test void givenIntervals_whenMerging_thenReturnMergedIntervals() { MergeOverlappingIntervals merger = new MergeOverlappingIntervals(); List<Interval> result = merger.doMerge(intervals); assertEquals(intervalsMerged, result); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java
package com.baeldung.algorithms.vigenere; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class VigenereCipherUnitTest { @Test void encodeBaeldung() { VigenereCipher cipher = new VigenereCipher(); String output = cipher.encode("BAELDUNG", "HELLO"); Assertions.assertEquals("JFQXSCSS", output); } @Test void encodeBaeldungMixedCharacters() { VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA"); String output = cipher.encode("BAELDUNG", "HELLO"); Assertions.assertEquals("DERDPTZV", output); } @Test void encodeArticleTitle() { VigenereCipher cipher = new VigenereCipher(); String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG"); Assertions.assertEquals("XJLQRZFL EJUTIM WU LBAM", output); } @Test void encodeArticleTitleMoreCharacters() { VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG"); Assertions.assertEquals("XJLQRZELBDNALZEGKOEVEPO", output); } @Test void decodeBaeldung() { VigenereCipher cipher = new VigenereCipher(); String output = cipher.decode("JFQXSCSS", "HELLO"); Assertions.assertEquals("BAELDUNG", output); } @Test void decodeBaeldungMixedCharacters() { VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA"); String output = cipher.decode("DERDPTZV", "HELLO"); Assertions.assertEquals("BAELDUNG", output); } @Test void decodeArticleTitleMoreCharacters() { VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); String output = cipher.decode("XJLQRZELBDNALZEGKOEVEPO", "BAELDUNG"); Assertions.assertEquals("VIGENERE CIPHER IN JAVA", output); } @Test void encodeDecodeBaeldung() { VigenereCipher cipher = new VigenereCipher(); String input = "BAELDUNG"; String key = "HELLO"; String encoded = cipher.encode(input, key); String decoded = cipher.decode(encoded, key); Assertions.assertEquals(input, decoded); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java
algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java
package com.baeldung.algorithms.vigenere; public class VigenereCipher { private final String characters; public VigenereCipher() { this("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public VigenereCipher(String characters) { this.characters = characters; } public String encode(String input, String key) { String result = ""; int keyPosition = 0; for (char c : input.toCharArray()) { char k = key.charAt(keyPosition % key.length()); int charIndex = characters.indexOf(c); int keyIndex = characters.indexOf(k); if (charIndex >= 0) { if (keyIndex >= 0) { int newCharIndex = (charIndex + keyIndex + 1) % characters.length(); c = characters.charAt(newCharIndex); } keyPosition++; } result += c; } return result; } public String decode(String input, String key) { String result = ""; int keyPosition = 0; for (char c : input.toCharArray()) { char k = key.charAt(keyPosition % key.length()); int charIndex = characters.indexOf(c); int keyIndex = characters.indexOf(k); if (charIndex >= 0) { if (keyIndex >= 0) { int newCharIndex = charIndex - keyIndex - 1; if (newCharIndex < 0) { newCharIndex = characters.length() + newCharIndex; } c = characters.charAt(newCharIndex); } keyPosition++; } result += c; } 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-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageWithApacheCommonsMath.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageWithApacheCommonsMath.java
package com.baeldung.algorithms.movingaverages; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class MovingAverageWithApacheCommonsMath { private final DescriptiveStatistics stats; public MovingAverageWithApacheCommonsMath(int windowSize) { this.stats = new DescriptiveStatistics(windowSize); } public void add(double value) { stats.addValue(value); } public double getMovingAverage() { return stats.getMean(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/ExponentialMovingAverage.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/ExponentialMovingAverage.java
package com.baeldung.algorithms.movingaverages; public class ExponentialMovingAverage { private final double alpha; private Double previousEMA; public ExponentialMovingAverage(double alpha) { if (alpha <= 0 || alpha > 1) { throw new IllegalArgumentException("Alpha must be in the range (0, 1]"); } this.alpha = alpha; this.previousEMA = null; } public double calculateEMA(double newValue) { if (previousEMA == null) { previousEMA = newValue; } else { previousEMA = alpha * newValue + (1 - alpha) * previousEMA; } return previousEMA; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageWithStreamBasedApproach.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageWithStreamBasedApproach.java
package com.baeldung.algorithms.movingaverages; import java.util.stream.DoubleStream; public class MovingAverageWithStreamBasedApproach { private int windowSize; public MovingAverageWithStreamBasedApproach(int windowSize) { this.windowSize = windowSize; } public double calculateAverage(double[] data) { return DoubleStream.of(data) .skip(Math.max(0, data.length - windowSize)) .limit(Math.min(data.length, windowSize)) .summaryStatistics() .getAverage(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageByCircularBuffer.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/movingaverages/MovingAverageByCircularBuffer.java
package com.baeldung.algorithms.movingaverages; public class MovingAverageByCircularBuffer { private final double[] buffer; private int head; private int count; public MovingAverageByCircularBuffer(int windowSize) { this.buffer = new double[windowSize]; } public void add(double value) { buffer[head] = value; head = (head + 1) % buffer.length; if (count < buffer.length) { count++; } } public double getMovingAverage() { if (count == 0) { return Double.NaN; } double sum = 0; for (int i = 0; i < count; i++) { sum += buffer[i]; } return sum / count; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/parentnodebinarytree/ParentKeeperTreeNode.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/parentnodebinarytree/ParentKeeperTreeNode.java
package com.baeldung.algorithms.parentnodebinarytree; import java.util.Objects; public class ParentKeeperTreeNode { int value; ParentKeeperTreeNode parent; ParentKeeperTreeNode left; ParentKeeperTreeNode right; public ParentKeeperTreeNode(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParentKeeperTreeNode treeNode = (ParentKeeperTreeNode) o; return value == treeNode.value; } @Override public int hashCode() { return Objects.hash(value); } public void insert(int value) { insert(this, value); } private void insert(ParentKeeperTreeNode currentNode, final int value) { if (currentNode.left == null && value < currentNode.value) { currentNode.left = new ParentKeeperTreeNode(value); currentNode.left.parent = currentNode; return; } if (currentNode.right == null && value > currentNode.value) { currentNode.right = new ParentKeeperTreeNode(value); currentNode.right.parent = currentNode; return; } if (value > currentNode.value) { insert(currentNode.right, value); } if (value < currentNode.value) { insert(currentNode.left, value); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/parentnodebinarytree/TreeNode.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/parentnodebinarytree/TreeNode.java
package com.baeldung.algorithms.parentnodebinarytree; import java.util.Deque; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Objects; import static java.lang.String.format; public class TreeNode { int value; TreeNode left; TreeNode right; public TreeNode(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TreeNode treeNode = (TreeNode) o; return value == treeNode.value; } @Override public int hashCode() { return Objects.hash(value); } public void insert(int value) { insert(this, value); } private void insert(TreeNode currentNode, final int value) { if (currentNode.left == null && value < currentNode.value) { currentNode.left = new TreeNode(value); return; } if (currentNode.right == null && value > currentNode.value) { currentNode.right = new TreeNode(value); return; } if (value > currentNode.value) { insert(currentNode.right, value); } if (value < currentNode.value) { insert(currentNode.left, value); } } public TreeNode parent(int target) throws NoSuchElementException { return parent(this, new TreeNode(target)); } private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException { if (target.equals(current) || current == null) { throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " + "The target is not in the tree or the target is the topmost root node.", target.value)); } if (target.equals(current.left) || target.equals(current.right)) { return current; } return parent(target.value < current.value ? current.left : current.right, target); } public TreeNode iterativeParent(int target) { return iterativeParent(this, new TreeNode(target)); } private TreeNode iterativeParent(TreeNode current, TreeNode target) { Deque<TreeNode> parentCandidates = new LinkedList<>(); String notFoundMessage = format("No parent node found for 'target.value=%s' " + "The target is not in the tree or the target is the topmost root node.", target.value); if (target.equals(current)) { throw new NoSuchElementException(notFoundMessage); } while (current != null || !parentCandidates.isEmpty()) { while (current != null) { parentCandidates.addFirst(current); current = current.left; } current = parentCandidates.pollFirst(); if (target.equals(current.left) || target.equals(current.right)) { return current; } current = current.right; } throw new NoSuchElementException(notFoundMessage); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/skiplist/Node.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/skiplist/Node.java
package com.baeldung.algorithms.skiplist; class Node { int value; Node[] forward; // array to hold references to different levels public Node(int value, int level) { this.value = value; this.forward = new Node[level + 1]; // level + 1 because level is 0-based } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/skiplist/SkipList.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/skiplist/SkipList.java
package com.baeldung.algorithms.skiplist; import java.util.Random; public class SkipList { private Node head; private int maxLevel; private int level; private Random random; public SkipList() { maxLevel = 16; // maximum number of levels level = 0; // current level of SkipList head = new Node(Integer.MIN_VALUE, maxLevel); random = new Random(); } public void insert(int value) { Node[] update = new Node[maxLevel + 1]; Node current = this.head; for (int i = level; i >= 0; i--) { while (current.forward[i] != null && current.forward[i].value < value) { current = current.forward[i]; } update[i] = current; } current = current.forward[0]; if (current == null || current.value != value) { int lvl = randomLevel(); if (lvl > level) { for (int i = level + 1; i <= lvl; i++) { update[i] = head; } level = lvl; } Node newNode = new Node(value, lvl); for (int i = 0; i <= lvl; i++) { newNode.forward[i] = update[i].forward[i]; update[i].forward[i] = newNode; } } } public boolean search(int value) { Node current = this.head; for (int i = level; i >= 0; i--) { while (current.forward[i] != null && current.forward[i].value < value) { current = current.forward[i]; } } current = current.forward[0]; return current != null && current.value == value; } public void delete(int value) { Node[] update = new Node[maxLevel + 1]; Node current = this.head; for (int i = level; i >= 0; i--) { while (current.forward[i] != null && current.forward[i].value < value) { current = current.forward[i]; } update[i] = current; } current = current.forward[0]; if (current != null && current.value == value) { for (int i = 0; i <= level; i++) { if (update[i].forward[i] != current) break; update[i].forward[i] = current.forward[i]; } while (level > 0 && head.forward[level] == null) { level--; } } } private int randomLevel() { int lvl = 0; while (lvl < maxLevel && random.nextDouble() < 0.5) { lvl++; } return lvl; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/eastersunday/EasterDateCalculator.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/eastersunday/EasterDateCalculator.java
package com.baeldung.algorithms.eastersunday; import java.time.LocalDate; public class EasterDateCalculator { LocalDate computeEasterDateWithGaussAlgorithm(int year) { int a = year % 19; int b = year % 4; int c = year % 7; int k = year / 100; int p = (13 + 8*k) / 25; int q = k / 4; int M = (15 - p + k - q) % 30; int N = (4 + k - q) % 7; int d = (19*a + M) % 30; int e = (2*b + 4*c + 6*d + N) % 7; if (d==29 && e == 6) { return LocalDate.of(year, 4, 19); } else if (d==28 && e==6 && ((11*M + 11)%30 < 10)) { return LocalDate.of(year, 4, 18); } int H = 22 + d + e; if (H <= 31) { return LocalDate.of(year, 3, H); } return LocalDate.of(year, 4, H-31); } LocalDate computeEasterDateWithButcherMeeusAlgorithm(int year) { int a = year % 19; int b = year / 100; int c = year % 100; int d = b / 4; int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; int h = (19*a + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; int l = (2*e + 2*i - h - k + 32) % 7; int m = (a + 11*h + 22*l) / 451; int t = h + l - 7*m + 114; int n = t / 31; int o = t % 31; return LocalDate.of(year, n, o+1); } LocalDate computeEasterDateWithConwayAlgorithm(int year) { int s = year / 100; int t = year % 100; int a = t / 4; int p = s % 4; int x = (9 - 2*p) % 7; int y = (x + t + a) % 7; int g = year % 19; int G = g + 1; int b = s / 4; int r = 8 * (s + 11) / 25; int C = -s + b + r; int d = (11*G + C) % 30; d = (d + 30) % 30; int h = (551 - 19*d + G) / 544; int e = (50 - d - h) % 7; int f = (e + y) % 7; int R = 57 - d - f - h; if (R <= 31) { return LocalDate.of(year, 3, R); } return LocalDate.of(year, 4, R-31); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigits.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigits.java
package com.baeldung.algorithms.largestNumberRemovingK; import java.util.Stack; public class LargestNumberRemoveKDigits { public static int findLargestNumberUsingArithmetic(int num, int k) { for (int j = 0; j < k; j++) { int result = 0; int i = 1; while (num / i > 0) { int temp = (num / (i * 10)) * i + (num % i); i *= 10; result = Math.max(result, temp); } num = result; } return num; } public static int findLargestNumberUsingStack(int num, int k) { String numStr = Integer.toString(num); int length = numStr.length(); if (k == length) return 0; Stack<Character> stack = new Stack<>(); for (int i = 0; i < length; i++) { char digit = numStr.charAt(i); while (k > 0 && !stack.isEmpty() && stack.peek() < digit) { stack.pop(); k--; } stack.push(digit); } while (k > 0) { stack.pop(); k--; } StringBuilder result = new StringBuilder(); while (!stack.isEmpty()) { result.insert(0, stack.pop()); } return Integer.parseInt(result.toString()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/Interval.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/Interval.java
package com.baeldung.algorithms.mergeintervals; import java.util.Objects; public class Interval { int start; int end; Interval(int start, int end) { this.start = start; this.end = end; } public void setEnd(int end) { this.end = end; } @Override public String toString() { return "Interval{" + "start=" + start + ", end=" + end + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Interval interval = (Interval) o; return start == interval.start && end == interval.end; } @Override public int hashCode() { return Objects.hash(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-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java
algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java
package com.baeldung.algorithms.mergeintervals; import static java.lang.Integer.max; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class MergeOverlappingIntervals { public List<Interval> doMerge(List<Interval> intervals) { intervals.sort(Comparator.comparingInt(interval -> interval.start)); ArrayList<Interval> merged = new ArrayList<>(); merged.add(intervals.get(0)); intervals.forEach(interval -> { Interval lastMerged = merged.get(merged.size() - 1); if (interval.start <= lastMerged.end){ lastMerged.setEnd(max(interval.end, lastMerged.end)); } else { merged.add(interval); } }); return merged; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-10/src/test/java/com/baeldung/algorithms/randomuniqueidentifier/UniqueIdGeneratorUnitTest.java
algorithms-modules/algorithms-miscellaneous-10/src/test/java/com/baeldung/algorithms/randomuniqueidentifier/UniqueIdGeneratorUnitTest.java
package com.baeldung.algorithms.randomuniqueidentifier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.*; class UniqueIdGeneratorUnitTest { private UniqueIdGenerator generator; private static final Pattern ALPHANUMERIC_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$"); @BeforeEach void setUp() { generator = new UniqueIdGenerator(); } @Test void givenDefaultSettings_whenGenerateUniqueIdIsCalled_thenReturnsValidAlphanumericString() { Set<String> existingIds = new HashSet<>(); String id = generator.generateUniqueId(existingIds); assertNotNull(id); assertEquals(8, id.length()); assertTrue(ALPHANUMERIC_PATTERN.matcher(id).matches()); } @Test void givenCustomLength_whenSetIdLengthIsCalled_thenGeneratorRespectsNewLength() { generator.setIdLength(5); Set<String> existingIds = new HashSet<>(); String id = generator.generateUniqueId(existingIds); assertEquals(5, id.length()); } @Test void givenExistingId_whenGenerateUniqueIdIsCalled_thenReturnsNonCollidingId() { // GIVEN: A set that already contains a specific ID Set<String> existingIds = new HashSet<>(); String existingId = "ABC12345"; existingIds.add(existingId); // WHEN: We generate a new ID String newId = generator.generateUniqueId(existingIds); // THEN: The new ID must not match the existing one assertNotEquals(existingId, newId); } @Test void givenLargeNumberRequests_whenGeneratedInBulk_thenAllIdsAreUnique() { Set<String> store = new HashSet<>(); int count = 100; for (int i = 0; i < count; i++) { store.add(generator.generateUniqueId(store)); } assertEquals(count, store.size(), "All 100 generated IDs should be unique"); } @Test void givenInvalidLength_whenSetIdLengthIsCalled_thenThrowsException() { assertThrows(IllegalArgumentException.class, () -> { generator.setIdLength(0); }); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-10/src/test/java/com/baeldung/algorithms/firstduplicate/FirstDuplicateUnitTest.java
algorithms-modules/algorithms-miscellaneous-10/src/test/java/com/baeldung/algorithms/firstduplicate/FirstDuplicateUnitTest.java
package com.baeldung.algorithms.firstduplicate; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class FirstDuplicateUnitTest { @Test public void givenArray_whenUsingBruteForce_thenFindFirstDuplicate() { FirstDuplicate firstDuplicate = new FirstDuplicate(); assertEquals(4, firstDuplicate.firstDuplicateBruteForce(new int[] { 2, 1, 3, 5, 3, 2 })); assertEquals(-1, firstDuplicate.firstDuplicateBruteForce(new int[] { 1, 2, 3, 4, 5 })); assertEquals(2, firstDuplicate.firstDuplicateBruteForce(new int[] { 2, 1, 1, 2 })); assertEquals(1, firstDuplicate.firstDuplicateBruteForce(new int[] { 1, 1 })); assertEquals(-1, firstDuplicate.firstDuplicateBruteForce(new int[] {})); } @Test public void givenArray_whenUsingHashSet_thenFindFirstDuplicate() { FirstDuplicate firstDuplicate = new FirstDuplicate(); assertEquals(4, firstDuplicate.firstDuplicateHashSet(new int[] { 2, 1, 3, 5, 3, 2 })); assertEquals(-1, firstDuplicate.firstDuplicateHashSet(new int[] { 1, 2, 3, 4, 5 })); assertEquals(2, firstDuplicate.firstDuplicateHashSet(new int[] { 2, 1, 1, 2 })); assertEquals(1, firstDuplicate.firstDuplicateHashSet(new int[] { 1, 1 })); assertEquals(-1, firstDuplicate.firstDuplicateHashSet(new int[] {})); } @Test public void givenArray_whenUsingArrayIndexing_thenFindFirstDuplicate() { FirstDuplicate firstDuplicate = new FirstDuplicate(); assertEquals(4, firstDuplicate.firstDuplicateArrayIndexing(new int[] { 2, 1, 3, 5, 3, 2 })); assertEquals(-1, firstDuplicate.firstDuplicateArrayIndexing(new int[] { 1, 2, 3, 4, 5 })); assertEquals(2, firstDuplicate.firstDuplicateArrayIndexing(new int[] { 2, 1, 1, 2 })); assertEquals(1, firstDuplicate.firstDuplicateArrayIndexing(new int[] { 1, 1 })); assertEquals(-1, firstDuplicate.firstDuplicateArrayIndexing(new int[] {})); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-10/src/main/java/com/baeldung/algorithms/randomuniqueidentifier/UniqueIdGenerator.java
algorithms-modules/algorithms-miscellaneous-10/src/main/java/com/baeldung/algorithms/randomuniqueidentifier/UniqueIdGenerator.java
package com.baeldung.algorithms.randomuniqueidentifier; import java.security.SecureRandom; import java.util.Set; import java.util.stream.Collectors; /** * Custom Random Identifier generator with unique ids . */ public class UniqueIdGenerator { private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static final SecureRandom random = new SecureRandom(); private int idLength = 8; // Default length /** * Overrides the default ID length for generated identifiers. * @param idLength The desired length (must be positive). */ public void setIdLength(int idLength) { if (idLength <= 0) { throw new IllegalArgumentException("Length must be positive"); } this.idLength = idLength; } /** * Generates a unique alphanumeric ID using the SecureRandom character mapping approach. * @param existingIds A set of IDs already in use to ensure uniqueness. * @return A unique alphanumeric string. */ public String generateUniqueId(Set<String> existingIds) { String newId; do { newId = generateRandomString(this.idLength); } while (existingIds.contains(newId)); return newId; } private String generateRandomString(int length) { return random.ints(length, 0, ALPHANUMERIC.length()) .mapToObj(ALPHANUMERIC::charAt) .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-10/src/main/java/com/baeldung/algorithms/firstduplicate/FirstDuplicate.java
algorithms-modules/algorithms-miscellaneous-10/src/main/java/com/baeldung/algorithms/firstduplicate/FirstDuplicate.java
package com.baeldung.algorithms.firstduplicate; import java.util.HashSet; public class FirstDuplicate { public int firstDuplicateBruteForce(int[] arr) { int minIndex = arr.length; for (int i = 0; i < arr.length - 1; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] == arr[j]) { minIndex = Math.min(minIndex, j); break; } } } return minIndex == arr.length ? -1 : minIndex; } public int firstDuplicateHashSet(int[] arr) { HashSet<Integer> firstDuplicateSet = new HashSet<>(); for (int i = 0; i < arr.length; i++) { if (firstDuplicateSet.contains(arr[i])) { return i; } firstDuplicateSet.add(arr[i]); } return -1; } public int firstDuplicateArrayIndexing(int[] arr) { for (int i = 0; i < arr.length; i++) { int val = Math.abs(arr[i]) - 1; if (arr[val] < 0) { return i; } arr[val] = -arr[val]; } return -1; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java
algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java
package com.baeldung.algorithms.gravitysort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class GravitySortUnitTest { @Test void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() { int[] actual = { 9, 9, 100, 3, 57, 12, 3, 78, 0, 2, 2, 40, 21, 9 }; int[] expected = { 0, 2, 2, 3, 3, 9, 9, 9, 12, 21, 40, 57, 78, 100 }; GravitySort.sort(actual); assertArrayEquals(expected, actual); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java
algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java
package com.baeldung.algorithms.bucketsort; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class IntegerBucketSorterUnitTest { private IntegerBucketSorter sorter; @BeforeEach public void setUp() throws Exception { sorter = new IntegerBucketSorter(); } @Test void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() { List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15); List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602); List<Integer> actual = sorter.sort(unsorted); 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-sorting-3/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java
algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java
package com.baeldung.algorithms.inoutsort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class InOutSortUnitTest { @Test void givenArray_whenInPlaceSort_thenReversed() { int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] expected = {7, 6, 5, 4, 3, 2, 1}; assertArrayEquals(expected, InOutSort.reverseInPlace(input), "the two arrays are not equal"); } @Test void givenArray_whenOutOfPlaceSort_thenReversed() { int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] expected = {7, 6, 5, 4, 3, 2, 1}; assertArrayEquals(expected, InOutSort.reverseOutOfPlace(input), "the two arrays are not equal"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java
algorithms-modules/algorithms-sorting-3/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java
package com.baeldung.algorithms.shellsort; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class ShellSortUnitTest { @Test void givenUnsortedArray_whenShellSort_thenSortedAsc() { int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8}; ShellSort.sort(input); int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82}; assertArrayEquals( expected, input, "the two arrays are not equal"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/gravitysort/GravitySort.java
algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/gravitysort/GravitySort.java
package com.baeldung.algorithms.gravitysort; public class GravitySort { public static int findMax(int[] A) { int max = A[0]; for (int i = 1; i< A.length; i++) { if (A[i] > max) { max = A[i]; } } return max; } public static boolean[][] setupAbacus(int[] A, int m) { boolean[][] abacus = new boolean[A.length][m]; for (int i = 0; i < abacus.length; i++) { int number = A[i]; for (int j = 0; j < abacus[0].length && j < number; j++) { abacus[A.length - 1 - i][j] = true; } } return abacus; } public static void dropBeads(boolean[][] abacus, int[] A, int m) { for (int i = 1; i < A.length; i++) { for (int j = m - 1; j >= 0; j--) { if (abacus[i][j] == true) { int x = i; while (x > 0 && abacus[x - 1][j] == false) { boolean temp = abacus[x - 1][j]; abacus[x - 1][j] = abacus[x][j]; abacus[x][j] = temp; x--; } } } } } public static void transformToList(boolean[][] abacus, int[] A) { int index = 0; for (int i = abacus.length - 1; i >= 0; i--) { int beads = 0; for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) { beads++; } A[index++] = beads; } } public static void sort(int[] A) { int m = findMax(A); boolean[][] abacus = setupAbacus(A, m); dropBeads(abacus, A, m); // transform abacus into sorted list transformToList(abacus, A); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorter.java
algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorter.java
package com.baeldung.algorithms.bucketsort; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class IntegerBucketSorter implements Sorter<Integer> { private final Comparator<Integer> comparator; public IntegerBucketSorter(Comparator<Integer> comparator) { this.comparator = comparator; } public IntegerBucketSorter() { comparator = Comparator.naturalOrder(); } public List<Integer> sort(List<Integer> arrayToSort) { List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort); for(List<Integer> bucket : buckets){ bucket.sort(comparator); } return concatenateSortedBuckets(buckets); } private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){ List<Integer> sortedArray = new LinkedList<>(); for(List<Integer> bucket : buckets){ sortedArray.addAll(bucket); } return sortedArray; } private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){ final int max = findMax(initialList); final int numberOfBuckets = (int) Math.sqrt(initialList.size()); List<List<Integer>> buckets = new ArrayList<>(); for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>()); //distribute the data for (int i : initialList) { buckets.get(hash(i, max, numberOfBuckets)).add(i); } return buckets; } private int findMax(List<Integer> input){ int m = Integer.MIN_VALUE; for (int i : input){ m = Math.max(i, m); } return m; } private static int hash(int i, int max, int numberOfBuckets) { return (int) ((double) i / max * (numberOfBuckets - 1)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/bucketsort/Sorter.java
algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/bucketsort/Sorter.java
package com.baeldung.algorithms.bucketsort; import java.util.List; public interface Sorter<T> { List<T> sort(List<T> arrayToSort); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java
algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java
package com.baeldung.algorithms.inoutsort; public class InOutSort { public static int[] reverseInPlace(int A[]) { int n = A.length; for (int i = 0; i < n / 2; i++) { int temp = A[i]; A[i] = A[n - 1 - i]; A[n - 1 - i] = temp; } return A; } public static int[] reverseOutOfPlace(int A[]) { int n = A.length; int[] B = new int[n]; for (int i = 0; i < n; i++) { B[n - i - 1] = A[i]; } return B; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java
algorithms-modules/algorithms-sorting-3/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java
package com.baeldung.algorithms.shellsort; public class ShellSort { public static void sort(int arrayToSort[]) { int n = arrayToSort.length; for (int gap = n / 2; gap > 0; gap /= 2) { for (int i = gap; i < n; i++) { int key = arrayToSort[i]; int j = i; while (j >= gap && arrayToSort[j - gap] > key) { arrayToSort[j] = arrayToSort[j - gap]; j -= gap; } arrayToSort[j] = key; } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false