JAVA-12097: renamed algorithms-module to algorithms-modules

This commit is contained in:
sampadawagde
2022-05-20 22:07:32 +05:30
parent 3b028d36d0
commit a2afe2eed0
324 changed files with 31 additions and 20 deletions

View File

@@ -0,0 +1,19 @@
## Algorithms - Miscellaneous
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
### Relevant articles:
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>algorithms-miscellaneous-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-5</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>
<tradukisto.version>1.0.1</tradukisto.version>
<commons-codec.version>1.11</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
</project>

View File

@@ -0,0 +1,33 @@
package com.baeldung.algorithms.balancedbinarytree;
public class BalancedBinaryTree {
public static boolean isBalanced(Tree tree) {
return isBalancedRecursive(tree, -1).isBalanced;
}
private static Result isBalancedRecursive(Tree tree, int depth) {
if (tree == null) {
return new Result(true, -1);
}
Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1);
Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1);
boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1;
boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced;
int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1;
return new Result(isBalanced && subtreesAreBalanced, height);
}
private static final class Result {
private final boolean isBalanced;
private final int height;
private Result(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.algorithms.balancedbinarytree;
public class Tree {
private final int value;
private final Tree left;
private final Tree right;
public Tree(int value, Tree left, Tree right) {
this.value = value;
this.left = left;
this.right = right;
}
public int value() {
return value;
}
public Tree left() {
return left;
}
public Tree right() {
return right;
}
@Override
public String toString() {
return String.format("[%s, %s, %s]",
value,
left == null ? "null" : left.toString(),
right == null ? "null" : right.toString()
);
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.algorithms.binarygap;
public class BinaryGap {
static int calculateBinaryGap(int n) {
return calculateBinaryGap(n >>> Integer.numberOfTrailingZeros(n), 0, 0);
}
static int calculateBinaryGap(int n, int current, int maximum) {
if (n == 0) {
return maximum;
} else if ((n & 1) == 0) {
return calculateBinaryGap(n >>> 1, current + 1, maximum);
} else {
return calculateBinaryGap(n >>> 1, 0, Math.max(maximum, current));
}
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.algorithms.combinatorics;
import java.util.*;
import static java.util.Collections.swap;
public class Combinatorics {
public static List<List<Integer>> permutations(List<Integer> sequence) {
List<List<Integer>> results = new ArrayList<>();
permutationsInternal(sequence, results, 0);
return results;
}
private static void permutationsInternal(List<Integer> sequence, List<List<Integer>> results, int index) {
if (index == sequence.size() - 1) {
results.add(new ArrayList<>(sequence));
}
for (int i = index; i < sequence.size(); i++) {
swap(sequence, i, index);
permutationsInternal(sequence, results, index + 1);
swap(sequence, i, index);
}
}
public static List<List<Integer>> combinations(List<Integer> inputSet, int k) {
List<List<Integer>> results = new ArrayList<>();
combinationsInternal(inputSet, k, results, new ArrayList<>(), 0);
return results;
}
private static void combinationsInternal(
List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) {
int leftToAccumulate = k - accumulator.size();
int possibleToAcculumate = inputSet.size() - index;
if (accumulator.size() == k) {
results.add(new ArrayList<>(accumulator));
} else if (leftToAccumulate <= possibleToAcculumate) {
combinationsInternal(inputSet, k, results, accumulator, index + 1);
accumulator.add(inputSet.get(index));
combinationsInternal(inputSet, k, results, accumulator, index + 1);
accumulator.remove(accumulator.size() - 1);
}
}
public static List<List<Character>> powerSet(List<Character> sequence) {
List<List<Character>> results = new ArrayList<>();
powerSetInternal(sequence, results, new ArrayList<>(), 0);
return results;
}
private static void powerSetInternal(
List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) {
if (index == set.size()) {
powerSet.add(new ArrayList<>(accumulator));
} else {
accumulator.add(set.get(index));
powerSetInternal(set, powerSet, accumulator, index + 1);
accumulator.remove(accumulator.size() - 1);
powerSetInternal(set, powerSet, accumulator, index + 1);
}
}
}

View File

@@ -0,0 +1,110 @@
package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
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) throws DecoderException {
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());
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.algorithms.integerstreammedian;
import java.util.PriorityQueue;
import java.util.Queue;
import static java.util.Comparator.reverseOrder;
public class MedianOfIntegerStream {
private Queue<Integer> minHeap, maxHeap;
MedianOfIntegerStream() {
minHeap = new PriorityQueue<>();
maxHeap = new PriorityQueue<>(reverseOrder());
}
void add(int num) {
if (!minHeap.isEmpty() && num < minHeap.peek()) {
maxHeap.offer(num);
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
}
} else {
minHeap.offer(num);
if (minHeap.size() > maxHeap.size() + 1) {
maxHeap.offer(minHeap.poll());
}
}
}
double getMedian() {
int median;
if (minHeap.size() < maxHeap.size()) {
median = maxHeap.peek();
} else if (minHeap.size() > maxHeap.size()) {
median = minHeap.peek();
} else {
median = (minHeap.peek() + maxHeap.peek()) / 2;
}
return median;
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.algorithms.integerstreammedian;
import java.util.PriorityQueue;
import java.util.Queue;
import static java.util.Comparator.reverseOrder;
public class MedianOfIntegerStream2 {
private Queue<Integer> minHeap, maxHeap;
MedianOfIntegerStream2() {
minHeap = new PriorityQueue<>();
maxHeap = new PriorityQueue<>(reverseOrder());
}
void add(int num) {
if (minHeap.size() == maxHeap.size()) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
} else {
minHeap.offer(num);
maxHeap.offer(minHeap.poll());
}
}
double getMedian() {
int median;
if (minHeap.size() > maxHeap.size()) {
median = minHeap.peek();
} else {
median = (minHeap.peek() + maxHeap.peek()) / 2;
}
return median;
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.algorithms.knapsack;
public class Knapsack {
public int knapsackRec(int[] w, int[] v, int n, int W) {
if (n <= 0) {
return 0;
} else if (w[n - 1] > W) {
return knapsackRec(w, v, n - 1, W);
} else {
return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1]));
}
}
public int knapsackDP(int[] w, int[] v, int n, int W) {
if (n <= 0 || W <= 0) {
return 0;
}
int[][] m = new int[n + 1][W + 1];
for (int j = 0; j <= W; j++) {
m[0][j] = 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= W; j++) {
if (w[i - 1] > j) {
m[i][j] = m[i - 1][j];
} else {
m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]);
}
}
}
return m[n][W];
}
}

View File

@@ -0,0 +1,35 @@
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;
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.algorithms.maximumsubarray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KadaneAlgorithm {
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.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 = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = arr[i];
} else {
maxEndingHere = maxEndingHere + arr[i];
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;
}
}
logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
return maxSoFar;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.algorithms.mergesortedarrays;
public class SortedArrays {
public static int[] merge(int[] foo, int[] bar) {
int fooLength = foo.length;
int barLength = bar.length;
int[] merged = new int[fooLength + barLength];
int fooPosition, barPosition, mergedPosition;
fooPosition = barPosition = mergedPosition = 0;
while (fooPosition < fooLength && barPosition < barLength) {
if (foo[fooPosition] < bar[barPosition]) {
merged[mergedPosition++] = foo[fooPosition++];
} else {
merged[mergedPosition++] = bar[barPosition++];
}
}
while (fooPosition < fooLength) {
merged[mergedPosition++] = foo[fooPosition++];
}
while (barPosition < barLength) {
merged[mergedPosition++] = bar[barPosition++];
}
return merged;
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.algorithms.prim;
public class Edge {
private int weight;
private boolean isIncluded = false;
private boolean isPrinted = false;
public Edge(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public boolean isIncluded() {
return isIncluded;
}
public void setIncluded(boolean included) {
isIncluded = included;
}
public boolean isPrinted() {
return isPrinted;
}
public void setPrinted(boolean printed) {
isPrinted = printed;
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.algorithms.prim;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
public class Prim {
private List<Vertex> graph;
public Prim(List<Vertex> graph){
this.graph = graph;
}
public void run(){
if (graph.size() > 0){
graph.get(0).setVisited(true);
}
while (isDisconnected()){
Edge nextMinimum = new Edge(Integer.MAX_VALUE);
Vertex nextVertex = graph.get(0);
for (Vertex vertex : graph){
if (vertex.isVisited()){
Pair<Vertex, Edge> candidate = vertex.nextMinimum();
if (candidate.getValue().getWeight() < nextMinimum.getWeight()){
nextMinimum = candidate.getValue();
nextVertex = candidate.getKey();
}
}
}
nextMinimum.setIncluded(true);
nextVertex.setVisited(true);
}
}
private boolean isDisconnected(){
for (Vertex vertex : graph){
if (!vertex.isVisited()){
return true;
}
}
return false;
}
public String originalGraphToString(){
StringBuilder sb = new StringBuilder();
for (Vertex vertex : graph){
sb.append(vertex.originalToString());
}
return sb.toString();
}
public void resetPrintHistory(){
for (Vertex vertex : graph){
Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Vertex,Edge> pair = it.next();
pair.getValue().setPrinted(false);
}
}
}
public String minimumSpanningTreeToString(){
StringBuilder sb = new StringBuilder();
for (Vertex vertex : graph){
sb.append(vertex.includedToString());
}
return sb.toString();
}
}

View File

@@ -0,0 +1,106 @@
package com.baeldung.algorithms.prim;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
public class Vertex {
private String label = null;
private Map<Vertex, Edge> edges = new HashMap<>();
private boolean isVisited = false;
public Vertex(String label){
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Map<Vertex, Edge> getEdges() {
return edges;
}
public void addEdge(Vertex vertex, Edge edge){
if (this.edges.containsKey(vertex)){
if (edge.getWeight() < this.edges.get(vertex).getWeight()){
this.edges.replace(vertex, edge);
}
} else {
this.edges.put(vertex, edge);
}
}
public boolean isVisited() {
return isVisited;
}
public void setVisited(boolean visited) {
isVisited = visited;
}
public Pair<Vertex, Edge> nextMinimum(){
Edge nextMinimum = new Edge(Integer.MAX_VALUE);
Vertex nextVertex = this;
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Vertex,Edge> pair = it.next();
if (!pair.getKey().isVisited()){
if (!pair.getValue().isIncluded()) {
if (pair.getValue().getWeight() < nextMinimum.getWeight()) {
nextMinimum = pair.getValue();
nextVertex = pair.getKey();
}
}
}
}
return new Pair<>(nextVertex, nextMinimum);
}
public String originalToString(){
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Vertex,Edge> pair = it.next();
if (!pair.getValue().isPrinted()) {
sb.append(getLabel());
sb.append(" --- ");
sb.append(pair.getValue().getWeight());
sb.append(" --- ");
sb.append(pair.getKey().getLabel());
sb.append("\n");
pair.getValue().setPrinted(true);
}
}
return sb.toString();
}
public String includedToString(){
StringBuilder sb = new StringBuilder();
if (isVisited()) {
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Vertex,Edge> pair = it.next();
if (pair.getValue().isIncluded()) {
if (!pair.getValue().isPrinted()) {
sb.append(getLabel());
sb.append(" --- ");
sb.append(pair.getValue().getWeight());
sb.append(" --- ");
sb.append(pair.getKey().getLabel());
sb.append("\n");
pair.getValue().setPrinted(true);
}
}
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.algorithms.relativelyprime;
import java.math.BigInteger;
class RelativelyPrime {
static boolean iterativeRelativelyPrime(int a, int b) {
return iterativeGCD(a, b) == 1;
}
static boolean recursiveRelativelyPrime(int a, int b) {
return recursiveGCD(a, b) == 1;
}
static boolean bigIntegerRelativelyPrime(int a, int b) {
return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE);
}
private static int iterativeGCD(int a, int b) {
int tmp;
while (b != 0) {
if (a < b) {
tmp = a;
a = b;
b = tmp;
}
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
private static int recursiveGCD(int a, int b) {
if (b == 0) {
return a;
}
if (a < b) {
return recursiveGCD(b, a);
}
return recursiveGCD(b, a % b);
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.algorithms.reversingtree;
public class TreeNode {
private int value;
private TreeNode rightChild;
private TreeNode leftChild;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TreeNode getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode rightChild) {
this.rightChild = rightChild;
}
public TreeNode getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode leftChild) {
this.leftChild = leftChild;
}
public TreeNode(int value, TreeNode leftChild, TreeNode rightChild) {
this.value = value;
this.rightChild = rightChild;
this.leftChild = leftChild;
}
public TreeNode(int value) {
this.value = value;
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.algorithms.reversingtree;
import java.util.LinkedList;
public class TreeReverser {
public void reverseRecursive(TreeNode treeNode) {
if (treeNode == null) {
return;
}
TreeNode temp = treeNode.getLeftChild();
treeNode.setLeftChild(treeNode.getRightChild());
treeNode.setRightChild(temp);
reverseRecursive(treeNode.getLeftChild());
reverseRecursive(treeNode.getRightChild());
}
public void reverseIterative(TreeNode treeNode) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if (treeNode != null) {
queue.add(treeNode);
}
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.getLeftChild() != null)
queue.add(node.getLeftChild());
if (node.getRightChild() != null)
queue.add(node.getRightChild());
TreeNode temp = node.getLeftChild();
node.setLeftChild(node.getRightChild());
node.setRightChild(temp);
}
}
public String toString(TreeNode root) {
if (root == null) {
return "";
}
StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
buffer.append(toString(root.getLeftChild()));
buffer.append(toString(root.getRightChild()));
return buffer.toString();
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,26 @@
package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
@Test
public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
for (Tree tree : balancedTrees()) {
assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree));
}
}
@Test
public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
for (Tree tree : unbalancedTrees()) {
assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree));
}
}
private String toString(Tree tree) {
return tree != null ? tree.toString() : "null";
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.algorithms.balancedbinarytree;
import java.util.Arrays;
import java.util.Collection;
class BinaryTreeDataProvider {
static Collection<Tree> balancedTrees() {
return Arrays.asList(
null,
leaf(1),
tree(1, leaf(2), leaf(3)),
tree(
1,
leaf(2),
tree(3, leaf(4), null)
),
tree(
1,
tree(
2,
tree(3, leaf(4), null),
leaf(5)
),
tree(
6,
leaf(7),
tree(8, null, leaf(9))
)
)
);
}
static Collection<Tree> unbalancedTrees() {
return Arrays.asList(
tree(
1,
tree(2, leaf(3), null),
null
),
tree(
1,
tree(
2,
tree(3, leaf(4), leaf(5)),
null
),
tree(6, leaf(7), null)
),
tree(
1,
tree(2, leaf(3), null),
tree(
4,
tree(5, leaf(6), leaf(7)),
null
)
)
);
}
private static Tree leaf(int value) {
return new Tree(value, null, null);
}
private static Tree tree(int value, Tree left, Tree right) {
return new Tree(value, left, right);
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.algorithms.binarygap;
import static com.baeldung.algorithms.binarygap.BinaryGap.calculateBinaryGap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BinaryGapUnitTest {
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(63);
assertEquals(0, result);
}
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(40);
assertEquals(1, result);
}
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(9);
assertEquals(2, result);
}
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(145);
assertEquals(3, result);
}
}

View File

@@ -0,0 +1,80 @@
package com.baeldung.algorithms.combinatorics;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class CombinatoricsUnitTest {
@Test
public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
List<Integer> sequence = Arrays.asList();
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(0, permutations.size());
}
@Test
public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(1, permutations.size());
assertEquals(1, permutations.get(0).size());
assertSame(1, permutations.get(0).get(0));
}
@Test
public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(24, permutations.size());
assertEquals(24, new HashSet<>(permutations).size());
}
@Test
public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
List<Integer> set = Arrays.asList(1, 2);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
assertEquals(0, combinations.size());
}
@Test
public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
List<Integer> set = Arrays.asList(1, 2, 3);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
assertEquals(1, combinations.size());
assertEquals(combinations.get(0), Arrays.asList(1, 2, 3));
}
@Test
public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
List<Integer> set = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> combinations = Combinatorics.combinations(set, 2);
assertEquals(6, combinations.size());
assertEquals(6, new HashSet<>(combinations).size());
}
@Test
public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd');
List<List<Character>> combinations = Combinatorics.powerSet(sequence);
assertEquals(16, combinations.size());
}
}

