JAVA-12097: renamed algorithms-module to algorithms-modules
This commit is contained in:
+33
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+17
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+67
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+110
@@ -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());
|
||||
}
|
||||
}
|
||||
+42
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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];
|
||||
}
|
||||
}
|
||||
+35
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -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;
|
||||
}
|
||||
}
|
||||
+33
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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;
|
||||
}
|
||||
}
|
||||
+73
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+106
@@ -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();
|
||||
}
|
||||
}
|
||||
+45
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+42
@@ -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;
|
||||
}
|
||||
}
|
||||
+53
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
Reference in New Issue
Block a user