[BAEL-19135] - Move search articles to a new module
This commit is contained in:
11
algorithms-searching/README.md
Normal file
11
algorithms-searching/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
## Algorithms - Searching
|
||||
|
||||
This module contains articles about searching algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
37
algorithms-searching/pom.xml
Normal file
37
algorithms-searching/pom.xml
Normal file
@@ -0,0 +1,37 @@
|
||||
<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-searching</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-searching</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>algorithms-searching</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
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) / 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) / 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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.info("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.info("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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
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 traverseLevelOrder() {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Queue<Node> nodes = new LinkedList<>();
|
||||
nodes.add(root);
|
||||
|
||||
while (!nodes.isEmpty()) {
|
||||
|
||||
Node node = nodes.remove();
|
||||
|
||||
System.out.print(" " + node.value);
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.left);
|
||||
}
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
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>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
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);
|
||||
}
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int value) {
|
||||
this.value = value;
|
||||
right = null;
|
||||
left = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
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 void 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();
|
||||
isVisited[current] = true;
|
||||
visit(current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
stack.push(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void dfs(int start) {
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
dfsRecursive(start, isVisited);
|
||||
}
|
||||
|
||||
private void dfsRecursive(int current, boolean[] isVisited) {
|
||||
isVisited[current] = true;
|
||||
visit(current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
dfsRecursive(dest, 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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();
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
13
algorithms-searching/src/main/resources/logback.xml
Normal file
13
algorithms-searching/src/main/resources/logback.xml
Normal 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>
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public 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
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryTreeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(!bt.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(6));
|
||||
assertTrue(bt.containsNode(4));
|
||||
|
||||
assertFalse(bt.containsNode(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
int initialSize = bt.getSize();
|
||||
|
||||
assertTrue(bt.containsNode(3));
|
||||
bt.add(3);
|
||||
assertEquals(initialSize, bt.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertFalse(bt.containsNode(99));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(9));
|
||||
bt.delete(9);
|
||||
assertFalse(bt.containsNode(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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
|
||||
public 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
|
||||
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseLevelOrder();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.algorithms.dfs.Graph;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
|
||||
Graph graph = createDirectedGraph();
|
||||
graph.dfs(0);
|
||||
System.out.println();
|
||||
graph.dfsWithoutRecursion(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
|
||||
Graph graph = createDirectedGraph();
|
||||
List<Integer> list = graph.topologicalSort(0);
|
||||
System.out.println(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class InterpolationSearchUnitTest {
|
||||
|
||||
private int[] myData;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
myData = new int[]{13,21,34,55,69,73,84,101};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor84_thenReturn6() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 84);
|
||||
assertEquals(6, pos);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 19);
|
||||
assertEquals(-1, pos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.algorithms.mcts;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.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;
|
||||
|
||||
public class MCTSUnitTest {
|
||||
private Tree gameTree;
|
||||
private MonteCarloTreeSearch mcts;
|
||||
|
||||
@Before
|
||||
public void initGameTree() {
|
||||
gameTree = new Tree();
|
||||
mcts = new MonteCarloTreeSearch();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
|
||||
double uctValue = 15.79;
|
||||
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
|
||||
State initState = gameTree.getRoot().getState();
|
||||
List<State> possibleStates = initState.getAllPossibleStates();
|
||||
assertTrue(possibleStates.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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
|
||||
public 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(winStatus, Board.DRAW);
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextSearchAlgorithmsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testStringSearchAlgorithms() {
|
||||
String text = "This is some nice text.";
|
||||
String pattern = "some";
|
||||
|
||||
int realPosition = text.indexOf(pattern);
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user