View File

@@ -0,0 +1,127 @@
package com.baeldung.algorithms.conversion;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.conversion.HexStringConverter;
public class ByteArrayConverterUnitTest {
private HexStringConverter hexStringConverter;
@Before
public void setup() {
hexStringConverter = new HexStringConverter();
}
@Test
public 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
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeHexString(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output);
}
@Test(expected=IllegalArgumentException.class)
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
hexStringConverter.hexToByte("fg");
}
@Test
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingGuava(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
assertArrayEquals(bytes, output);
}
private String getSampleHexString() {
return "0af50c0e2d10";
}
private byte[] getSampleBytes() {
return new byte[] { 10, -11, 12, 14, 45, 16 };
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.algorithms.integerstreammedian;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MedianOfIntegerStreamUnitTest {
@Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
MedianOfIntegerStream mis = new MedianOfIntegerStream();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey());
assertEquals(e.getValue(), (Double) mis.getMedian());
}
}
@Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
MedianOfIntegerStream2 mis = new MedianOfIntegerStream2();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey());
assertEquals(e.getValue(), (Double) mis.getMedian());
}
}
private Map<Integer, Double> testcaseFixture() {
return new LinkedHashMap<Integer, Double>() {{
put(1, 1d);
put(7, 4d);
put(5, 5d);
put(8, 6d);
put(3, 5d);
put(9, 6d);
put(4, 5d);
}};
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.algorithms.knapsack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KnapsackUnitTest {
@Test
public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;
final int W = 67;
final Knapsack knapsack = new Knapsack();
assertEquals(1270, knapsack.knapsackRec(w, v, n, W));
assertEquals(1270, knapsack.knapsackDP(w, v, n, W));
}
@Test
public void givenZeroItems_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] {};
final int[] v = new int[] {};
final int n = 0;
final int W = 67;
final Knapsack knapsack = new Knapsack();
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
}
@Test
public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;
final int W = 0;
final Knapsack knapsack = new Knapsack();
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.algorithms.maximumsubarray;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
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);
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.algorithms.maximumsubarray;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//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);
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.algorithms.mergesortedarrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.mergesortedarrays.SortedArrays;
public class SortedArraysUnitTest {
@Test
public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 7 };
int[] bar = { 4, 8, 11 };
int[] merged = { 3, 4, 7, 8, 11 };
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
}
@Test
public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 3, 7 };
int[] bar = { 4, 8, 8, 11 };
int[] merged = { 3, 3, 4, 7, 8, 8, 11 };
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.algorithms.prim;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class PrimUnitTest {
@Test
public void givenAGraph_whenPrimRuns_thenPrintMST() {
Prim prim = new Prim(createGraph());
System.out.println(prim.originalGraphToString());
System.out.println("----------------");
prim.run();
System.out.println();
prim.resetPrintHistory();
System.out.println(prim.minimumSpanningTreeToString());
}
public static List<Vertex> createGraph() {
List<Vertex> graph = new ArrayList<>();
Vertex a = new Vertex("A");
Vertex b = new Vertex("B");
Vertex c = new Vertex("C");
Vertex d = new Vertex("D");
Vertex e = new Vertex("E");
Edge ab = new Edge(2);
a.addEdge(b, ab);
b.addEdge(a, ab);
Edge ac = new Edge(3);
a.addEdge(c, ac);
c.addEdge(a, ac);
Edge bc = new Edge(2);
b.addEdge(c, bc);
c.addEdge(b, bc);
Edge be = new Edge(5);
b.addEdge(e, be);
e.addEdge(b, be);
Edge cd = new Edge(1);
c.addEdge(d, cd);
d.addEdge(c, cd);
Edge ce = new Edge(1);
c.addEdge(e, ce);
e.addEdge(c, ce);
graph.add(a);
graph.add(b);
graph.add(c);
graph.add(d);
graph.add(e);
return graph;
}
}

