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-9/src/main/java/com/baeldung/algorithms/permutation/StringPermutation.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/permutation/StringPermutation.java
package com.baeldung.algorithms.permutation; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class StringPermutation { public static boolean isPermutationWithSorting(String s1, String s2) { if (s1.length() != s2.length()) { return false; } char[] s1CharArray = s1.toCharArray(); char[] s2CharArray = s2.toCharArray(); Arrays.sort(s1CharArray); Arrays.sort(s2CharArray); return Arrays.equals(s1CharArray, s2CharArray); } public static boolean isPermutationWithOneCounter(String s1, String s2) { if (s1.length() != s2.length()) { return false; } int[] counter = new int[256]; for (int i = 0; i < s1.length(); i++) { counter[s1.charAt(i)]++; counter[s2.charAt(i)]--; } for (int count : counter) { if (count != 0) { return false; } } return true; } public static boolean isPermutationWithTwoCounters(String s1, String s2) { if (s1.length() != s2.length()) { return false; } int[] counter1 = new int[256]; int[] counter2 = new int[256]; for (int i = 0; i < s1.length(); i++) { counter1[s1.charAt(i)]++; } for (int i = 0; i < s2.length(); i++) { counter2[s2.charAt(i)]++; } return Arrays.equals(counter1, counter2); } public static boolean isPermutationWithMap(String s1, String s2) { if (s1.length() != s2.length()) { return false; } Map<Character, Integer> charsMap = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { charsMap.merge(s1.charAt(i), 1, Integer::sum); } for (int i = 0; i < s2.length(); i++) { if (!charsMap.containsKey(s2.charAt(i)) || charsMap.get(s2.charAt(i)) == 0) { return false; } charsMap.merge(s2.charAt(i), -1, Integer::sum); } return true; } public static boolean isPermutationInclusion(String s1, String s2) { int ns1 = s1.length(), ns2 = s2.length(); if (ns1 < ns2) { return false; } int[] s1Count = new int[26]; int[] s2Count = new int[26]; for (char ch : s2.toCharArray()) { s2Count[ch - 'a']++; } for (int i = 0; i < ns1; ++i) { s1Count[s1.charAt(i) - 'a']++; if (i >= ns2) { s1Count[s1.charAt(i - ns2) - 'a']--; } if (Arrays.equals(s2Count, s1Count)) { return true; } } return false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/Node.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/Node.java
package com.baeldung.algorithms.minimax; import java.util.ArrayList; import java.util.List; public class Node { private int noOfBones; private boolean isMaxPlayer; private int score; private List<Node> children; public Node(int noOfBones, boolean isMaxPlayer) { this.noOfBones = noOfBones; this.isMaxPlayer = isMaxPlayer; children = new ArrayList<>(); } int getNoOfBones() { return noOfBones; } boolean isMaxPlayer() { return isMaxPlayer; } int getScore() { return score; } void setScore(int score) { this.score = score; } List<Node> getChildren() { return children; } void addChild(Node newNode) { children.add(newNode); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/Tree.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/Tree.java
package com.baeldung.algorithms.minimax; public class Tree { private Node root; Tree() { } Node getRoot() { return root; } void setRoot(Node root) { this.root = root; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
package com.baeldung.algorithms.minimax; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class GameOfBones { static List<Integer> getPossibleStates(int noOfBonesInHeap) { return IntStream.rangeClosed(1, 3).boxed() .map(i -> noOfBonesInHeap - i) .filter(newHeapCount -> newHeapCount >= 0) .collect(Collectors.toList()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
package com.baeldung.algorithms.minimax; import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; public class MiniMax { private Tree tree; public Tree getTree() { return tree; } public void constructTree(int noOfBones) { tree = new Tree(); Node root = new Node(noOfBones, true); tree.setRoot(root); constructTree(root); } private void constructTree(Node parentNode) { List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones()); boolean isChildMaxPlayer = !parentNode.isMaxPlayer(); listofPossibleHeaps.forEach(n -> { Node newNode = new Node(n, isChildMaxPlayer); parentNode.addChild(newNode); if (newNode.getNoOfBones() > 0) { constructTree(newNode); } }); } public boolean checkWin() { Node root = tree.getRoot(); checkWin(root); return root.getScore() == 1; } private void checkWin(Node node) { List<Node> children = node.getChildren(); boolean isMaxPlayer = node.isMaxPlayer(); children.forEach(child -> { if (child.getNoOfBones() == 0) { child.setScore(isMaxPlayer ? 1 : -1); } else { checkWin(child); } }); Node bestChild = findBestChild(isMaxPlayer, children); node.setScore(bestChild.getScore()); } private Node findBestChild(boolean isMaxPlayer, List<Node> children) { Comparator<Node> byScoreComparator = Comparator.comparing(Node::getScore); return children.stream() .max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed()) .orElseThrow(NoSuchElementException::new); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java
package com.baeldung.algorithms.kthlargest; import java.util.Arrays; import java.util.Collections; import java.util.stream.IntStream; public class FindKthLargest { public int findKthLargestBySorting(Integer[] arr, int k) { Arrays.sort(arr); int targetIndex = arr.length - k; return arr[targetIndex]; } public int findSecondLargestWithoutSorting(Integer[] arr) throws Exception{ Integer[] result = new Integer[2]; if (arr == null || arr.length < 2) { throw new Exception( "Array should have at least two elements and be not null"); } else { if (arr[0] > arr[1]) { result[0] = arr[0]; result[1] = arr[1]; } else { result[0] = arr[1]; result[1] = arr[0]; } if (arr.length > 2) { for (int i = 2; i < arr.length; i++) { if (arr[i] > result[0]) { result[1] = result[0]; result[0] = arr[i]; } else if (arr[i] > result[1]) { result[1] = arr[i]; } } } } return result[1]; } public int findKthLargestBySortingDesc(Integer[] arr, int k) { Arrays.sort(arr, Collections.reverseOrder()); return arr[k - 1]; } public int findKthElementByQuickSelect(Integer[] arr, int left, int right, int k) { if (k >= 0 && k <= right - left + 1) { int pos = partition(arr, left, right); if (pos - left == k) { return arr[pos]; } if (pos - left > k) { return findKthElementByQuickSelect(arr, left, pos - 1, k); } return findKthElementByQuickSelect(arr, pos + 1, right, k - pos + left - 1); } return 0; } public int findKthElementByQuickSelectWithIterativePartition(Integer[] arr, int left, int right, int k) { if (k >= 0 && k <= right - left + 1) { int pos = partitionIterative(arr, left, right); if (pos - left == k) { return arr[pos]; } if (pos - left > k) { return findKthElementByQuickSelectWithIterativePartition(arr, left, pos - 1, k); } return findKthElementByQuickSelectWithIterativePartition(arr, pos + 1, right, k - pos + left - 1); } return 0; } private int partition(Integer[] arr, int left, int right) { int pivot = arr[right]; Integer[] leftArr; Integer[] rightArr; leftArr = IntStream.range(left, right) .filter(i -> arr[i] < pivot) .map(i -> arr[i]) .boxed() .toArray(Integer[]::new); rightArr = IntStream.range(left, right) .filter(i -> arr[i] > pivot) .map(i -> arr[i]) .boxed() .toArray(Integer[]::new); int leftArraySize = leftArr.length; System.arraycopy(leftArr, 0, arr, left, leftArraySize); arr[leftArraySize + left] = pivot; System.arraycopy(rightArr, 0, arr, left + leftArraySize + 1, rightArr.length); return left + leftArraySize; } private int partitionIterative(Integer[] arr, int left, int right) { int pivot = arr[right], i = left; for (int j = left; j <= right - 1; j++) { if (arr[j] <= pivot) { swap(arr, i, j); i++; } } swap(arr, i, right); return i; } public int findKthElementByRandomizedQuickSelect(Integer[] arr, int left, int right, int k) { if (k >= 0 && k <= right - left + 1) { int pos = randomPartition(arr, left, right); if (pos - left == k) { return arr[pos]; } if (pos - left > k) { return findKthElementByRandomizedQuickSelect(arr, left, pos - 1, k); } return findKthElementByRandomizedQuickSelect(arr, pos + 1, right, k - pos + left - 1); } return 0; } private int randomPartition(Integer arr[], int left, int right) { int n = right - left + 1; int pivot = (int) (Math.random() * n); swap(arr, left + pivot, right); return partition(arr, left, right); } private void swap(Integer[] arr, int n1, int n2) { int temp = arr[n2]; arr[n2] = arr[n1]; arr[n1] = temp; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/successivepairs/SuccessivePairs.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/successivepairs/SuccessivePairs.java
package com.baeldung.algorithms.successivepairs; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class SuccessivePairs { public static <T> List<SimpleEntry<T, T>> collectSuccessivePairs(Stream<T> stream) { List<T> list = stream.collect(Collectors.toList()); return IntStream.range(0, list.size() - 1) .mapToObj(i -> new SimpleEntry<>(list.get(i), list.get(i + 1))) .collect(Collectors.toList()); } public static <T> Stream<List<T>> pairwise(Stream<T> stream) { List<T> list = stream.collect(Collectors.toList()); List<List<T>> pairs = new ArrayList<>(); for (int i = 0; i < list.size() - 1; i++) { pairs.add(Arrays.asList(list.get(i), list.get(i + 1))); } return pairs.stream(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/countoccurence/CountOccurrence.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/countoccurence/CountOccurrence.java
package com.baeldung.algorithms.countoccurence; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class CountOccurrence { public static int[] countOccurrencesWithCounter(int[] elements, int n) { int[] counter = new int[n]; for (int element : elements) { counter[element]++; } return counter; } public static <T> Map<T, Integer> countOccurrencesWithMap(T[] elements) { Map<T, Integer> counter = new HashMap<>(); for (T element : elements) { counter.merge(element, 1, Integer::sum); } return counter; } public static <T> Map<T, Long> countOccurrencesWithStream(T[] elements) { return Arrays.stream(elements) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/subarray/SubarrayMeansBruteForce.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/subarray/SubarrayMeansBruteForce.java
package com.baeldung.algorithms.subarray; public class SubarrayMeansBruteForce { public static int countSubarraysWithMean(int[] inputArray, int mean) { int count = 0; for (int i = 0; i < inputArray.length; i++) { long sum = 0; for (int j = i; j < inputArray.length; j++) { sum += inputArray[j]; if (sum * 1.0 / (j - i + 1) == mean) { count++; } } } return count; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/subarray/SubarrayMeansPrefixSums.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/subarray/SubarrayMeansPrefixSums.java
package com.baeldung.algorithms.subarray; import java.util.HashMap; import java.util.Map; public class SubarrayMeansPrefixSums { public static int countSubarraysWithMean(int[] inputArray, int mean) { int n = inputArray.length; long[] prefixSums = new long[n + 1]; long[] adjustedPrefixes = new long[n + 1]; for (int i = 0; i < n; i++) { prefixSums[i + 1] = prefixSums[i] + inputArray[i]; adjustedPrefixes[i + 1] = prefixSums[i + 1] - (long) mean * (i + 1); } Map<Long, Integer> count = new HashMap<>(); int total = 0; for (long adjustedPrefix : adjustedPrefixes) { total += count.getOrDefault(adjustedPrefix, 0); count.put(adjustedPrefix, count.getOrDefault(adjustedPrefix, 0) + 1); } return total; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java
package com.baeldung.algorithms.editdistance; public class EditDistanceDynamicProgramming extends EditDistanceBase { static int calculate(String x, String y) { int[][] dp = new int[x.length() + 1][y.length() + 1]; for (int i = 0; i <= x.length(); i++) { for (int j = 0; j <= y.length(); j++) { if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else { dp[i][j] = min(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1, dp[i][j - 1] + 1); } } } return dp[x.length()][y.length()]; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java
package com.baeldung.algorithms.editdistance; import java.util.Arrays; public class EditDistanceBase { static int costOfSubstitution(char a, char b) { return a == b ? 0 : 1; } static int min(int... numbers) { return Arrays.stream(numbers) .min().orElse(Integer.MAX_VALUE); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java
algorithms-modules/algorithms-miscellaneous-9/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java
package com.baeldung.algorithms.editdistance; public class EditDistanceRecursive extends EditDistanceBase { static int calculate(String x, String y) { if (x.isEmpty()) { return y.length(); } if (y.isEmpty()) { return x.length(); } int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0)); int insertion = calculate(x, y.substring(1)) + 1; int deletion = calculate(x.substring(1), y) + 1; return min(substitution, insertion, deletion); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/dijkstra/DijkstraAlgorithmLongRunningUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/dijkstra/DijkstraAlgorithmLongRunningUnitTest.java
package com.baeldung.algorithms.dijkstra; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.dijkstra.Dijkstra; import com.baeldung.algorithms.dijkstra.Graph; import com.baeldung.algorithms.dijkstra.Node; class DijkstraAlgorithmLongRunningUnitTest { @Test public void whenSPPSolved_thenCorrect() { Node nodeA = new Node("A"); Node nodeB = new Node("B"); Node nodeC = new Node("C"); Node nodeD = new Node("D"); Node nodeE = new Node("E"); Node nodeF = new Node("F"); nodeA.addDestination(nodeB, 10); nodeA.addDestination(nodeC, 15); nodeB.addDestination(nodeD, 12); nodeB.addDestination(nodeF, 15); nodeC.addDestination(nodeE, 10); nodeD.addDestination(nodeE, 2); nodeD.addDestination(nodeF, 1); nodeF.addDestination(nodeE, 5); Graph graph = new Graph(); graph.addNode(nodeA); graph.addNode(nodeB); graph.addNode(nodeC); graph.addNode(nodeD); graph.addNode(nodeE); graph.addNode(nodeF); graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); List<Node> shortestPathForNodeB = Arrays.asList(nodeA); List<Node> shortestPathForNodeC = Arrays.asList(nodeA); List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB); List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); for (Node node : graph.getNodes()) { switch (node.getName()) { case "B": assertTrue(node .getShortestPath() .equals(shortestPathForNodeB)); break; case "C": assertTrue(node .getShortestPath() .equals(shortestPathForNodeC)); break; case "D": assertTrue(node .getShortestPath() .equals(shortestPathForNodeD)); break; case "E": assertTrue(node .getShortestPath() .equals(shortestPathForNodeE)); break; case "F": assertTrue(node .getShortestPath() .equals(shortestPathForNodeF)); break; } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
package com.baeldung.algorithms.enumstatemachine; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class LeaveRequestStateUnitTest { @Test void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() { LeaveRequestState state = LeaveRequestState.Escalated; assertEquals( "Team Leader", state.responsiblePerson()); } @Test void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() { LeaveRequestState state = LeaveRequestState.Approved; assertEquals( "Department Manager" , state.responsiblePerson()); } @Test void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() { LeaveRequestState state = LeaveRequestState.Submitted; state = state.nextState(); assertEquals(LeaveRequestState.Escalated, state); state = state.nextState(); assertEquals(LeaveRequestState.Approved, state); state = state.nextState(); assertEquals(LeaveRequestState.Approved, state); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java
package com.baeldung.algorithms.conversion; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.commons.codec.DecoderException; import org.hamcrest.text.IsEqualIgnoringCase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ByteArrayConverterUnitTest { private HexStringConverter hexStringConverter; @BeforeEach public void setup() { hexStringConverter = new HexStringConverter(); } @Test void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); if (hexString.charAt(0) == '0') { hexString = hexString.substring(1); } String output = hexStringConverter.encodeUsingBigIntegerToString(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingBigInteger() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingBigInteger(hexString); assertArrayEquals(bytes, output); } @Test void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeHexString(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeHexString(hexString); assertArrayEquals(bytes, output); } @Test void shouldDecodeHexToByteWithInvalidHexCharacter() { assertThrows(IllegalArgumentException.class, () -> { hexStringConverter.hexToByte("fg"); }); } @Test void shouldEncodeByteArrayToHexStringDataTypeConverter() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingDataTypeConverter(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString); assertArrayEquals(bytes, output); } @Test void shouldEncodeByteArrayToHexStringUsingGuava() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingGuava(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingGuava() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingGuava(hexString); assertArrayEquals(bytes, output); } @Test void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingApacheCommons(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString); assertArrayEquals(bytes, output); } @Test void shouldEncodeByteArrayToHexStringUsingHexFormat() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingHexFormat(bytes); assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); } @Test void shouldDecodeHexStringToByteArrayUsingHexFormat() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingHexFormat(hexString); assertArrayEquals(bytes, output); } private String getSampleHexString() { return "0af50c0e2d10"; } private byte[] getSampleBytes() { return new byte[]{10, -11, 12, 14, 45, 16}; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/maximumsubarray/BruteForceAlgorithmUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/maximumsubarray/BruteForceAlgorithmUnitTest.java
package com.baeldung.algorithms.maximumsubarray; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class BruteForceAlgorithmUnitTest { @Test void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() { //given int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5}; //when BruteForceAlgorithm algorithm = new BruteForceAlgorithm(); int maximumSum = algorithm.maxSubArray(arr); //then assertEquals(6, maximumSum); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithmUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithmUnitTest.java
package com.baeldung.algorithms.maximumsubarray; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class KadaneAlgorithmUnitTest { @Test void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturnsExpectedResult() { //given int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 }; //when KadaneAlgorithm algorithm = new KadaneAlgorithm(); int maxSum = algorithm.maxSubArraySum(arr); //then assertEquals(6, maxSum); } @Test void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() { //given int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 }; //when KadaneAlgorithm algorithm = new KadaneAlgorithm(); int maxSum = algorithm.maxSubArraySum(arr); //then assertEquals(-1, maxSum); } @Test void givenArrayWithAllPosiitveNumbersWhenMaximumSubarrayThenReturnsExpectedResult() { //given int[] arr = new int[] {4, 1, 3, 2}; //when KadaneAlgorithm algorithm = new KadaneAlgorithm(); int maxSum = algorithm.maxSubArraySum(arr); //then assertEquals(10, maxSum); } @Test void givenArrayToTestStartIndexWhenMaximumSubarrayThenReturnsExpectedResult() { //given int[] arr = new int[] { 1, 2, -1, 3, -6, -2 }; //when KadaneAlgorithm algorithm = new KadaneAlgorithm(); int maxSum = algorithm.maxSubArraySum(arr); //then assertEquals(5, maxSum); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/latlondistance/GeoDistanceUnitTest.java
algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/latlondistance/GeoDistanceUnitTest.java
package com.baeldung.algorithms.latlondistance; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class GeoDistanceUnitTest { @Test public void testCalculateDistance() { double lat1 = 40.714268; // New York double lon1 = -74.005974; double lat2 = 34.0522; // Los Angeles double lon2 = -118.2437; double equirectangularDistance = EquirectangularApproximation.calculateDistance(lat1, lon1, lat2, lon2); double haversineDistance = HaversineDistance.calculateDistance(lat1, lon1, lat2, lon2); double vincentyDistance = VincentyDistance.calculateDistance(lat1, lon1, lat2, lon2); double expectedDistance = 3944; assertTrue(Math.abs(equirectangularDistance - expectedDistance) < 100); assertTrue(Math.abs(haversineDistance - expectedDistance) < 10); assertTrue(Math.abs(vincentyDistance - expectedDistance) < 0.5); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java
package com.baeldung.algorithms.permutation; import java.util.Arrays; import java.util.Collections; public class Permutation { public static <T> void printAllRecursive(T[] elements, char delimiter) { printAllRecursive(elements.length, elements, delimiter); } public static <T> void printAllRecursive(int n, T[] elements, char delimiter) { if(n == 1) { printArray(elements, delimiter); } else { for(int i = 0; i < n-1; i++) { printAllRecursive(n - 1, elements, delimiter); if(n % 2 == 0) { swap(elements, i, n-1); } else { swap(elements, 0, n-1); } } printAllRecursive(n - 1, elements, delimiter); } } public static <T> void printAllIterative(int n, T[] elements, char delimiter) { int[] indexes = new int[n]; for (int i = 0; i < n; i++) { indexes[i] = 0; } printArray(elements, delimiter); int i = 0; while (i < n) { if (indexes[i] < i) { swap(elements, i % 2 == 0 ? 0: indexes[i], i); printArray(elements, delimiter); indexes[i]++; i = 0; } else { indexes[i] = 0; i++; } } } public static <T extends Comparable<T>> void printAllOrdered(T[] elements, char delimiter) { Arrays.sort(elements); boolean hasNext = true; while(hasNext) { printArray(elements, delimiter); int k = 0, l = 0; hasNext = false; for (int i = elements.length - 1; i > 0; i--) { if (elements[i].compareTo(elements[i - 1]) > 0) { k = i - 1; hasNext = true; break; } } for (int i = elements.length - 1; i > k; i--) { if (elements[i].compareTo(elements[k]) > 0) { l = i; break; } } swap(elements, k, l); Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length)); } } public static <T> void printRandom(T[] elements, char delimiter) { Collections.shuffle(Arrays.asList(elements)); printArray(elements, delimiter); } private static <T> void swap(T[] elements, int a, int b) { T tmp = elements[a]; elements[a] = elements[b]; elements[b] = tmp; } private static <T> void printArray(T[] elements, char delimiter) { String delimiterSpace = delimiter + " "; for(int i = 0; i < elements.length; i++) { System.out.print(elements[i] + delimiterSpace); } System.out.print('\n'); } public static void main(String[] argv) { Integer[] elements = {1,2,3,4}; System.out.println("Rec:"); printAllRecursive(elements, ';'); System.out.println("Iter:"); printAllIterative(elements.length, elements, ';'); System.out.println("Orderes:"); printAllOrdered(elements, ';'); System.out.println("Random:"); printRandom(elements, ';'); System.out.println("Random:"); printRandom(elements, ';'); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
package com.baeldung.algorithms.dijkstra; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Node { private String name; private LinkedList<Node> shortestPath = new LinkedList<>(); private Integer distance = Integer.MAX_VALUE; private Map<Node, Integer> adjacentNodes = new HashMap<>(); public Node(String name) { this.name = name; } public void addDestination(Node destination, int distance) { adjacentNodes.put(destination, distance); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<Node, Integer> getAdjacentNodes() { return adjacentNodes; } public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) { this.adjacentNodes = adjacentNodes; } public Integer getDistance() { return distance; } public void setDistance(Integer distance) { this.distance = distance; } public List<Node> getShortestPath() { return shortestPath; } public void setShortestPath(LinkedList<Node> shortestPath) { this.shortestPath = shortestPath; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
package com.baeldung.algorithms.dijkstra; import java.util.HashSet; import java.util.Set; public class Graph { private Set<Node> nodes = new HashSet<>(); public void addNode(Node nodeA) { nodes.add(nodeA); } public Set<Node> getNodes() { return nodes; } public void setNodes(Set<Node> nodes) { this.nodes = nodes; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
package com.baeldung.algorithms.dijkstra; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Set; public class Dijkstra { public static Graph calculateShortestPathFromSource(Graph graph, Node source) { source.setDistance(0); Set<Node> settledNodes = new HashSet<>(); Set<Node> unsettledNodes = new HashSet<>(); unsettledNodes.add(source); while (unsettledNodes.size() != 0) { Node currentNode = getLowestDistanceNode(unsettledNodes); unsettledNodes.remove(currentNode); for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) { Node adjacentNode = adjacencyPair.getKey(); Integer edgeWeigh = adjacencyPair.getValue(); if (!settledNodes.contains(adjacentNode)) { CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode); unsettledNodes.add(adjacentNode); } } settledNodes.add(currentNode); } return graph; } private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) { Integer sourceDistance = sourceNode.getDistance(); if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) { evaluationNode.setDistance(sourceDistance + edgeWeigh); LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath()); shortestPath.add(sourceNode); evaluationNode.setShortestPath(shortestPath); } } private static Node getLowestDistanceNode(Set<Node> unsettledNodes) { Node lowestDistanceNode = null; int lowestDistance = Integer.MAX_VALUE; for (Node node : unsettledNodes) { int nodeDistance = node.getDistance(); if (nodeDistance < lowestDistance) { lowestDistance = nodeDistance; lowestDistanceNode = node; } } return lowestDistanceNode; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
package com.baeldung.algorithms.enumstatemachine; public enum LeaveRequestState { Submitted { @Override public LeaveRequestState nextState() { System.out.println("Starting the Leave Request and sending to Team Leader for approval."); return Escalated; } @Override public String responsiblePerson() { return "Employee"; } }, Escalated { @Override public LeaveRequestState nextState() { System.out.println("Reviewing the Leave Request and escalating to Department Manager."); return Approved; } @Override public String responsiblePerson() { return "Team Leader"; } }, Approved { @Override public LeaveRequestState nextState() { System.out.println("Approving the Leave Request."); return this; } @Override public String responsiblePerson() { return "Department Manager"; } }; public abstract String responsiblePerson(); public abstract LeaveRequestState nextState(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java
package com.baeldung.algorithms.conversion; import java.math.BigInteger; import java.util.HexFormat; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import com.google.common.io.BaseEncoding; import jakarta.xml.bind.DatatypeConverter; public class HexStringConverter { /** * Create a byte Array from String of hexadecimal digits using Character conversion * @param hexString - Hexadecimal digits as String * @return Desired byte Array */ public byte[] decodeHexString(String hexString) { if (hexString.length() % 2 == 1) { throw new IllegalArgumentException("Invalid hexadecimal String supplied."); } byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < hexString.length(); i += 2) { bytes[i / 2] = hexToByte(hexString.substring(i, i + 2)); } return bytes; } /** * Create a String of hexadecimal digits from a byte Array using Character conversion * @param byteArray - The byte Array * @return Desired String of hexadecimal digits in lower case */ public String encodeHexString(byte[] byteArray) { StringBuffer hexStringBuffer = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { hexStringBuffer.append(byteToHex(byteArray[i])); } return hexStringBuffer.toString(); } public String byteToHex(byte num) { char[] hexDigits = new char[2]; hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); hexDigits[1] = Character.forDigit((num & 0xF), 16); return new String(hexDigits); } public byte hexToByte(String hexString) { int firstDigit = toDigit(hexString.charAt(0)); int secondDigit = toDigit(hexString.charAt(1)); return (byte) ((firstDigit << 4) + secondDigit); } private int toDigit(char hexChar) { int digit = Character.digit(hexChar, 16); if(digit == -1) { throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar); } return digit; } public String encodeUsingBigIntegerToString(byte[] bytes) { BigInteger bigInteger = new BigInteger(1, bytes); return bigInteger.toString(16); } public String encodeUsingBigIntegerStringFormat(byte[] bytes) { BigInteger bigInteger = new BigInteger(1, bytes); return String.format("%0" + (bytes.length << 1) + "x", bigInteger); } public byte[] decodeUsingBigInteger(String hexString) { byte[] byteArray = new BigInteger(hexString, 16).toByteArray(); if (byteArray[0] == 0) { byte[] output = new byte[byteArray.length - 1]; System.arraycopy(byteArray, 1, output, 0, output.length); return output; } return byteArray; } public String encodeUsingDataTypeConverter(byte[] bytes) { return DatatypeConverter.printHexBinary(bytes); } public byte[] decodeUsingDataTypeConverter(String hexString) { return DatatypeConverter.parseHexBinary(hexString); } public String encodeUsingApacheCommons(byte[] bytes) { return Hex.encodeHexString(bytes); } public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException { return Hex.decodeHex(hexString); } public String encodeUsingGuava(byte[] bytes) { return BaseEncoding.base16() .encode(bytes); } public byte[] decodeUsingGuava(String hexString) { return BaseEncoding.base16() .decode(hexString.toUpperCase()); } public String encodeUsingHexFormat(byte[] bytes) { HexFormat hexFormat = HexFormat.of(); return hexFormat.formatHex(bytes); } public byte[] decodeUsingHexFormat(String hexString) { HexFormat hexFormat = HexFormat.of(); return hexFormat.parseHex(hexString); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/maximumsubarray/BruteForceAlgorithm.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/maximumsubarray/BruteForceAlgorithm.java
package com.baeldung.algorithms.maximumsubarray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BruteForceAlgorithm { private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName()); public int maxSubArray(int[] arr) { int size = arr.length; int maximumSubArraySum = Integer.MIN_VALUE; int start = 0; int end = 0; for (int left = 0; left < size; left++) { int runningWindowSum = 0; for (int right = left; right < size; right++) { runningWindowSum += arr[right]; if (runningWindowSum > maximumSubArraySum) { maximumSubArraySum = runningWindowSum; start = left; end = right; } } } logger.info("Found Maximum Subarray between {} and {}", start, end); return maximumSubArraySum; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithm.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithm.java
package com.baeldung.algorithms.maximumsubarray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KadaneAlgorithm { private Logger logger = LoggerFactory.getLogger(KadaneAlgorithm.class.getName()); public int maxSubArraySum(int[] arr) { int size = arr.length; int start = 0; int end = 0; int maxSoFar = arr[0], maxEndingHere = arr[0]; for (int i = 1; i < size; i++) { maxEndingHere = maxEndingHere + arr[i]; if (arr[i] > maxEndingHere) { maxEndingHere = arr[i]; if (maxSoFar < maxEndingHere) { start = i; } } if (maxSoFar < maxEndingHere) { maxSoFar = maxEndingHere; end = i; } } logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end); return maxSoFar; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/HaversineDistance.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/HaversineDistance.java
package com.baeldung.algorithms.latlondistance; public class HaversineDistance { private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM public static double calculateDistance(double startLat, double startLong, double endLat, double endLong) { double dLat = Math.toRadians((endLat - startLat)); double dLong = Math.toRadians((endLong - startLong)); startLat = Math.toRadians(startLat); endLat = Math.toRadians(endLat); double a = haversine(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversine(dLong); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return EARTH_RADIUS * c; } public static double haversine(double val) { return Math.pow(Math.sin(val / 2), 2); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/EquirectangularApproximation.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/EquirectangularApproximation.java
package com.baeldung.algorithms.latlondistance; public class EquirectangularApproximation { private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double lon1Rad = Math.toRadians(lon1); double lon2Rad = Math.toRadians(lon2); double x = (lon2Rad - lon1Rad) * Math.cos((lat1Rad + lat2Rad) / 2); double y = (lat2Rad - lat1Rad); double distance = Math.sqrt(x * x + y * y) * EARTH_RADIUS; return distance; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/VincentyDistance.java
algorithms-modules/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/latlondistance/VincentyDistance.java
package com.baeldung.algorithms.latlondistance; public class VincentyDistance { // Constants for WGS84 ellipsoid model of Earth private static final double SEMI_MAJOR_AXIS_MT = 6378137; private static final double SEMI_MINOR_AXIS_MT = 6356752.314245; private static final double FLATTENING = 1 / 298.257223563; private static final double ERROR_TOLERANCE = 1e-12; public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) { double U1 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude1))); double U2 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude2))); double sinU1 = Math.sin(U1); double cosU1 = Math.cos(U1); double sinU2 = Math.sin(U2); double cosU2 = Math.cos(U2); double longitudeDifference = Math.toRadians(longitude2 - longitude1); double previousLongitudeDifference; double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM; do { sinSigma = Math.sqrt(Math.pow(cosU2 * Math.sin(longitudeDifference), 2) + Math.pow(cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(longitudeDifference), 2)); cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(longitudeDifference); sigma = Math.atan2(sinSigma, cosSigma); sinAlpha = cosU1 * cosU2 * Math.sin(longitudeDifference) / sinSigma; cosSqAlpha = 1 - Math.pow(sinAlpha, 2); cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha; if (Double.isNaN(cos2SigmaM)) { cos2SigmaM = 0; } previousLongitudeDifference = longitudeDifference; double C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)); longitudeDifference = Math.toRadians(longitude2 - longitude1) + (1 - C) * FLATTENING * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)))); } while (Math.abs(longitudeDifference - previousLongitudeDifference) > ERROR_TOLERANCE); double uSq = cosSqAlpha * (Math.pow(SEMI_MAJOR_AXIS_MT, 2) - Math.pow(SEMI_MINOR_AXIS_MT, 2)) / Math.pow(SEMI_MINOR_AXIS_MT, 2); double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) - B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2)))); double distanceMt = SEMI_MINOR_AXIS_MT * A * (sigma - deltaSigma); return distanceMt / 1000; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
package com.baeldung.algorithms.binarysearch; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class BinarySearchUnitTest { int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; int key = 6; int expectedIndexForSearchKey = 7; int low = 0; int high = sortedArray.length - 1; List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); @Test void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); } @Test void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); } @Test void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); } @Test void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); } @Test void givenSortedListOfIntegers_whenBinarySearchOnSortedArraysWithDuplicates_thenGetIndexOfDuplicates() { int[] sortedArray = { 1, 2, 3, 4, 5, 5, 5, 5, 5, 6, 7, 7, 8, 9 }; BinarySearch binSearch = new BinarySearch(); assertEquals(Arrays.asList(4, 5, 6, 7, 8), binSearch.runBinarySearchOnSortedArraysWithDuplicates(sortedArray, 5)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java
package com.baeldung.algorithms.suffixtree; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class SuffixTreeUnitTest { private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class); private static SuffixTree suffixTree; @BeforeAll public static void setUp() { suffixTree = new SuffixTree("havanabanana"); printTree(); } @Test void givenSuffixTree_whenSearchingForA_thenReturn6Matches() { List<String> matches = suffixTree.searchText("a"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray()); } @Test void givenSuffixTree_whenSearchingForNab_thenReturn1Match() { List<String> matches = suffixTree.searchText("nab"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray()); } @Test void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() { List<String> matches = suffixTree.searchText("nag"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] {}, matches.toArray()); } @Test void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() { List<String> matches = suffixTree.searchText("ana"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray()); } @Test void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() { List<String> matches = suffixTree.searchText("na"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray()); } @Test void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() { List<String> matches = suffixTree.searchText("x"); matches.stream() .forEach(m -> LOGGER.debug(m)); assertArrayEquals(new String[] {}, matches.toArray()); } private static void printTree() { suffixTree.printTree(); LOGGER.debug("\n" + suffixTree.printTree()); LOGGER.debug("=============================================="); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/breadthfirstsearch/BreadthFirstSearchAlgorithmUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/breadthfirstsearch/BreadthFirstSearchAlgorithmUnitTest.java
package com.baeldung.algorithms.breadthfirstsearch; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class BreadthFirstSearchAlgorithmUnitTest { private Tree<Integer> root; private Tree<Integer> rootFirstChild; private Tree<Integer> depthMostChild; private Tree<Integer> rootSecondChild; private Node<Integer> start; private Node<Integer> firstNeighbor; private Node<Integer> firstNeighborNeighbor; private Node<Integer> secondNeighbor; @Test void givenTree_whenSearchTen_thenRoot() { initTree(); assertThat(BreadthFirstSearchAlgorithm.search(10, root)).isPresent().contains(root); } @Test void givenTree_whenSearchThree_thenDepthMostValue() { initTree(); assertThat(BreadthFirstSearchAlgorithm.search(3, root)).isPresent().contains(depthMostChild); } @Test void givenTree_whenSearchFour_thenRootSecondChild() { initTree(); assertThat(BreadthFirstSearchAlgorithm.search(4, root)).isPresent().contains(rootSecondChild); } @Test void givenTree_whenSearchFive_thenNotFound() { initTree(); assertThat(BreadthFirstSearchAlgorithm.search(5, root)).isEmpty(); } private void initTree() { root = Tree.of(10); rootFirstChild = root.addChild(2); depthMostChild = rootFirstChild.addChild(3); rootSecondChild = root.addChild(4); } @Test void givenNode_whenSearchTen_thenStart() { initNode(); assertThat(BreadthFirstSearchAlgorithm.search(10, firstNeighborNeighbor)).isPresent().contains(start); } @Test void givenNode_whenSearchThree_thenNeighborNeighbor() { initNode(); assertThat(BreadthFirstSearchAlgorithm.search(3, firstNeighborNeighbor)).isPresent().contains(firstNeighborNeighbor); } @Test void givenNode_whenSearchFour_thenSecondNeighbor() { initNode(); assertThat(BreadthFirstSearchAlgorithm.search(4, firstNeighborNeighbor)).isPresent().contains(secondNeighbor); } @Test void givenNode_whenSearchFive_thenNotFound() { initNode(); assertThat(BreadthFirstSearchAlgorithm.search(5, firstNeighborNeighbor)).isEmpty(); } private void initNode() { start = new Node<>(10); firstNeighbor = new Node<>(2); start.connect(firstNeighbor); firstNeighborNeighbor = new Node<>(3); firstNeighbor.connect(firstNeighborNeighbor); firstNeighborNeighbor.connect(start); secondNeighbor = new Node<>(4); start.connect(secondNeighbor); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
package com.baeldung.algorithms.mcts; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch; import com.baeldung.algorithms.mcts.montecarlo.State; import com.baeldung.algorithms.mcts.montecarlo.UCT; import com.baeldung.algorithms.mcts.tictactoe.Board; import com.baeldung.algorithms.mcts.tictactoe.Position; import com.baeldung.algorithms.mcts.tree.Tree; class MCTSUnitTest { private Tree gameTree; private MonteCarloTreeSearch mcts; @BeforeEach public void initGameTree() { gameTree = new Tree(); mcts = new MonteCarloTreeSearch(); } @Test void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { double uctValue = 15.79; assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01); } @Test void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { State initState = gameTree.getRoot().getState(); List<State> possibleStates = initState.getAllPossibleStates(); assertTrue(possibleStates.size() > 0); } @Test void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { Board board = new Board(); int initAvailablePositions = board.getEmptyPositions().size(); board.performMove(Board.P1, new Position(1, 1)); int availablePositions = board.getEmptyPositions().size(); assertTrue(initAvailablePositions > availablePositions); } @Test void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { Board board = new Board(); int player = Board.P1; int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; for (int i = 0; i < totalMoves; i++) { board = mcts.findNextMove(board, player); if (board.checkStatus() != -1) { break; } player = 3 - player; } int winStatus = board.checkStatus(); assertEquals(Board.DRAW, winStatus); } @Test void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { Board board = new Board(); MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch(); mcts1.setLevel(1); MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch(); mcts3.setLevel(3); int player = Board.P1; int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; for (int i = 0; i < totalMoves; i++) { if (player == Board.P1) board = mcts3.findNextMove(board, player); else board = mcts1.findNextMove(board, player); if (board.checkStatus() != -1) { break; } player = 3 - player; } int winStatus = board.checkStatus(); assertTrue(winStatus == Board.DRAW || winStatus == Board.P1); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java
package com.baeldung.algorithms.dfs; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.jupiter.api.Test; class GraphUnitTest { @Test void givenDirectedGraph_whenDFS_thenPrintAllValues() { Graph graph = createDirectedGraph(); boolean[] visited; visited = graph.dfs(0); boolean[] expected = new boolean[]{true, true, true, true, true, true}; Assert.assertArrayEquals(expected, visited); visited = graph.dfsWithoutRecursion(0); Assert.assertArrayEquals(expected, visited); } @Test void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { Graph graph = createDirectedGraph(); List<Integer> list = graph.topologicalSort(0); System.out.println(list); List<Integer> expected = Arrays.asList(0, 2, 1, 3, 4, 5); Assert.assertEquals(expected, list); } private Graph createDirectedGraph() { Graph graph = new Graph(); graph.addVertex(0); graph.addVertex(1); graph.addVertex(2); graph.addVertex(3); graph.addVertex(4); graph.addVertex(5); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.addEdge(4, 5); return graph; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java
package com.baeldung.algorithms.dfs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class BinaryTreeUnitTest { @Test void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { BinaryTree bt = createBinaryTree(); assertFalse(bt.isEmpty()); } @Test void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { BinaryTree bt = createBinaryTree(); assertTrue(bt.containsNode(6)); assertTrue(bt.containsNode(4)); assertFalse(bt.containsNode(1)); } @Test void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { BinaryTree bt = createBinaryTree(); int initialSize = bt.getSize(); assertTrue(bt.containsNode(3)); bt.add(3); assertEquals(initialSize, bt.getSize()); } @Test void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { BinaryTree bt = createBinaryTree(); assertFalse(bt.containsNode(99)); } @Test void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { BinaryTree bt = createBinaryTree(); assertTrue(bt.containsNode(9)); bt.delete(9); assertFalse(bt.containsNode(9)); } @Test void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { BinaryTree bt = createBinaryTree(); int initialSize = bt.getSize(); assertFalse(bt.containsNode(99)); bt.delete(99); assertFalse(bt.containsNode(99)); assertEquals(initialSize, bt.getSize()); } @Test void it_deletes_the_root() { int value = 12; BinaryTree bt = new BinaryTree(); bt.add(value); assertTrue(bt.containsNode(value)); bt.delete(value); assertFalse(bt.containsNode(value)); } @Test void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); System.out.println(); bt.traverseInOrderWithoutRecursion(); } @Test void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); System.out.println(); bt.traversePreOrderWithoutRecursion(); } @Test void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); System.out.println(); bt.traversePostOrderWithoutRecursion(); } private BinaryTree createBinaryTree() { BinaryTree bt = new BinaryTree(); bt.add(6); bt.add(4); bt.add(8); bt.add(3); bt.add(5); bt.add(7); bt.add(9); return bt; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java
package com.baeldung.algorithms.kthsmallest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import java.util.*; import static com.baeldung.algorithms.kthsmallest.KthSmallest.*; import static org.junit.jupiter.api.Assertions.*; class KthSmallestUnitTest { @Nested class Exceptions { @Test void when_at_least_one_list_is_null_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(1, null, null); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null); Executable executable3 = () -> findKthSmallestElement(1, null, new int[]{2}); assertThrows(IllegalArgumentException.class, executable1); assertThrows(IllegalArgumentException.class, executable2); assertThrows(IllegalArgumentException.class, executable3); } @Test void when_at_least_one_list_is_empty_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2}); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{}); Executable executable3 = () -> findKthSmallestElement(1, new int[]{}, new int[]{}); assertThrows(IllegalArgumentException.class, executable1); assertThrows(IllegalArgumentException.class, executable2); assertThrows(IllegalArgumentException.class, executable3); } @Test void when_k_is_smaller_than_0_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2}); assertThrows(IllegalArgumentException.class, executable1); } @Test void when_k_is_smaller_than_1_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2}); assertThrows(IllegalArgumentException.class, executable1); } @Test void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5}); assertThrows(NoSuchElementException.class, executable1); } } @Nested class K_is_smaller_than_the_size_of_list1_and_the_size_of_list2 { @Test public void when_k_is_1_then_the_smallest_element_is_returned_from_list1() { int result = findKthSmallestElement(1, new int[]{2, 7}, new int[]{3, 5}); assertEquals(2, result); } @Test public void when_k_is_1_then_the_smallest_element_is_returned_list2() { int result = findKthSmallestElement(1, new int[]{3, 5}, new int[]{2, 7}); assertEquals(2, result); } @Test public void when_kth_element_is_smallest_element_and_occurs_in_both_lists() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(1, list1, list2); assertEquals(1, result); } @Test public void when_kth_element_is_smallest_element_and_occurs_in_both_lists2() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(2, list1, list2); assertEquals(1, result); } @Test public void when_kth_element_is_largest_element_and_occurs_in_both_lists_1() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(5, list1, list2); assertEquals(3, result); } @Test public void when_kth_element_is_largest_element_and_occurs_in_both_lists_2() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(6, list1, list2); assertEquals(3, result); } @Test public void when_kth_element_and_occurs_in_both_lists() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{0, 2, 3}; int result = findKthSmallestElement(3, list1, list2); assertEquals(2, result); } @Test public void and_kth_element_is_in_first_list() { int[] list1 = new int[]{1,2,3,4}; int[] list2 = new int[]{1,3,4,5}; int result = findKthSmallestElement(3, list1, list2); assertEquals(2, result); } @Test public void and_kth_is_in_second_list() { int[] list1 = new int[]{1,3,4,4}; int[] list2 = new int[]{1,2,4,5}; int result = findKthSmallestElement(3, list1, list2); assertEquals(2, result); } @Test public void and_elements_in_first_list_are_all_smaller_than_second_list() { int[] list1 = new int[]{1,3,7,9}; int[] list2 = new int[]{11,12,14,15}; int result = findKthSmallestElement(3, list1, list2); assertEquals(7, result); } @Test public void and_elements_in_first_list_are_all_smaller_than_second_list2() { int[] list1 = new int[]{1,3,7,9}; int[] list2 = new int[]{11,12,14,15}; int result = findKthSmallestElement(4, list1, list2); assertEquals(9, result); } @Test public void and_only_elements_from_second_list_are_part_of_result() { int[] list1 = new int[]{11,12,14,15}; int[] list2 = new int[]{1,3,7,9}; int result = findKthSmallestElement(3, list1, list2); assertEquals(7, result); } @Test public void and_only_elements_from_second_list_are_part_of_result2() { int[] list1 = new int[]{11,12,14,15}; int[] list2 = new int[]{1,3,7,9}; int result = findKthSmallestElement(4, list1, list2); assertEquals(9, result); } } @Nested class K_is_bigger_than_the_size_of_at_least_one_of_the_lists { @Test public void k_is_smaller_than_list1_and_bigger_than_list2() { int[] list1 = new int[]{1, 2, 3, 4, 7, 9}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(5, list1, list2); assertEquals(3, result); } @Test public void k_is_bigger_than_list1_and_smaller_than_list2() { int[] list1 = new int[]{1, 2, 3}; int[] list2 = new int[]{1, 2, 3, 4, 7, 9}; int result = findKthSmallestElement(5, list1, list2); assertEquals(3, result); } @Test public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_smaller_than_first_list() { int[] list1 = new int[]{9, 11, 13, 55}; int[] list2 = new int[]{1, 2, 3, 7}; int result = findKthSmallestElement(6, list1, list2); assertEquals(11, result); } @Test public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_bigger_than_first_list() { int[] list1 = new int[]{1, 2, 3, 7}; int[] list2 = new int[]{9, 11, 13, 55}; int result = findKthSmallestElement(6, list1, list2); assertEquals(11, result); } @Test public void when_k_is_bigger_than_the_size_of_both_lists() { int[] list1 = new int[]{3, 7, 9, 11, 55}; int[] list2 = new int[]{1, 2, 3, 7, 13}; int result = findKthSmallestElement(7, list1, list2); assertEquals(9, result); } @Test public void when_k_is_bigger_than_the_size_of_both_lists_and_list1_has_more_elements_than_list2() { int[] list1 = new int[]{3, 7, 9, 11, 55, 77, 100, 200}; int[] list2 = new int[]{1, 2, 3, 7, 13}; int result = findKthSmallestElement(11, list1, list2); assertEquals(77, result); } @Test public void max_test() { int[] list1 = new int[]{100, 200}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(4, list1, list2); assertEquals(100, result); } @Test public void max_test2() { int[] list1 = new int[]{100, 200}; int[] list2 = new int[]{1, 2, 3}; int result = findKthSmallestElement(5, list1, list2); assertEquals(200, result); } @Test public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_in_list2() { int[] list1 = new int[]{1, 2, 5}; int[] list2 = new int[]{1, 3, 4, 7}; int result = findKthSmallestElement(4, list1, list2); assertEquals(3, result); } @Test public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list2() { int[] list1 = new int[]{1, 2, 5}; int[] list2 = new int[]{3, 4, 7}; int result = findKthSmallestElement(3, list1, list2); assertEquals(3, result); } @Test public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list23() { int[] list1 = new int[]{3, 11, 27, 53, 90}; int[] list2 = new int[]{4, 20, 21, 100}; int result = findKthSmallestElement(5, list1, list2); assertEquals(21, result); } } // @Test // public void randomTests() { // IntStream.range(1, 100000).forEach(i -> random()); // } private void random() { Random random = new Random(); int length1 = (Math.abs(random.nextInt())) % 1000 + 1; int length2 = (Math.abs(random.nextInt())) % 1000 + 1; int[] list1 = sortedRandomIntArrayOfLength(length1); int[] list2 = sortedRandomIntArrayOfLength(length2); int k = (Math.abs(random.nextInt()) % (length1 + length2)) + 1 ; int result = findKthSmallestElement(k, list1, list2); int result2 = getKthElementSorted(list1, list2, k); int result3 = getKthElementMerge(list1, list2, k); assertEquals(result2, result); assertEquals(result2, result3); } private int[] sortedRandomIntArrayOfLength(int length) { int[] intArray = new Random().ints(length).toArray(); Arrays.sort(intArray); return intArray; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/firstnonrepeating/FirstNonRepeatingElementUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/firstnonrepeating/FirstNonRepeatingElementUnitTest.java
package com.baeldung.algorithms.firstnonrepeating; 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; public class FirstNonRepeatingElementUnitTest { private List<Integer> list; @BeforeEach void setUp() { list = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4); } @Test void whenUsingForLoop_thenReturnFirstNonRepeatingElement() { int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingForLoop(list); assertEquals(3, result); } @Test void whenUsingIndexOf_thenReturnFirstNonRepeatingElement() { int result = FirstNonRepeatingElement.findFirstNonRepeatedElementUsingIndex(list); assertEquals(3, result); } @Test void whenUsingHashMap_thenReturnFirstNonRepeatingElement() { int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingHashMap(list); assertEquals(3, result); } @Test void whenUsingArray_thenReturnFirstNonRepeatingElement() { int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingArray(list); assertEquals(3, result); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java
package com.baeldung.algorithms.quadtree; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class QuadTreeSearchUnitTest { private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class); private static QuadTree quadTree; @BeforeAll public static void setUp() { Region area = new Region(0, 0, 400, 400); quadTree = new QuadTree(area); float[][] points = new float[][] { { 21, 25 }, { 55, 53 }, { 70, 318 }, { 98, 302 }, { 49, 229 }, { 135, 229 }, { 224, 292 }, { 206, 321 }, { 197, 258 }, { 245, 238 } }; for (int i = 0; i < points.length; i++) { Point point = new Point(points[i][0], points[i][1]); quadTree.addPoint(point); } LOGGER.debug("\n" + quadTree.printTree("")); LOGGER.debug("=============================================="); } @Test void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() { Region searchArea = new Region(200, 200, 250, 250); List<Point> result = quadTree.search(searchArea, null, ""); LOGGER.debug(result.toString()); LOGGER.debug(quadTree.printSearchTraversePath()); assertEquals(1, result.size()); assertArrayEquals(new float[] { 245, 238 }, new float[]{result.get(0).getX(), result.get(0).getY() }, 0); } @Test void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() { Region searchArea = new Region(0, 0, 100, 100); List<Point> result = quadTree.search(searchArea, null, ""); LOGGER.debug(result.toString()); LOGGER.debug(quadTree.printSearchTraversePath()); assertEquals(2, result.size()); assertArrayEquals(new float[] { 21, 25 }, new float[]{result.get(0).getX(), result.get(0).getY() }, 0); assertArrayEquals(new float[] { 55, 53 }, new float[]{result.get(1).getX(), result.get(1).getY() }, 0); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java
package com.baeldung.algorithms.textsearch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class TextSearchAlgorithmsUnitTest { @Test void testStringSearchAlgorithms() { String text = "This is some nice text."; String pattern = "some"; int realPosition = text.indexOf(pattern); assertEquals(TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()), realPosition); assertEquals(TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()), realPosition); assertEquals(TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()) , realPosition); assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()), realPosition); assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()), realPosition); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java
algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java
package com.baeldung.algorithms.interpolationsearch; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class InterpolationSearchUnitTest { private int[] myData; @BeforeEach public void setUp() { myData = new int[]{13,21,34,55,69,73,84,101}; } @Test void givenSortedArray_whenLookingFor84_thenReturn6() { int pos = InterpolationSearch.interpolationSearch(myData, 84); assertEquals(6, pos); } @Test void givenSortedArray_whenLookingFor19_thenReturnMinusOne() { int pos = InterpolationSearch.interpolationSearch(myData, 19); assertEquals(-1, pos); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java
package com.baeldung.algorithms.binarysearch; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class BinarySearch { public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) { int index = Integer.MAX_VALUE; while (low <= high) { int mid = low + ((high - low) / 2); if (sortedArray[mid] < key) { low = mid + 1; } else if (sortedArray[mid] > key) { high = mid - 1; } else if (sortedArray[mid] == key) { index = mid; break; } } return index; } public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) { int middle = low + ((high - low) / 2); if (high < low) { return -1; } if (key == sortedArray[middle]) { return middle; } else if (key < sortedArray[middle]) { return runBinarySearchRecursively(sortedArray, key, low, middle - 1); } else { return runBinarySearchRecursively(sortedArray, key, middle + 1, high); } } public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) { int index = Arrays.binarySearch(sortedArray, key); return index; } public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) { int index = Collections.binarySearch(sortedList, key); return index; } public List<Integer> runBinarySearchOnSortedArraysWithDuplicates(int[] sortedArray, Integer key) { int startIndex = startIndexSearch(sortedArray, key); int endIndex = endIndexSearch(sortedArray, key); return IntStream.rangeClosed(startIndex, endIndex) .boxed() .collect(Collectors.toList()); } private int endIndexSearch(int[] sortedArray, int target) { int left = 0; int right = sortedArray.length - 1; int result = -1; while (left <= right) { int mid = left + (right - left) / 2; if (sortedArray[mid] == target) { result = mid; left = mid + 1; } else if (sortedArray[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return result; } private int startIndexSearch(int[] sortedArray, int target) { int left = 0; int right = sortedArray.length - 1; int result = -1; while (left <= right) { int mid = left + (right - left) / 2; if (sortedArray[mid] == target) { result = mid; right = mid - 1; } else if (sortedArray[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return result; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/Node.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/Node.java
package com.baeldung.algorithms.suffixtree; import java.util.ArrayList; import java.util.List; public class Node { private String text; private List<Node> children; private int position; public Node(String word, int position) { this.text = word; this.position = position; this.children = new ArrayList<>(); } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public List<Node> getChildren() { return children; } public void setChildren(List<Node> children) { this.children = children; } public String printTree(String depthIndicator) { String str = ""; String positionStr = position > -1 ? "[" + String.valueOf(position) + "]" : ""; str += depthIndicator + text + positionStr + "\n"; for (int i = 0; i < children.size(); i++) { str += children.get(i) .printTree(depthIndicator + "\t"); } return str; } @Override public String toString() { return printTree(""); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/SuffixTree.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/suffixtree/SuffixTree.java
package com.baeldung.algorithms.suffixtree; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SuffixTree { private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTree.class); private static final String WORD_TERMINATION = "$"; private static final int POSITION_UNDEFINED = -1; private Node root; private String fullText; public SuffixTree(String text) { root = new Node("", POSITION_UNDEFINED); for (int i = 0; i < text.length(); i++) { addSuffix(text.substring(i) + WORD_TERMINATION, i); } fullText = text; } public List<String> searchText(String pattern) { LOGGER.debug("Searching for pattern \"{}\"", pattern); List<String> result = new ArrayList<>(); List<Node> nodes = getAllNodesInTraversePath(pattern, root, false); if (nodes.size() > 0) { Node lastNode = nodes.get(nodes.size() - 1); if (lastNode != null) { List<Integer> positions = getPositions(lastNode); positions = positions.stream() .sorted() .collect(Collectors.toList()); positions.forEach(m -> result.add((markPatternInText(m, pattern)))); } } return result; } private void addSuffix(String suffix, int position) { LOGGER.debug(">>>>>>>>>>>> Adding new suffix {}", suffix); List<Node> nodes = getAllNodesInTraversePath(suffix, root, true); if (nodes.size() == 0) { addChildNode(root, suffix, position); LOGGER.debug("{}", printTree()); } else { Node lastNode = nodes.remove(nodes.size() - 1); String newText = suffix; if (nodes.size() > 0) { String existingSuffixUptoLastNode = nodes.stream() .map(a -> a.getText()) .reduce("", String::concat); // Remove prefix from newText already included in parent newText = newText.substring(existingSuffixUptoLastNode.length()); } extendNode(lastNode, newText, position); LOGGER.debug("{}", printTree()); } } private List<Integer> getPositions(Node node) { List<Integer> positions = new ArrayList<>(); if (node.getText() .endsWith(WORD_TERMINATION)) { positions.add(node.getPosition()); } for (int i = 0; i < node.getChildren() .size(); i++) { positions.addAll(getPositions(node.getChildren() .get(i))); } return positions; } private String markPatternInText(Integer startPosition, String pattern) { String matchingTextLHS = fullText.substring(0, startPosition); String matchingText = fullText.substring(startPosition, startPosition + pattern.length()); String matchingTextRHS = fullText.substring(startPosition + pattern.length()); return matchingTextLHS + "[" + matchingText + "]" + matchingTextRHS; } private void addChildNode(Node parentNode, String text, int position) { parentNode.getChildren() .add(new Node(text, position)); } private void extendNode(Node node, String newText, int position) { String currentText = node.getText(); String commonPrefix = getLongestCommonPrefix(currentText, newText); if (commonPrefix != currentText) { String parentText = currentText.substring(0, commonPrefix.length()); String childText = currentText.substring(commonPrefix.length()); splitNodeToParentAndChild(node, parentText, childText); } String remainingText = newText.substring(commonPrefix.length()); addChildNode(node, remainingText, position); } private void splitNodeToParentAndChild(Node parentNode, String parentNewText, String childNewText) { Node childNode = new Node(childNewText, parentNode.getPosition()); if (parentNode.getChildren() .size() > 0) { while (parentNode.getChildren() .size() > 0) { childNode.getChildren() .add(parentNode.getChildren() .remove(0)); } } parentNode.getChildren() .add(childNode); parentNode.setText(parentNewText); parentNode.setPosition(POSITION_UNDEFINED); } private String getLongestCommonPrefix(String str1, String str2) { int compareLength = Math.min(str1.length(), str2.length()); for (int i = 0; i < compareLength; i++) { if (str1.charAt(i) != str2.charAt(i)) { return str1.substring(0, i); } } return str1.substring(0, compareLength); } private List<Node> getAllNodesInTraversePath(String pattern, Node startNode, boolean isAllowPartialMatch) { List<Node> nodes = new ArrayList<>(); for (int i = 0; i < startNode.getChildren() .size(); i++) { Node currentNode = startNode.getChildren() .get(i); String nodeText = currentNode.getText(); if (pattern.charAt(0) == nodeText.charAt(0)) { if (isAllowPartialMatch && pattern.length() <= nodeText.length()) { nodes.add(currentNode); return nodes; } int compareLength = Math.min(nodeText.length(), pattern.length()); for (int j = 1; j < compareLength; j++) { if (pattern.charAt(j) != nodeText.charAt(j)) { if (isAllowPartialMatch) { nodes.add(currentNode); } return nodes; } } nodes.add(currentNode); if (pattern.length() > compareLength) { List<Node> nodes2 = getAllNodesInTraversePath(pattern.substring(compareLength), currentNode, isAllowPartialMatch); if (nodes2.size() > 0) { nodes.addAll(nodes2); } else if (!isAllowPartialMatch) { nodes.add(null); } } return nodes; } } return nodes; } public String printTree() { return root.printTree(""); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/Node.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/Node.java
package com.baeldung.algorithms.breadthfirstsearch; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Node<T> { private T value; private Set<Node<T>> neighbors; public Node(T value) { this.value = value; this.neighbors = new HashSet<>(); } public T getValue() { return value; } public Set<Node<T>> getNeighbors() { return Collections.unmodifiableSet(neighbors); } public void connect(Node<T> node) { if (this == node) throw new IllegalArgumentException("Can't connect node to itself"); this.neighbors.add(node); node.neighbors.add(this); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/Tree.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/Tree.java
package com.baeldung.algorithms.breadthfirstsearch; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Tree<T> { private T value; private List<Tree<T>> children; private Tree(T value) { this.value = value; this.children = new ArrayList<>(); } public static <T> Tree<T> of(T value) { return new Tree<>(value); } public T getValue() { return value; } public List<Tree<T>> getChildren() { return Collections.unmodifiableList(children); } public Tree<T> addChild(T value) { Tree<T> newChild = new Tree<>(value); children.add(newChild); return newChild; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/BreadthFirstSearchAlgorithm.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/breadthfirstsearch/BreadthFirstSearchAlgorithm.java
package com.baeldung.algorithms.breadthfirstsearch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class BreadthFirstSearchAlgorithm { private static final Logger LOGGER = LoggerFactory.getLogger(BreadthFirstSearchAlgorithm.class); public static <T> Optional<Tree<T>> search(T value, Tree<T> root) { Queue<Tree<T>> queue = new ArrayDeque<>(); queue.add(root); Tree<T> currentNode; while (!queue.isEmpty()) { currentNode = queue.remove(); LOGGER.debug("Visited node with value: {}", currentNode.getValue()); if (currentNode.getValue().equals(value)) { return Optional.of(currentNode); } else { queue.addAll(currentNode.getChildren()); } } return Optional.empty(); } public static <T> Optional<Node<T>> search(T value, Node<T> start) { Queue<Node<T>> queue = new ArrayDeque<>(); queue.add(start); Node<T> currentNode; Set<Node<T>> alreadyVisited = new HashSet<>(); while (!queue.isEmpty()) { currentNode = queue.remove(); LOGGER.debug("Visited node with value: {}", currentNode.getValue()); if (currentNode.getValue().equals(value)) { return Optional.of(currentNode); } else { alreadyVisited.add(currentNode); queue.addAll(currentNode.getNeighbors()); queue.removeAll(alreadyVisited); } } return Optional.empty(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
package com.baeldung.algorithms.mcts.montecarlo; import java.util.List; import com.baeldung.algorithms.mcts.tictactoe.Board; import com.baeldung.algorithms.mcts.tree.Node; import com.baeldung.algorithms.mcts.tree.Tree; public class MonteCarloTreeSearch { private static final int WIN_SCORE = 10; private int level; private int opponent; public MonteCarloTreeSearch() { this.level = 3; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } private int getMillisForCurrentLevel() { return 2 * (this.level - 1) + 1; } public Board findNextMove(Board board, int playerNo) { long start = System.currentTimeMillis(); long end = start + 60 * getMillisForCurrentLevel(); opponent = 3 - playerNo; Tree tree = new Tree(); Node rootNode = tree.getRoot(); rootNode.getState().setBoard(board); rootNode.getState().setPlayerNo(opponent); while (System.currentTimeMillis() < end) { // Phase 1 - Selection Node promisingNode = selectPromisingNode(rootNode); // Phase 2 - Expansion if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS) expandNode(promisingNode); // Phase 3 - Simulation Node nodeToExplore = promisingNode; if (promisingNode.getChildArray().size() > 0) { nodeToExplore = promisingNode.getRandomChildNode(); } int playoutResult = simulateRandomPlayout(nodeToExplore); // Phase 4 - Update backPropogation(nodeToExplore, playoutResult); } Node winnerNode = rootNode.getChildWithMaxScore(); tree.setRoot(winnerNode); return winnerNode.getState().getBoard(); } private Node selectPromisingNode(Node rootNode) { Node node = rootNode; while (node.getChildArray().size() != 0) { node = UCT.findBestNodeWithUCT(node); } return node; } private void expandNode(Node node) { List<State> possibleStates = node.getState().getAllPossibleStates(); possibleStates.forEach(state -> { Node newNode = new Node(state); newNode.setParent(node); newNode.getState().setPlayerNo(node.getState().getOpponent()); node.getChildArray().add(newNode); }); } private void backPropogation(Node nodeToExplore, int playerNo) { Node tempNode = nodeToExplore; while (tempNode != null) { tempNode.getState().incrementVisit(); if (tempNode.getState().getPlayerNo() == playerNo) tempNode.getState().addScore(WIN_SCORE); tempNode = tempNode.getParent(); } } private int simulateRandomPlayout(Node node) { Node tempNode = new Node(node); State tempState = tempNode.getState(); int boardStatus = tempState.getBoard().checkStatus(); if (boardStatus == opponent) { tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE); return boardStatus; } while (boardStatus == Board.IN_PROGRESS) { tempState.togglePlayer(); tempState.randomPlay(); boardStatus = tempState.getBoard().checkStatus(); } return boardStatus; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
package com.baeldung.algorithms.mcts.montecarlo; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.baeldung.algorithms.mcts.tree.Node; public class UCT { public static double uctValue(int totalVisit, double nodeWinScore, int nodeVisit) { if (nodeVisit == 0) { return Integer.MAX_VALUE; } return (nodeWinScore / (double) nodeVisit) + 1.41 * Math.sqrt(Math.log(totalVisit) / (double) nodeVisit); } static Node findBestNodeWithUCT(Node node) { int parentVisit = node.getState().getVisitCount(); return Collections.max( node.getChildArray(), Comparator.comparing(c -> uctValue(parentVisit, c.getState().getWinScore(), c.getState().getVisitCount()))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
package com.baeldung.algorithms.mcts.montecarlo; import java.util.ArrayList; import java.util.List; import com.baeldung.algorithms.mcts.tictactoe.Board; import com.baeldung.algorithms.mcts.tictactoe.Position; public class State { private Board board; private int playerNo; private int visitCount; private double winScore; public State() { board = new Board(); } public State(State state) { this.board = new Board(state.getBoard()); this.playerNo = state.getPlayerNo(); this.visitCount = state.getVisitCount(); this.winScore = state.getWinScore(); } public State(Board board) { this.board = new Board(board); } Board getBoard() { return board; } void setBoard(Board board) { this.board = board; } int getPlayerNo() { return playerNo; } void setPlayerNo(int playerNo) { this.playerNo = playerNo; } int getOpponent() { return 3 - playerNo; } public int getVisitCount() { return visitCount; } public void setVisitCount(int visitCount) { this.visitCount = visitCount; } double getWinScore() { return winScore; } void setWinScore(double winScore) { this.winScore = winScore; } public List<State> getAllPossibleStates() { List<State> possibleStates = new ArrayList<>(); List<Position> availablePositions = this.board.getEmptyPositions(); availablePositions.forEach(p -> { State newState = new State(this.board); newState.setPlayerNo(3 - this.playerNo); newState.getBoard().performMove(newState.getPlayerNo(), p); possibleStates.add(newState); }); return possibleStates; } void incrementVisit() { this.visitCount++; } void addScore(double score) { if (this.winScore != Integer.MIN_VALUE) this.winScore += score; } void randomPlay() { List<Position> availablePositions = this.board.getEmptyPositions(); int totalPossibilities = availablePositions.size(); int selectRandom = (int) (Math.random() * totalPossibilities); this.board.performMove(this.playerNo, availablePositions.get(selectRandom)); } void togglePlayer() { this.playerNo = 3 - this.playerNo; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
package com.baeldung.algorithms.mcts.tictactoe; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Board { int[][] boardValues; int totalMoves; public static final int DEFAULT_BOARD_SIZE = 3; public static final int IN_PROGRESS = -1; public static final int DRAW = 0; public static final int P1 = 1; public static final int P2 = 2; public Board() { boardValues = new int[DEFAULT_BOARD_SIZE][DEFAULT_BOARD_SIZE]; } public Board(int boardSize) { boardValues = new int[boardSize][boardSize]; } public Board(int[][] boardValues) { this.boardValues = boardValues; } public Board(int[][] boardValues, int totalMoves) { this.boardValues = boardValues; this.totalMoves = totalMoves; } public Board(Board board) { int boardLength = board.getBoardValues().length; this.boardValues = new int[boardLength][boardLength]; int[][] boardValues = board.getBoardValues(); int n = boardValues.length; for (int i = 0; i < n; i++) { int m = boardValues[i].length; for (int j = 0; j < m; j++) { this.boardValues[i][j] = boardValues[i][j]; } } } public void performMove(int player, Position p) { this.totalMoves++; boardValues[p.getX()][p.getY()] = player; } public int[][] getBoardValues() { return boardValues; } public void setBoardValues(int[][] boardValues) { this.boardValues = boardValues; } public int checkStatus() { int boardSize = boardValues.length; int maxIndex = boardSize - 1; int[] diag1 = new int[boardSize]; int[] diag2 = new int[boardSize]; for (int i = 0; i < boardSize; i++) { int[] row = boardValues[i]; int[] col = new int[boardSize]; for (int j = 0; j < boardSize; j++) { col[j] = boardValues[j][i]; } int checkRowForWin = checkForWin(row); if(checkRowForWin!=0) return checkRowForWin; int checkColForWin = checkForWin(col); if(checkColForWin!=0) return checkColForWin; diag1[i] = boardValues[i][i]; diag2[i] = boardValues[maxIndex - i][i]; } int checkDia1gForWin = checkForWin(diag1); if(checkDia1gForWin!=0) return checkDia1gForWin; int checkDiag2ForWin = checkForWin(diag2); if(checkDiag2ForWin!=0) return checkDiag2ForWin; if (getEmptyPositions().size() > 0) return IN_PROGRESS; else return DRAW; } private int checkForWin(int[] row) { boolean isEqual = true; int size = row.length; int previous = row[0]; for (int i = 0; i < size; i++) { if (previous != row[i]) { isEqual = false; break; } previous = row[i]; } if(isEqual) return previous; else return 0; } public void printBoard() { int size = this.boardValues.length; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(boardValues[i][j] + " "); } System.out.println(); } } public List<Position> getEmptyPositions() { int size = this.boardValues.length; List<Position> emptyPositions = new ArrayList<>(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (boardValues[i][j] == 0) emptyPositions.add(new Position(i, j)); } } return emptyPositions; } public void printStatus() { switch (this.checkStatus()) { case P1: System.out.println("Player 1 wins"); break; case P2: System.out.println("Player 2 wins"); break; case DRAW: System.out.println("Game Draw"); break; case IN_PROGRESS: System.out.println("Game In Progress"); break; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
package com.baeldung.algorithms.mcts.tictactoe; public class Position { int x; int y; public Position() { } public Position(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
package com.baeldung.algorithms.mcts.tree; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.baeldung.algorithms.mcts.montecarlo.State; public class Node { State state; Node parent; List<Node> childArray; public Node() { this.state = new State(); childArray = new ArrayList<>(); } public Node(State state) { this.state = state; childArray = new ArrayList<>(); } public Node(State state, Node parent, List<Node> childArray) { this.state = state; this.parent = parent; this.childArray = childArray; } public Node(Node node) { this.childArray = new ArrayList<>(); this.state = new State(node.getState()); if (node.getParent() != null) this.parent = node.getParent(); List<Node> childArray = node.getChildArray(); for (Node child : childArray) { this.childArray.add(new Node(child)); } } public State getState() { return state; } public void setState(State state) { this.state = state; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } public List<Node> getChildArray() { return childArray; } public void setChildArray(List<Node> childArray) { this.childArray = childArray; } public Node getRandomChildNode() { int noOfPossibleMoves = this.childArray.size(); int selectRandom = (int) (Math.random() * noOfPossibleMoves); return this.childArray.get(selectRandom); } public Node getChildWithMaxScore() { return Collections.max(this.childArray, Comparator.comparing(c -> { return c.getState().getVisitCount(); })); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
package com.baeldung.algorithms.mcts.tree; public class Tree { Node root; public Tree() { root = new Node(); } public Tree(Node root) { this.root = root; } public Node getRoot() { return root; } public void setRoot(Node root) { this.root = root; } public void addChild(Node parent, Node child) { parent.getChildArray().add(child); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java
package com.baeldung.algorithms.dfs; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; public class Graph { private Map<Integer, List<Integer>> adjVertices; public Graph() { this.adjVertices = new HashMap<Integer, List<Integer>>(); } public void addVertex(int vertex) { adjVertices.putIfAbsent(vertex, new ArrayList<>()); } public void addEdge(int src, int dest) { adjVertices.get(src).add(dest); } public boolean[] dfsWithoutRecursion(int start) { Stack<Integer> stack = new Stack<Integer>(); boolean[] isVisited = new boolean[adjVertices.size()]; stack.push(start); while (!stack.isEmpty()) { int current = stack.pop(); if(!isVisited[current]){ isVisited[current] = true; visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) stack.push(dest); } } } return isVisited; } public boolean[] dfs(int start) { boolean[] isVisited = new boolean[adjVertices.size()]; return dfsRecursive(start, isVisited); } private boolean[] dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } return isVisited; } public List<Integer> topologicalSort(int start) { LinkedList<Integer> result = new LinkedList<Integer>(); boolean[] isVisited = new boolean[adjVertices.size()]; topologicalSortRecursive(start, isVisited, result); return result; } private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList<Integer> result) { isVisited[current] = true; for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) topologicalSortRecursive(dest, isVisited, result); } result.addFirst(current); } private void visit(int value) { System.out.print(" " + value); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java
package com.baeldung.algorithms.dfs; import java.util.Stack; public class BinaryTree { Node root; public void add(int value) { root = addRecursive(root, value); } private Node addRecursive(Node current, int value) { if (current == null) { return new Node(value); } if (value < current.value) { current.left = addRecursive(current.left, value); } else if (value > current.value) { current.right = addRecursive(current.right, value); } return current; } public boolean isEmpty() { return root == null; } public int getSize() { return getSizeRecursive(root); } private int getSizeRecursive(Node current) { return current == null ? 0 : getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right); } public boolean containsNode(int value) { return containsNodeRecursive(root, value); } private boolean containsNodeRecursive(Node current, int value) { if (current == null) { return false; } if (value == current.value) { return true; } return value < current.value ? containsNodeRecursive(current.left, value) : containsNodeRecursive(current.right, value); } public void delete(int value) { root = deleteRecursive(root, value); } private Node deleteRecursive(Node current, int value) { if (current == null) { return null; } if (value == current.value) { // Case 1: no children if (current.left == null && current.right == null) { return null; } // Case 2: only 1 child if (current.right == null) { return current.left; } if (current.left == null) { return current.right; } // Case 3: 2 children int smallestValue = findSmallestValue(current.right); current.value = smallestValue; current.right = deleteRecursive(current.right, smallestValue); return current; } if (value < current.value) { current.left = deleteRecursive(current.left, value); return current; } current.right = deleteRecursive(current.right, value); return current; } private int findSmallestValue(Node root) { return root.left == null ? root.value : findSmallestValue(root.left); } public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } } public void traversePostOrder(Node node) { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); visit(node.value); } } public void traverseInOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.left; } Node top = stack.pop(); visit(top.value); current = top.right; } } public void traversePreOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current; stack.push(root); while(! stack.isEmpty()) { current = stack.pop(); visit(current.value); if(current.right != null) stack.push(current.right); if(current.left != null) stack.push(current.left); } } public void traversePostOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node prev = root; Node current; stack.push(root); while (!stack.isEmpty()) { current = stack.peek(); boolean hasChild = (current.left != null || current.right != null); boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); if (!hasChild || isPrevLastChild) { current = stack.pop(); visit(current.value); prev = current; } else { if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } } } private void visit(int value) { System.out.print(" " + value); } static class Node { int value; Node left; Node right; Node(int value) { this.value = value; right = null; left = null; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/kthsmallest/KthSmallest.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/kthsmallest/KthSmallest.java
package com.baeldung.algorithms.kthsmallest; import java.util.Arrays; import java.util.NoSuchElementException; import static java.lang.Math.max; import static java.lang.Math.min; public class KthSmallest { public static int findKthSmallestElement(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException { checkInput(k, list1, list2); // we are looking for the minimum value if(k == 1) { return min(list1[0], list2[0]); } // we are looking for the maximum value if(list1.length + list2.length == k) { return max(list1[list1.length-1], list2[list2.length-1]); } // swap lists if needed to make sure we take at least one element from list1 if(k <= list2.length && list2[k-1] < list1[0]) { int[] list1_ = list1; list1 = list2; list2 = list1_; } // correct left boundary if k is bigger than the size of list2 int left = k < list2.length ? 0 : k - list2.length - 1; // the inital right boundary cannot exceed the list1 int right = min(k-1, list1.length - 1); int nElementsList1, nElementsList2; // binary search do { nElementsList1 = ((left + right) / 2) + 1; nElementsList2 = k - nElementsList1; if(nElementsList2 > 0) { if (list1[nElementsList1 - 1] > list2[nElementsList2 - 1]) { right = nElementsList1 - 2; } else { left = nElementsList1; } } } while(!kthSmallesElementFound(list1, list2, nElementsList1, nElementsList2)); return nElementsList2 == 0 ? list1[nElementsList1-1] : max(list1[nElementsList1-1], list2[nElementsList2-1]); } private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) { // we do not take any element from the second list if(nElementsList2 < 1) { return true; } if(list1[nElementsList1-1] == list2[nElementsList2-1]) { return true; } if(nElementsList1 == list1.length) { return list1[nElementsList1-1] <= list2[nElementsList2]; } if(nElementsList2 == list2.length) { return list2[nElementsList2-1] <= list1[nElementsList1]; } return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1]; } private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException { if(list1 == null || list2 == null || k < 1) { throw new IllegalArgumentException(); } if(list1.length == 0 || list2.length == 0) { throw new IllegalArgumentException(); } if(k > list1.length + list2.length) { throw new NoSuchElementException(); } } public static int getKthElementSorted(int[] list1, int[] list2, int k) { int length1 = list1.length, length2 = list2.length; int[] combinedArray = new int[length1 + length2]; System.arraycopy(list1, 0, combinedArray, 0, list1.length); System.arraycopy(list2, 0, combinedArray, list1.length, list2.length); Arrays.sort(combinedArray); return combinedArray[k-1]; } public static int getKthElementMerge(int[] list1, int[] list2, int k) { int i1 = 0, i2 = 0; while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) { if(list1[i1] < list2[i2]) { i1++; } else { i2++; } } if((i1 + i2) < k) { return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1]; } else if(i1 > 0 && i2 > 0) { return Math.max(list1[i1-1], list2[i2-1]); } else { return i1 == 0 ? list2[i2-1] : list1[i1-1]; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/firstnonrepeating/FirstNonRepeatingElement.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/firstnonrepeating/FirstNonRepeatingElement.java
package com.baeldung.algorithms.firstnonrepeating; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class FirstNonRepeatingElement { public static Integer findFirstNonRepeatingUsingForLoop(List<Integer> list) { for (int i = 0; i < list.size(); i++) { int current = list.get(i); boolean isRepeating = false; for (int j = 0; j < list.size(); j++) { if (i != j && current == list.get(j)) { isRepeating = true; break; } } if (!isRepeating) { return current; } } return null; } public static Integer findFirstNonRepeatedElementUsingIndex(List<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.indexOf(list.get(i)) == list.lastIndexOf(list.get(i))) { return list.get(i); } } return null; } public static Integer findFirstNonRepeatingUsingHashMap(List<Integer> list) { Map<Integer, Integer> counts = new HashMap<>(); for (int num : list) { counts.put(num, counts.getOrDefault(num, 0) + 1); } for (int num : list) { if (counts.get(num) == 1) { return num; } } return null; } public static Integer findFirstNonRepeatingUsingArray(List<Integer> list) { int maxElement = Collections.max(list); int[] frequency = new int[maxElement + 1]; for (int num : list) { frequency[num]++; } for (int num : list) { if (frequency[num] == 1) { return num; } } return null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Region.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Region.java
package com.baeldung.algorithms.quadtree; public class Region { private float x1; private float y1; private float x2; private float y2; public Region(float x1, float y1, float x2, float y2) { if (x1 >= x2 || y1 >= y2) throw new IllegalArgumentException("(x1,y1) should be lesser than (x2,y2)"); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public Region getQuadrant(int quadrantIndex) { float quadrantWidth = (this.x2 - this.x1) / 2; float quadrantHeight = (this.y2 - this.y1) / 2; // 0=SW, 1=NW, 2=NE, 3=SE switch (quadrantIndex) { case 0: return new Region(x1, y1, x1 + quadrantWidth, y1 + quadrantHeight); case 1: return new Region(x1, y1 + quadrantHeight, x1 + quadrantWidth, y2); case 2: return new Region(x1 + quadrantWidth, y1 + quadrantHeight, x2, y2); case 3: return new Region(x1 + quadrantWidth, y1, x2, y1 + quadrantHeight); } return null; } public boolean containsPoint(Point point) { // Consider left and top side to be inclusive for points on border return point.getX() >= this.x1 && point.getX() < this.x2 && point.getY() >= this.y1 && point.getY() < this.y2; } public boolean doesOverlap(Region testRegion) { // Is test region completely to left of my region? if (testRegion.getX2() < this.getX1()) { return false; } // Is test region completely to right of my region? if (testRegion.getX1() > this.getX2()) { return false; } // Is test region completely above my region? if (testRegion.getY1() > this.getY2()) { return false; } // Is test region completely below my region? if (testRegion.getY2() < this.getY1()) { return false; } return true; } @Override public String toString() { return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]"; } public float getX1() { return x1; } public float getY1() { return y1; } public float getX2() { return x2; } public float getY2() { return y2; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Point.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/Point.java
package com.baeldung.algorithms.quadtree; public class Point { private float x; private float y; public Point(float x, float y) { this.x = x; this.y = y; } public float getX() { return x; } public float getY() { return y; } @Override public String toString() { return "[" + x + " , " + y + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/QuadTree.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/quadtree/QuadTree.java
package com.baeldung.algorithms.quadtree; import java.util.ArrayList; import java.util.List; public class QuadTree { private static final int MAX_POINTS = 3; private Region area; private List<Point> points = new ArrayList<>(); private List<QuadTree> quadTrees = new ArrayList<>(); private StringBuilder searchTraversePath; public QuadTree(Region area) { this.area = area; } public boolean addPoint(Point point) { if (this.area.containsPoint(point)) { if (this.points.size() < MAX_POINTS) { this.points.add(point); return true; } else { if (this.quadTrees.size() == 0) { createQuadrants(); } return addPointToOneQuadrant(point); } } return false; } private boolean addPointToOneQuadrant(Point point) { boolean isPointAdded; for (int i = 0; i < 4; i++) { isPointAdded = this.quadTrees.get(i) .addPoint(point); if (isPointAdded) return true; } return false; } private void createQuadrants() { Region region; for (int i = 0; i < 4; i++) { region = this.area.getQuadrant(i); quadTrees.add(new QuadTree(region)); } } public List<Point> search(Region searchRegion, List<Point> matches, String depthIndicator) { searchTraversePath = new StringBuilder(); if (matches == null) { matches = new ArrayList<Point>(); searchTraversePath.append(depthIndicator) .append("Search Boundary =") .append(searchRegion) .append("\n"); } if (!this.area.doesOverlap(searchRegion)) { return matches; } else { for (Point point : points) { if (searchRegion.containsPoint(point)) { searchTraversePath.append(depthIndicator) .append("Found match " + point) .append("\n"); matches.add(point); } } if (this.quadTrees.size() > 0) { for (int i = 0; i < 4; i++) { searchTraversePath.append(depthIndicator) .append("Q") .append(i) .append("-->") .append(quadTrees.get(i).area) .append("\n"); quadTrees.get(i) .search(searchRegion, matches, depthIndicator + "\t"); this.searchTraversePath.append(quadTrees.get(i) .printSearchTraversePath()); } } } return matches; } public String printTree(String depthIndicator) { String str = ""; if (depthIndicator == "") { str += "Root-->" + area.toString() + "\n"; } for (Point point : points) { str += depthIndicator + point.toString() + "\n"; } for (int i = 0; i < quadTrees.size(); i++) { str += depthIndicator + "Q" + String.valueOf(i) + "-->" + quadTrees.get(i).area.toString() + "\n"; str += quadTrees.get(i) .printTree(depthIndicator + "\t"); } return str; } public String printSearchTraversePath() { return searchTraversePath.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithms.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithms.java
package com.baeldung.algorithms.textsearch; import java.math.BigInteger; import java.util.Random; public class TextSearchAlgorithms { public static long getBiggerPrime(int m) { BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random()); return prime.longValue(); } public static long getLowerPrime(long number) { BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random()); return prime.longValue(); } private static int getNumberOfBits(final int number) { return Integer.SIZE - Integer.numberOfLeadingZeros(number); } private static int getNumberOfBits(final long number) { return Long.SIZE - Long.numberOfLeadingZeros(number); } public static int simpleTextSearch(char[] pattern, char[] text) { int patternSize = pattern.length; int textSize = text.length; int i = 0; while ((i + patternSize) <= textSize) { int j = 0; while (text[i + j] == pattern[j]) { j += 1; if (j >= patternSize) return i; } i += 1; } return -1; } public static int RabinKarpMethod(char[] pattern, char[] text) { int patternSize = pattern.length; // m int textSize = text.length; // n long prime = getBiggerPrime(patternSize); long r = 1; for (int i = 0; i < patternSize - 1; i++) { r *= 2; r = r % prime; } long[] t = new long[textSize]; t[0] = 0; long pfinger = 0; for (int j = 0; j < patternSize; j++) { t[0] = (2 * t[0] + text[j]) % prime; pfinger = (2 * pfinger + pattern[j]) % prime; } int i = 0; boolean passed = false; int diff = textSize - patternSize; for (i = 0; i <= diff; i++) { if (t[i] == pfinger) { passed = true; for (int k = 0; k < patternSize; k++) { if (text[i + k] != pattern[k]) { passed = false; break; } } if (passed) { return i; } } if (i < diff) { long value = 2 * (t[i] - r * text[i]) + text[i + patternSize]; t[i + 1] = ((value % prime) + prime) % prime; } } return -1; } public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) { int patternSize = pattern.length; // m int textSize = text.length; // n int i = 0, j = 0; int[] shift = KnuthMorrisPrattShift(pattern); while ((i + patternSize) <= textSize) { while (text[i + j] == pattern[j]) { j += 1; if (j >= patternSize) return i; } if (j > 0) { i += shift[j - 1]; j = Math.max(j - shift[j - 1], 0); } else { i++; j = 0; } } return -1; } public static int[] KnuthMorrisPrattShift(char[] pattern) { int patternSize = pattern.length; int[] shift = new int[patternSize]; shift[0] = 1; int i = 1, j = 0; while ((i + j) < patternSize) { if (pattern[i + j] == pattern[j]) { shift[i + j] = i; j++; } else { if (j == 0) shift[i] = i + 1; if (j > 0) { i = i + shift[j - 1]; j = Math.max(j - shift[j - 1], 0); } else { i = i + 1; j = 0; } } } return shift; } public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) { int patternSize = pattern.length; int textSize = text.length; int i = 0, j = 0; while ((i + patternSize) <= textSize) { j = patternSize - 1; while (text[i + j] == pattern[j]) { j--; if (j < 0) return i; } i++; } return -1; } public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) { int shift[] = new int[256]; for (int k = 0; k < 256; k++) { shift[k] = pattern.length; } for (int k = 0; k < pattern.length - 1; k++) { shift[pattern[k]] = pattern.length - 1 - k; } int i = 0, j = 0; while ((i + pattern.length) <= text.length) { j = pattern.length - 1; while (text[i + j] == pattern[j]) { j -= 1; if (j < 0) return i; } i = i + shift[text[i + pattern.length - 1]]; } return -1; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearch.java
algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearch.java
package com.baeldung.algorithms.interpolationsearch; public class InterpolationSearch { public static int interpolationSearch(int[] data, int item) { int highEnd = (data.length - 1); int lowEnd = 0; while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) { int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]); if (highEnd == lowEnd) { if (data[lowEnd] == item) { return lowEnd; } else { return -1; } } if (data[probe] == item) { return probe; } if (data[probe] < item) { lowEnd = probe + 1; } else { highEnd = probe - 1; } } return -1; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java
package com.baeldung.algorithms.kruskal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraph; import com.google.common.graph.ValueGraphBuilder; import com.baeldung.algorithms.kruskal.Kruskal; class KruskalUnitTest { private MutableValueGraph<Integer, Double> graph; @BeforeEach public void setup() { graph = ValueGraphBuilder.undirected().build(); graph.putEdgeValue(0, 1, 8.0); graph.putEdgeValue(0, 2, 5.0); graph.putEdgeValue(1, 2, 9.0); graph.putEdgeValue(1, 3, 11.0); graph.putEdgeValue(2, 3, 15.0); graph.putEdgeValue(2, 4, 10.0); graph.putEdgeValue(3, 4, 7.0); } @Test void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() { final Kruskal kruskal = new Kruskal(); ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph); assertTrue(spanningTree.hasEdgeConnecting(0, 1)); assertTrue(spanningTree.hasEdgeConnecting(0, 2)); assertTrue(spanningTree.hasEdgeConnecting(2, 4)); assertTrue(spanningTree.hasEdgeConnecting(3, 4)); assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1)); assertEquals(graph.edgeValue(0, 2), spanningTree.edgeValue(0, 2)); assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4)); assertEquals(graph.edgeValue(3, 4), spanningTree.edgeValue(3, 4)); assertFalse(spanningTree.hasEdgeConnecting(1, 2)); assertFalse(spanningTree.hasEdgeConnecting(1, 3)); assertFalse(spanningTree.hasEdgeConnecting(2, 3)); } @Test void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() { final Kruskal kruskal = new Kruskal(); ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph); assertTrue(spanningTree.hasEdgeConnecting(0, 1)); assertTrue(spanningTree.hasEdgeConnecting(1, 3)); assertTrue(spanningTree.hasEdgeConnecting(2, 3)); assertTrue(spanningTree.hasEdgeConnecting(2, 4)); assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1)); assertEquals(graph.edgeValue(1, 3), spanningTree.edgeValue(1, 3)); assertEquals(graph.edgeValue(2, 3), spanningTree.edgeValue(2, 3)); assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4)); assertFalse(spanningTree.hasEdgeConnecting(0, 2)); assertFalse(spanningTree.hasEdgeConnecting(1, 2)); assertFalse(spanningTree.hasEdgeConnecting(3, 4)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java
package com.baeldung.algorithms.boruvka; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraphBuilder; class BoruvkaUnitTest { private MutableValueGraph<Integer, Integer> graph; @BeforeEach public void setup() { graph = ValueGraphBuilder.undirected() .build(); graph.putEdgeValue(0, 1, 8); graph.putEdgeValue(0, 2, 5); graph.putEdgeValue(1, 2, 9); graph.putEdgeValue(1, 3, 11); graph.putEdgeValue(2, 3, 15); graph.putEdgeValue(2, 4, 10); graph.putEdgeValue(3, 4, 7); } @Test void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { BoruvkaMST boruvkaMST = new BoruvkaMST(graph); MutableValueGraph<Integer, Integer> mst = boruvkaMST.getMST(); assertEquals(30, boruvkaMST.getTotalWeight()); assertEquals(4, mst.edges().size()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; class LinkedListReversalUnitTest { @Test void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() { ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i <= 5; i++) { assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); } LinkedListReversal reversal = new LinkedListReversal(); node = reversal.reverseList(head); for (int i = 5; i >= 1; i--) { assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); } } @Test void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() { ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i <= 5; i++) { assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); } LinkedListReversal reversal = new LinkedListReversal(); node = reversal.reverseListRecursive(head); for (int i = 5; i >= 1; i--) { assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); } } private ListNode constructLinkedList() { ListNode head = null; ListNode tail = null; for (int i = 1; i <= 5; i++) { ListNode node = new ListNode(i); if (head == null) { head = node; } else { tail.setNext(node); } tail = node; } return head; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java
package com.baeldung.algorithms.minheapmerge; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; class MinHeapUnitTest { private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } }; private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 }; @Test void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { int[] resultArray = MinHeap.merge(inputArray); assertThat(resultArray.length, is(equalTo(10))); assertThat(resultArray, is(equalTo(expectedArray))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/caesarcipher/CaesarCipherUnitTest.java
package com.baeldung.algorithms.caesarcipher; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class CaesarCipherUnitTest { private static final String SENTENCE = "he told me i could never teach a llama to drive"; private static final String SENTENCE_SHIFTED_THREE = "kh wrog ph l frxog qhyhu whdfk d oodpd wr gulyh"; private static final String SENTENCE_SHIFTED_TEN = "ro dyvn wo s myevn xofob dokmr k vvkwk dy nbsfo"; private CaesarCipher algorithm = new CaesarCipher(); @Test void givenSentenceAndShiftThree_whenCipher_thenCipheredMessageWithoutOverflow() { String cipheredSentence = algorithm.cipher(SENTENCE, 3); assertThat(cipheredSentence) .isEqualTo(SENTENCE_SHIFTED_THREE); } @Test void givenSentenceAndShiftTen_whenCipher_thenCipheredMessageWithOverflow() { String cipheredSentence = algorithm.cipher(SENTENCE, 10); assertThat(cipheredSentence) .isEqualTo(SENTENCE_SHIFTED_TEN); } @Test void givenSentenceAndShiftThirtySix_whenCipher_thenCipheredLikeTenMessageWithOverflow() { String cipheredSentence = algorithm.cipher(SENTENCE, 36); assertThat(cipheredSentence) .isEqualTo(SENTENCE_SHIFTED_TEN); } @Test void givenSentenceShiftedThreeAndShiftThree_whenDecipher_thenOriginalSentenceWithoutOverflow() { String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_THREE, 3); assertThat(decipheredSentence) .isEqualTo(SENTENCE); } @Test void givenSentenceShiftedTenAndShiftTen_whenDecipher_thenOriginalSentenceWithOverflow() { String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_TEN, 10); assertThat(decipheredSentence) .isEqualTo(SENTENCE); } @Test void givenSentenceShiftedTenAndShiftThirtySix_whenDecipher_thenOriginalSentenceWithOverflow() { String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_TEN, 36); assertThat(decipheredSentence) .isEqualTo(SENTENCE); } @Test void givenSentenceShiftedThree_whenBreakCipher_thenOriginalSentence() { int offset = algorithm.breakCipher(SENTENCE_SHIFTED_THREE); assertThat(offset) .isEqualTo(3); assertThat(algorithm.decipher(SENTENCE_SHIFTED_THREE, offset)) .isEqualTo(SENTENCE); } @Test void givenSentenceShiftedTen_whenBreakCipher_thenOriginalSentence() { int offset = algorithm.breakCipher(SENTENCE_SHIFTED_TEN); assertThat(offset) .isEqualTo(10); assertThat(algorithm.decipher(SENTENCE_SHIFTED_TEN, offset)) .isEqualTo(SENTENCE); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java
package com.baeldung.algorithms.greedy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import java.util.Arrays; class GreedyAlgorithmUnitTest { private SocialConnector prepareNetwork() { SocialConnector sc = new SocialConnector(); SocialUser root = new SocialUser("root"); SocialUser child1 = new SocialUser("child1"); SocialUser child2 = new SocialUser("child2"); SocialUser child3 = new SocialUser("child3"); SocialUser child21 = new SocialUser("child21"); SocialUser child211 = new SocialUser("child211"); SocialUser child2111 = new SocialUser("child2111"); SocialUser child31 = new SocialUser("child31"); SocialUser child311 = new SocialUser("child311"); SocialUser child3111 = new SocialUser("child3111"); child211.addFollowers(Arrays.asList(new SocialUser[]{child2111})); child311.addFollowers(Arrays.asList(new SocialUser[]{child3111})); child21.addFollowers(Arrays.asList(new SocialUser[]{child211})); child31.addFollowers(Arrays.asList(new SocialUser[]{child311, new SocialUser("child312"), new SocialUser("child313"), new SocialUser("child314")})); child1.addFollowers(Arrays.asList(new SocialUser[]{new SocialUser("child11"), new SocialUser("child12")})); child2.addFollowers(Arrays.asList(new SocialUser[]{child21, new SocialUser("child22"), new SocialUser("child23")})); child3.addFollowers(Arrays.asList(new SocialUser[]{child31})); root.addFollowers(Arrays.asList(new SocialUser[]{child1, child2, child3})); sc.setUsers(Arrays.asList(new SocialUser[]{root, child1, child2, child3, child21, child31, child311, child211})); return sc; } @Test void greedyAlgorithmTest() { GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); assertEquals(ga.findMostFollowersPath("root"), 5); } @Test void nongreedyAlgorithmTest() { NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); assertThrows(IllegalStateException.class, () -> { nga.findMostFollowersPath("root"); }); } @Test void nongreedyAlgorithmUnboundedTest() { SocialConnector sc = prepareNetwork(); sc.switchCounter(); NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); assertEquals(nga.findMostFollowersPath("root"), 6); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java
package com.baeldung.algorithms.topkelements; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; import org.junit.jupiter.api.Test; class TopKElementsFinderUnitTest { private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder(); private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder(); private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder(); private final int k = 4; private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12); private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12); private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12); private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12); @Test void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() { assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); } @Test void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java
package com.baeldung.algorithms.gradientdescent; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.Function; import org.junit.jupiter.api.Test; class GradientDescentUnitTest { @Test void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { Function<Double, Double> df = x -> StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x; GradientDescent gd = new GradientDescent(); double res = gd.findLocalMinimum(df, 1); assertTrue(res > 1.78); assertTrue(res < 1.84); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java
package com.baeldung.algorithms.balancedbrackets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class BalancedBracketsUsingStringUnitTest { private BalancedBracketsUsingString balancedBracketsUsingString; @BeforeEach public void setup() { balancedBracketsUsingString = new BalancedBracketsUsingString(); } @Test void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced(null); assertThat(result).isFalse(); } @Test void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced(""); assertThat(result).isTrue(); } @Test void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("abc[](){}"); assertThat(result).isFalse(); } @Test void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}"); assertThat(result).isFalse(); } @Test void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}"); assertThat(result).isFalse(); } @Test void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{[(])}"); assertThat(result).isFalse(); } @Test void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{}("); assertThat(result).isFalse(); } @Test void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); assertThat(result).isTrue(); } @Test void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}"); assertThat(result).isTrue(); } @Test void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{{([])}}"); assertThat(result).isTrue(); } @Test void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}"); assertThat(result).isFalse(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java
algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java
package com.baeldung.algorithms.balancedbrackets; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class BalancedBracketsUsingDequeUnitTest { private BalancedBracketsUsingDeque balancedBracketsUsingDeque; @BeforeEach public void setup() { balancedBracketsUsingDeque = new BalancedBracketsUsingDeque(); } @Test void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced(null); assertThat(result).isFalse(); } @Test void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced(""); assertThat(result).isTrue(); } @Test void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}"); assertThat(result).isFalse(); } @Test void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}"); assertThat(result).isFalse(); } @Test void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}"); assertThat(result).isFalse(); } @Test void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}"); assertThat(result).isFalse(); } @Test void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{}("); assertThat(result).isFalse(); } @Test void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); assertThat(result).isTrue(); } @Test void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}"); assertThat(result).isTrue(); } @Test void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}"); assertThat(result).isTrue(); } @Test void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}"); assertThat(result).isFalse(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/CycleDetector.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/CycleDetector.java
package com.baeldung.algorithms.kruskal; import java.util.ArrayList; import java.util.List; public class CycleDetector { List<DisjointSetInfo> nodes; public CycleDetector(int totalNodes) { initDisjointSets(totalNodes); } public boolean detectCycle(Integer u, Integer v) { Integer rootU = pathCompressionFind(u); Integer rootV = pathCompressionFind(v); if (rootU.equals(rootV)) { return true; } unionByRank(rootU, rootV); return false; } private void initDisjointSets(int totalNodes) { nodes = new ArrayList<>(totalNodes); for (int i = 0; i < totalNodes; i++) { nodes.add(new DisjointSetInfo(i)); } } private Integer find(Integer node) { Integer parent = nodes.get(node).getParentNode(); if (parent.equals(node)) { return node; } else { return find(parent); } } private Integer pathCompressionFind(Integer node) { DisjointSetInfo setInfo = nodes.get(node); Integer parent = setInfo.getParentNode(); if (parent.equals(node)) { return node; } else { Integer parentNode = find(parent); setInfo.setParentNode(parentNode); return parentNode; } } private void union(Integer rootU, Integer rootV) { DisjointSetInfo setInfoU = nodes.get(rootU); setInfoU.setParentNode(rootV); } private void unionByRank(int rootU, int rootV) { DisjointSetInfo setInfoU = nodes.get(rootU); DisjointSetInfo setInfoV = nodes.get(rootV); int rankU = setInfoU.getRank(); int rankV = setInfoV.getRank(); if (rankU < rankV) { setInfoU.setParentNode(rootV); } else { setInfoV.setParentNode(rootU); if (rankU == rankV) { setInfoU.setRank(rankU + 1); } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/DisjointSetInfo.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/DisjointSetInfo.java
package com.baeldung.algorithms.kruskal; public class DisjointSetInfo { private Integer parentNode; private int rank; DisjointSetInfo(Integer nodeNumber) { setParentNode(nodeNumber); setRank(1); } public Integer getParentNode() { return parentNode; } public void setParentNode(Integer parentNode) { this.parentNode = parentNode; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/Kruskal.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/kruskal/Kruskal.java
package com.baeldung.algorithms.kruskal; import com.google.common.graph.EndpointPair; import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraph; import com.google.common.graph.ValueGraphBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; public class Kruskal { public ValueGraph<Integer, Double> minSpanningTree(ValueGraph<Integer, Double> graph) { return spanningTree(graph, true); } public ValueGraph<Integer, Double> maxSpanningTree(ValueGraph<Integer, Double> graph) { return spanningTree(graph, false); } private ValueGraph<Integer, Double> spanningTree(ValueGraph<Integer, Double> graph, boolean minSpanningTree) { Set<EndpointPair<Integer>> edges = graph.edges(); List<EndpointPair<Integer>> edgeList = new ArrayList<>(edges); if (minSpanningTree) { edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get())); } else { edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get()))); } int totalNodes = graph.nodes().size(); CycleDetector cycleDetector = new CycleDetector(totalNodes); int edgeCount = 0; MutableValueGraph<Integer, Double> spanningTree = ValueGraphBuilder.undirected().build(); for (EndpointPair<Integer> edge : edgeList) { if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) { continue; } spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get()); edgeCount++; if (edgeCount == totalNodes - 1) { break; } } return spanningTree; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Board.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Board.java
package com.baeldung.algorithms.play2048; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Board { private static final Logger LOG = LoggerFactory.getLogger(Board.class); private final int[][] board; private final int score; public Board(int size) { assert(size > 0); this.board = new int[size][]; this.score = 0; for (int x = 0; x < size; ++x) { this.board[x] = new int[size]; for (int y = 0; y < size; ++y) { board[x][y] = 0; } } } private Board(int[][] board, int score) { this.score = score; this.board = new int[board.length][]; for (int x = 0; x < board.length; ++x) { this.board[x] = Arrays.copyOf(board[x], board[x].length); } } public int getSize() { return board.length; } public int getScore() { return score; } public int getCell(Cell cell) { int x = cell.getX(); int y = cell.getY(); assert(x >= 0 && x < board.length); assert(y >= 0 && y < board.length); return board[x][y]; } public boolean isEmpty(Cell cell) { return getCell(cell) == 0; } public List<Cell> emptyCells() { List<Cell> result = new ArrayList<>(); for (int x = 0; x < board.length; ++x) { for (int y = 0; y < board[x].length; ++y) { Cell cell = new Cell(x, y); if (isEmpty(cell)) { result.add(cell); } } } return result; } public Board placeTile(Cell cell, int number) { if (!isEmpty(cell)) { throw new IllegalArgumentException("That cell is not empty"); } Board result = new Board(this.board, this.score); result.board[cell.getX()][cell.getY()] = number; return result; } public Board move(Move move) { // Clone the board int[][] tiles = new int[this.board.length][]; for (int x = 0; x < this.board.length; ++x) { tiles[x] = Arrays.copyOf(this.board[x], this.board[x].length); } LOG.debug("Before move: {}", Arrays.deepToString(tiles)); // If we're doing an Left/Right move then transpose the board to make it a Up/Down move if (move == Move.LEFT || move == Move.RIGHT) { tiles = transpose(tiles); LOG.debug("After transpose: {}", Arrays.deepToString(tiles)); } // If we're doing a Right/Down move then reverse the board. // With the above we're now always doing an Up move if (move == Move.DOWN || move == Move.RIGHT) { tiles = reverse(tiles); LOG.debug("After reverse: {}", Arrays.deepToString(tiles)); } LOG.debug("Ready to move: {}", Arrays.deepToString(tiles)); // Shift everything up int[][] result = new int[tiles.length][]; int newScore = 0; for (int x = 0; x < tiles.length; ++x) { LinkedList<Integer> thisRow = new LinkedList<>(); for (int y = 0; y < tiles[0].length; ++y) { if (tiles[x][y] > 0) { thisRow.add(tiles[x][y]); } } LOG.debug("Unmerged row: {}", thisRow); LinkedList<Integer> newRow = new LinkedList<>(); while (thisRow.size() >= 2) { int first = thisRow.pop(); int second = thisRow.peek(); LOG.debug("Looking at numbers {} and {}", first, second); if (second == first) { LOG.debug("Numbers match, combining"); int newNumber = first * 2; newRow.add(newNumber); newScore += newNumber; thisRow.pop(); } else { LOG.debug("Numbers don't match"); newRow.add(first); } } newRow.addAll(thisRow); LOG.debug("Merged row: {}", newRow); result[x] = new int[tiles[0].length]; for (int y = 0; y < tiles[0].length; ++y) { if (newRow.isEmpty()) { result[x][y] = 0; } else { result[x][y] = newRow.pop(); } } } LOG.debug("After moves: {}", Arrays.deepToString(result)); // Un-reverse the board if (move == Move.DOWN || move == Move.RIGHT) { result = reverse(result); LOG.debug("After reverse: {}", Arrays.deepToString(result)); } // Un-transpose the board if (move == Move.LEFT || move == Move.RIGHT) { result = transpose(result); LOG.debug("After transpose: {}", Arrays.deepToString(result)); } return new Board(result, this.score + newScore); } private static int[][] transpose(int[][] input) { int[][] result = new int[input.length][]; for (int x = 0; x < input.length; ++x) { result[x] = new int[input[0].length]; for (int y = 0; y < input[0].length; ++y) { result[x][y] = input[y][x]; } } return result; } private static int[][] reverse(int[][] input) { int[][] result = new int[input.length][]; for (int x = 0; x < input.length; ++x) { result[x] = new int[input[0].length]; for (int y = 0; y < input[0].length; ++y) { result[x][y] = input[x][input.length - y - 1]; } } return result; } @Override public String toString() { return Arrays.deepToString(board); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Board board1 = (Board) o; return Arrays.deepEquals(board, board1.board); } @Override public int hashCode() { return Arrays.deepHashCode(board); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Move.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Move.java
package com.baeldung.algorithms.play2048; public enum Move { UP, DOWN, LEFT, RIGHT }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Cell.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Cell.java
package com.baeldung.algorithms.play2048; import java.util.StringJoiner; public class Cell { private int x; private int y; public Cell(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public String toString() { return new StringJoiner(", ", Cell.class.getSimpleName() + "[", "]").add("x=" + x).add("y=" + y).toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Play2048.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Play2048.java
package com.baeldung.algorithms.play2048; public class Play2048 { private static final int SIZE = 4; private static final int INITIAL_NUMBERS = 2; public static void main(String[] args) { // The board and players Board board = new Board(SIZE); Computer computer = new Computer(); Human human = new Human(); // The computer has two moves first System.out.println("Setup"); System.out.println("====="); for (int i = 0; i < INITIAL_NUMBERS; ++i) { board = computer.makeMove(board); } printBoard(board); do { board = human.makeMove(board); System.out.println("Human move"); System.out.println("=========="); printBoard(board); board = computer.makeMove(board); System.out.println("Computer move"); System.out.println("============="); printBoard(board); } while (!board.emptyCells().isEmpty()); System.out.println("Final Score: " + board.getScore()); } private static void printBoard(Board board) { StringBuilder topLines = new StringBuilder(); StringBuilder midLines = new StringBuilder(); for (int x = 0; x < board.getSize(); ++x) { topLines.append("+--------"); midLines.append("| "); } topLines.append("+"); midLines.append("|"); for (int y = 0; y < board.getSize(); ++y) { System.out.println(topLines); System.out.println(midLines); for (int x = 0; x < board.getSize(); ++x) { Cell cell = new Cell(x, y); System.out.print("|"); if (board.isEmpty(cell)) { System.out.print(" "); } else { StringBuilder output = new StringBuilder(Integer.toString(board.getCell(cell))); while (output.length() < 8) { output.append(" "); if (output.length() < 8) { output.insert(0, " "); } } System.out.print(output); } } System.out.println("|"); System.out.println(midLines); } System.out.println(topLines); System.out.println("Score: " + board.getScore()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Human.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Human.java
package com.baeldung.algorithms.play2048; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.math3.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Human { private static final Logger LOG = LoggerFactory.getLogger(Human.class); public Board makeMove(Board input) { // For each move in MOVE // Generate board from move // Generate Score for Board // Return board with the best score // // Generate Score // If Depth Limit // Return Final Score // Total Score = 0 // For every empty square in new board // Generate board with "2" in square // Calculate Score // Total Score += (Score * 0.9) // Generate board with "4" in square // Calculate Score // Total Score += (Score * 0.1) // // Calculate Score // For each move in MOVE // Generate board from move // Generate score for board // Return the best generated score return Arrays.stream(Move.values()) .parallel() .map(input::move) .filter(board -> !board.equals(input)) .max(Comparator.comparingInt(board -> generateScore(board, 0))) .orElse(input); } private int generateScore(Board board, int depth) { if (depth >= 3) { int finalScore = calculateFinalScore(board); LOG.debug("Final score for board {}: {}", board,finalScore); return finalScore; } return board.emptyCells().stream() .parallel() .flatMap(cell -> Stream.of(new Pair<>(cell, 2), new Pair<>(cell, 4))) .mapToInt(move -> { LOG.debug("Simulating move {} at depth {}", move, depth); Board newBoard = board.placeTile(move.getFirst(), move.getSecond()); int boardScore = calculateScore(newBoard, depth + 1); int calculatedScore = (int) (boardScore * (move.getSecond() == 2 ? 0.9 : 0.1)); LOG.debug("Calculated score for board {} and move {} at depth {}: {}", newBoard, move, depth, calculatedScore); return calculatedScore; }) .sum(); } private int calculateScore(Board board, int depth) { return Arrays.stream(Move.values()) .parallel() .map(board::move) .filter(moved -> !moved.equals(board)) .mapToInt(newBoard -> generateScore(newBoard, depth)) .max() .orElse(0); } private int calculateFinalScore(Board board) { List<List<Integer>> rowsToScore = new ArrayList<>(); for (int i = 0; i < board.getSize(); ++i) { List<Integer> row = new ArrayList<>(); List<Integer> col = new ArrayList<>(); for (int j = 0; j < board.getSize(); ++j) { row.add(board.getCell(new Cell(i, j))); col.add(board.getCell(new Cell(j, i))); } rowsToScore.add(row); rowsToScore.add(col); } return rowsToScore.stream() .parallel() .mapToInt(row -> { List<Integer> preMerged = row.stream() .filter(value -> value != 0) .collect(Collectors.toList()); int numMerges = 0; int monotonicityLeft = 0; int monotonicityRight = 0; for (int i = 0; i < preMerged.size() - 1; ++i) { Integer first = preMerged.get(i); Integer second = preMerged.get(i + 1); if (first.equals(second)) { ++numMerges; } else if (first > second) { monotonicityLeft += first - second; } else { monotonicityRight += second - first; } } int score = 1000; score += 250 * row.stream().filter(value -> value == 0).count(); score += 750 * numMerges; score -= 10 * row.stream().mapToInt(value -> value).sum(); score -= 50 * Math.min(monotonicityLeft, monotonicityRight); return score; }) .sum(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Computer.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/play2048/Computer.java
package com.baeldung.algorithms.play2048; import java.security.SecureRandom; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Computer { private static final Logger LOG = LoggerFactory.getLogger(Computer.class); private final SecureRandom rng = new SecureRandom(); public Board makeMove(Board input) { List<Cell> emptyCells = input.emptyCells(); LOG.info("Number of empty cells: {}", emptyCells.size()); double numberToPlace = rng.nextDouble(); LOG.info("New number probability: {}", numberToPlace); int indexToPlace = rng.nextInt(emptyCells.size()); Cell cellToPlace = emptyCells.get(indexToPlace); LOG.info("Placing number into empty cell: {}", cellToPlace); return input.placeTile(cellToPlace, numberToPlace >= 0.9 ? 4 : 2); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java
package com.baeldung.algorithms.boruvka; public class UnionFind { private int[] parents; private int[] ranks; public UnionFind(int n) { parents = new int[n]; ranks = new int[n]; for (int i = 0; i < n; i++) { parents[i] = i; ranks[i] = 0; } } public int find(int u) { while (u != parents[u]) { u = parents[u]; } return u; } public void union(int u, int v) { int uParent = find(u); int vParent = find(v); if (uParent == vParent) { return; } if (ranks[uParent] < ranks[vParent]) { parents[uParent] = vParent; } else if (ranks[uParent] > ranks[vParent]) { parents[vParent] = uParent; } else { parents[vParent] = uParent; ranks[uParent]++; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java
package com.baeldung.algorithms.boruvka; import com.google.common.graph.EndpointPair; import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraphBuilder; public class BoruvkaMST { private static MutableValueGraph<Integer, Integer> mst = ValueGraphBuilder.undirected() .build(); private static int totalWeight; public BoruvkaMST(MutableValueGraph<Integer, Integer> graph) { int size = graph.nodes().size(); UnionFind uf = new UnionFind(size); // repeat at most log N times or until we have N-1 edges for (int t = 1; t < size && mst.edges().size() < size - 1; t = t + t) { EndpointPair<Integer>[] closestEdgeArray = new EndpointPair[size]; // foreach tree in graph, find closest edge for (EndpointPair<Integer> edge : graph.edges()) { int u = edge.nodeU(); int v = edge.nodeV(); int uParent = uf.find(u); int vParent = uf.find(v); if (uParent == vParent) { continue; // same tree } int weight = graph.edgeValueOrDefault(u, v, 0); if (closestEdgeArray[uParent] == null) { closestEdgeArray[uParent] = edge; } if (closestEdgeArray[vParent] == null) { closestEdgeArray[vParent] = edge; } int uParentWeight = graph.edgeValueOrDefault(closestEdgeArray[uParent].nodeU(), closestEdgeArray[uParent].nodeV(), 0); int vParentWeight = graph.edgeValueOrDefault(closestEdgeArray[vParent].nodeU(), closestEdgeArray[vParent].nodeV(), 0); if (weight < uParentWeight) { closestEdgeArray[uParent] = edge; } if (weight < vParentWeight) { closestEdgeArray[vParent] = edge; } } // add newly discovered edges to MST for (int i = 0; i < size; i++) { EndpointPair<Integer> edge = closestEdgeArray[i]; if (edge != null) { int u = edge.nodeU(); int v = edge.nodeV(); int weight = graph.edgeValueOrDefault(u, v, 0); // don't add the same edge twice if (uf.find(u) != uf.find(v)) { mst.putEdgeValue(u, v, weight); totalWeight += weight; uf.union(u, v); } } } } } public MutableValueGraph<Integer, Integer> getMST() { return mst; } public int getTotalWeight() { return totalWeight; } public String toString() { return "MST: " + mst.toString() + " | Total Weight: " + totalWeight; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/linkedlist/LinkedListReversal.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/linkedlist/LinkedListReversal.java
package com.baeldung.algorithms.linkedlist; public class LinkedListReversal { ListNode reverseList(ListNode head) { ListNode previous = null; ListNode current = head; while (current != null) { ListNode nextElement = current.getNext(); current.setNext(previous); previous = current; current = nextElement; } return previous; } ListNode reverseListRecursive(ListNode head) { if (head == null) { return null; } if (head.getNext() == null) { return head; } ListNode node = reverseListRecursive(head.getNext()); head.getNext().setNext(head); head.setNext(null); return node; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/linkedlist/ListNode.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/linkedlist/ListNode.java
package com.baeldung.algorithms.linkedlist; public class ListNode { private int data; private ListNode next; ListNode(int data) { this.data = data; this.next = null; } public int getData() { return data; } public ListNode getNext() { return next; } public void setData(int data) { this.data = data; } public void setNext(ListNode next) { this.next = next; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java
package com.baeldung.algorithms.minheapmerge; public class MinHeap { HeapNode[] heapNodes; public MinHeap(HeapNode heapNodes[]) { this.heapNodes = heapNodes; heapifyFromLastLeafsParent(); } void heapifyFromLastLeafsParent() { int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); while (lastLeafsParentIndex >= 0) { heapify(lastLeafsParentIndex); lastLeafsParentIndex--; } } void heapify(int index) { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { smallestElementIndex = leftNodeIndex; } if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { smallestElementIndex = rightNodeIndex; } if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); } } int getParentNodeIndex(int index) { return (index - 1) / 2; } int getLeftNodeIndex(int index) { return (2 * index + 1); } int getRightNodeIndex(int index) { return (2 * index + 2); } HeapNode getRootNode() { return heapNodes[0]; } void heapifyFromRoot() { heapify(0); } void swap(int i, int j) { HeapNode temp = heapNodes[i]; heapNodes[i] = heapNodes[j]; heapNodes[j] = temp; } static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = 0; for (int i = 0; i < array.length; i++) { HeapNode node = new HeapNode(array[i][0], i); heapNodes[i] = node; resultingArraySize += array[i].length; } MinHeap minHeap = new MinHeap(heapNodes); int[] resultingArray = new int[resultingArraySize]; for (int i = 0; i < resultingArraySize; i++) { HeapNode root = minHeap.getRootNode(); resultingArray[i] = root.element; if (root.nextElementIndex < array[root.arrayIndex].length) { root.element = array[root.arrayIndex][root.nextElementIndex++]; } else { root.element = Integer.MAX_VALUE; } minHeap.heapifyFromRoot(); } return resultingArray; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java
package com.baeldung.algorithms.minheapmerge; public class HeapNode { int element; int arrayIndex; int nextElementIndex = 1; public HeapNode(int element, int arrayIndex) { this.element = element; this.arrayIndex = arrayIndex; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/caesarcipher/CaesarCipher.java
package com.baeldung.algorithms.caesarcipher; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.stream.IntStream; public class CaesarCipher { private final Logger log = LoggerFactory.getLogger(CaesarCipher.class); private static final char LETTER_A = 'a'; private static final char LETTER_Z = 'z'; private static final int ALPHABET_SIZE = LETTER_Z - LETTER_A + 1; private static final double[] ENGLISH_LETTERS_PROBABILITIES = {0.073, 0.009, 0.030, 0.044, 0.130, 0.028, 0.016, 0.035, 0.074, 0.002, 0.003, 0.035, 0.025, 0.078, 0.074, 0.027, 0.003, 0.077, 0.063, 0.093, 0.027, 0.013, 0.016, 0.005, 0.019, 0.001}; public String cipher(String message, int offset) { StringBuilder result = new StringBuilder(); for (char character : message.toCharArray()) { if (character != ' ') { int originalAlphabetPosition = character - LETTER_A; int newAlphabetPosition = (originalAlphabetPosition + offset) % ALPHABET_SIZE; char newCharacter = (char) (LETTER_A + newAlphabetPosition); result.append(newCharacter); } else { result.append(character); } } return result.toString(); } public String decipher(String message, int offset) { return cipher(message, ALPHABET_SIZE - (offset % ALPHABET_SIZE)); } public int breakCipher(String message) { return probableOffset(chiSquares(message)); } private double[] chiSquares(String message) { double[] expectedLettersFrequencies = expectedLettersFrequencies(message.length()); double[] chiSquares = new double[ALPHABET_SIZE]; for (int offset = 0; offset < chiSquares.length; offset++) { String decipheredMessage = decipher(message, offset); long[] lettersFrequencies = observedLettersFrequencies(decipheredMessage); double chiSquare = new ChiSquareTest().chiSquare(expectedLettersFrequencies, lettersFrequencies); chiSquares[offset] = chiSquare; } return chiSquares; } private long[] observedLettersFrequencies(String message) { return IntStream.rangeClosed(LETTER_A, LETTER_Z) .mapToLong(letter -> countLetter((char) letter, message)) .toArray(); } private long countLetter(char letter, String message) { return message.chars() .filter(character -> character == letter) .count(); } private double[] expectedLettersFrequencies(int messageLength) { return Arrays.stream(ENGLISH_LETTERS_PROBABILITIES) .map(probability -> probability * messageLength) .toArray(); } private int probableOffset(double[] chiSquares) { int probableOffset = 0; for (int offset = 0; offset < chiSquares.length; offset++) { log.debug(String.format("Chi-Square for offset %d: %.2f", offset, chiSquares[offset])); if (chiSquares[offset] < chiSquares[probableOffset]) { probableOffset = offset; } } return probableOffset; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java
package com.baeldung.algorithms.greedy; import java.util.List; public class NonGreedyAlgorithm { int currentLevel = 0; final int maxLevel = 3; SocialConnector tc; public NonGreedyAlgorithm(SocialConnector tc, int level) { super(); this.tc = tc; this.currentLevel = level; } public long findMostFollowersPath(String account) { List<SocialUser> followers = tc.getFollowers(account); long total = currentLevel > 0 ? followers.size() : 0; if (currentLevel < maxLevel ) { currentLevel++; long[] count = new long[followers.size()]; int i = 0; for (SocialUser el : followers) { NonGreedyAlgorithm sub = new NonGreedyAlgorithm(tc, currentLevel); count[i] = sub.findMostFollowersPath(el.getUsername()); i++; } long max = 0; for (; i > 0; i--) { if (count[i-1] > max ) max = count[i-1]; } return total + max; } return total; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java
package com.baeldung.algorithms.greedy; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.Setter; public class SocialConnector { private boolean isCounterEnabled = true; private int counter = 4; @Getter @Setter List<SocialUser> users; public SocialConnector() { users = new ArrayList<>(); } public boolean switchCounter() { this.isCounterEnabled = !this.isCounterEnabled; return this.isCounterEnabled; } public List<SocialUser> getFollowers(String account) { if (counter < 0) throw new IllegalStateException ("API limit reached"); else { if(this.isCounterEnabled) counter--; for(SocialUser user : users) { if (user.getUsername().equals(account)) { return user.getFollowers(); } } } return new ArrayList<>(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/FollowersPath.java
package com.baeldung.algorithms.greedy; import java.util.ArrayList; import java.util.List; public class FollowersPath { private List<Follower> accounts; private long count; public FollowersPath() { super(); this.accounts = new ArrayList<>(); } public List<Follower> getAccounts() { return accounts; } public long getCount() { return count; } public void addFollower(String username, long count) { accounts.add(new Follower(username, count)); } public void addCount(long count) { this.count += count; } @Override public String toString() { String details = ""; for(Follower a : accounts) { details+=a.toString() + ", "; } return "Total: " + count + ", \n\r" + " Details: { " + "\n\r" + details + "\n\r" + " }"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/SocialUser.java
package com.baeldung.algorithms.greedy; import java.util.ArrayList; import java.util.List; import lombok.Getter; public class SocialUser { @Getter private String username; @Getter private List<SocialUser> followers; public SocialUser(String username) { super(); this.username = username; this.followers = new ArrayList<>(); } public SocialUser(String username, List<SocialUser> followers) { super(); this.username = username; this.followers = followers; } public long getFollowersCount() { return followers.size(); } public void addFollowers(List<SocialUser> followers) { this.followers.addAll(followers); } @Override public boolean equals(Object obj) { return ((SocialUser) obj).getUsername().equals(username); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/Follower.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/Follower.java
package com.baeldung.algorithms.greedy; import lombok.Getter; public class Follower { @Getter String username; @Getter long count; public Follower(String username, long count) { super(); this.username = username; this.count = count; } @Override public String toString() { return "User: " + username + ", Followers: " + count + "\n\r" ; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java
package com.baeldung.algorithms.greedy; import java.util.List; public class GreedyAlgorithm { int currentLevel = 0; final int maxLevel = 3; SocialConnector sc; FollowersPath fp; public GreedyAlgorithm(SocialConnector sc) { super(); this.sc = sc; this.fp = new FollowersPath(); } public long findMostFollowersPath(String account) { long max = 0; SocialUser toFollow = null; List<SocialUser> followers = sc.getFollowers(account); for (SocialUser el : followers) { long followersCount = el.getFollowersCount(); if (followersCount > max) { toFollow = el; max = followersCount; } } if (currentLevel < maxLevel - 1) { currentLevel++; max += findMostFollowersPath(toFollow.getUsername()); return max; } else { return max; } } public FollowersPath getFollowers() { return fp; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TreeSetTopKElementsFinder.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TreeSetTopKElementsFinder.java
package com.baeldung.algorithms.topkelements; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> { public List<Integer> findTopK(List<Integer> input, int k) { Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder()); sortedSet.addAll(input); return sortedSet.stream().limit(k).collect(Collectors.toList()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TopKElementsFinder.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/TopKElementsFinder.java
package com.baeldung.algorithms.topkelements; import java.util.List; public interface TopKElementsFinder<T extends Comparable<T>> { List<T> findTopK(List<T> input, int k); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/BruteForceTopKElementsFinder.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/BruteForceTopKElementsFinder.java
package com.baeldung.algorithms.topkelements; import java.util.ArrayList; import java.util.List; public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> { public List<Integer> findTopK(List<Integer> input, int k) { List<Integer> array = new ArrayList<>(input); List<Integer> topKList = new ArrayList<>(); for (int i = 0; i < k; i++) { int maxIndex = 0; for (int j = 1; j < array.size(); j++) { if (array.get(j) > array.get(maxIndex)) { maxIndex = j; } } topKList.add(array.remove(maxIndex)); } return topKList; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/MaxHeapTopKElementsFinder.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/topkelements/MaxHeapTopKElementsFinder.java
package com.baeldung.algorithms.topkelements; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PriorityQueue; public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> { public List<Integer> findTopK(List<Integer> input, int k) { PriorityQueue<Integer> maxHeap = new PriorityQueue<>(); input.forEach(number -> { maxHeap.add(number); if (maxHeap.size() > k) { maxHeap.poll(); } }); List<Integer> topKList = new ArrayList<>(maxHeap); Collections.reverse(topKList); return topKList; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java
algorithms-modules/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java
package com.baeldung.algorithms.gradientdescent; import java.util.function.Function; public class GradientDescent { private final double precision = 0.000001; public double findLocalMinimum(Function<Double, Double> f, double initialX) { double stepCoefficient = 0.1; double previousStep = 1.0; double currentX = initialX; double previousX = initialX; double previousY = f.apply(previousX); int iter = 100; currentX += stepCoefficient * previousY; while (previousStep > precision && iter > 0) { iter--; double currentY = f.apply(currentX); if (currentY > previousY) { stepCoefficient = -stepCoefficient / 2; } previousX = currentX; currentX += stepCoefficient * previousY; previousY = currentY; previousStep = StrictMath.abs(currentX - previousX); } return currentX; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false