Added IterativeDeepening

This commit is contained in:
Niklas Birk 2019-03-27 20:38:47 +01:00
parent 72bdf77bf6
commit bb95a412d8
3 changed files with 102 additions and 22 deletions

View File

@ -0,0 +1,45 @@
package search.iterativedeepening;
import search.Node;
public class IterativeDeepening
{
public <T> Node<T> iterativeDeepening(Node<T> node, Node<T> target)
{
int lowBarrier = 0;
Node<T> resultNode;
do
{
resultNode = depthFirstSearch(node, target, 0, lowBarrier++);
}
while (resultNode == null);
return resultNode;
}
private <T> Node<T> depthFirstSearch(Node<T> node, Node<T> target, int depth, int barrier)
{
if (node.isTargetReached(target))
{
return node;
}
var newNodes = node.generateSuccessors();
while (!newNodes.isEmpty() && depth < barrier)
{
var resultNode = depthFirstSearch(newNodes.get(0), target, ++depth, barrier);
if (resultNode != null)
{
return resultNode;
}
newNodes.remove(0);
}
return null;
}
}

View File

@ -28,26 +28,4 @@ class DepthFirstSearchTest
printSolution(actual);
}
// @Test
// void shouldReturnCorrectTargetChubekNode()
// {
// int[][] state = {
// {2, 0, 4},
// {6, 7, 1},
// {8, 5, 3}
// };
// var root = new EightPuzzleNode(state);
//
// int[][] targetState = {
// {1, 2, 3},
// {4, 5, 6},
// {7, 8, 0}
// };
// var expected = new EightPuzzleNode(targetState);
//
// var actual = new DepthFirstSearch().depthFirstSearch(root, expected);
//
// printSolution(actual);
// }
}

View File

@ -0,0 +1,57 @@
package search.iterativedeepening;
import org.junit.jupiter.api.Test;
import search.EightPuzzleNode;
import search.breadthfirstsearch.BreadthFirstSearch;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static search.SearchTestUtils.printSolution;
class IterativeDeepeningTest
{
@Test
void shouldReturnCorrectTarget()
{
int[][] state = {
{5, 0, 3},
{2, 1, 6},
{4, 7, 8}
};
var root = new EightPuzzleNode(state);
int[][] targetState = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 0}
};
var expected = new EightPuzzleNode(targetState);
var actual = new IterativeDeepening().iterativeDeepening(root, expected);
printSolution(actual);
}
@Test
void shouldReturnCorrectTargetChubekNode()
{
int[][] state = {
{2, 0, 4},
{6, 7, 1},
{8, 5, 3}
};
var root = new EightPuzzleNode(state);
int[][] targetState = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 0}
};
var expected = new EightPuzzleNode(targetState);
var actual = new IterativeDeepening().iterativeDeepening(root, expected);
printSolution(actual);
}
}