View File

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

View File

@@ -0,0 +1,47 @@
package com.baeldung.algorithms.reversingtree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class TreeReverserUnitTest {
@Test
public void givenTreeWhenReversingRecursivelyThenReversed() {
TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree();
reverser.reverseRecursive(treeNode);
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
.trim());
}
@Test
public void givenTreeWhenReversingIterativelyThenReversed() {
TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree();
reverser.reverseIterative(treeNode);
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
.trim());
}
private TreeNode createBinaryTree() {
TreeNode leaf1 = new TreeNode(1);
TreeNode leaf2 = new TreeNode(3);
TreeNode leaf3 = new TreeNode(6);
TreeNode leaf4 = new TreeNode(9);
TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
TreeNode root = new TreeNode(4, nodeLeft, nodeRight);
return root;
}
}

View File

@@ -0,0 +1,41 @@
{
"nodes": 5,
"edges": 7,
"edgeList": [
{
"first": 0,
"second": 1,
"weight": 8
},
{
"first": 0,
"second": 2,
"weight": 5
},
{
"first": 1,
"second": 2,
"weight": 9
},
{
"first": 1,
"second": 3,
"weight": 11
},
{
"first": 2,
"second": 3,
"weight": 15
},
{
"first": 2,
"second": 4,
"weight": 10
},
{
"first": 3,
"second": 4,
"weight": 7
}
]
}