- static member in Puzzle8
- added docs
- added statistic in AStar visit
This commit is contained in:
2023-12-13 10:01:24 +01:00
parent 6ac1ff463d
commit f941ef93c3
2 changed files with 20 additions and 1 deletions

View File

@@ -22,6 +22,9 @@ public class AStar<State, Action> {
private BiFunction<State, State, Integer> heuristic;
private TriFunction<State, State, Action, Integer> cost;
private int lastStateVisitedCount = 0;
private int lastStateTotalCount = 0;
/**
* Crea una istanza dell'algoritmo A* con una funzione di azioni possibili da compiere dato uno stato
* e una funzione di transizione che dato uno stato permette di raggiungerne un'altro tramite un'azione.
@@ -92,11 +95,16 @@ public class AStar<State, Action> {
Objects.requireNonNull(initial);
Objects.requireNonNull(goal);
this.lastStateVisitedCount = 0;
this.lastStateTotalCount = 1;
NodeState found = null;
var list = new PriorityQueue<NodeState>();
list.add(new NodeState(null, initial, null, 0, 0));
while(list.size() > 0) {
this.lastStateVisitedCount += 1;
var current = list.poll();
if(current.state.equals(goal)) {
found = current;
@@ -105,6 +113,7 @@ public class AStar<State, Action> {
for(var action : this.actions.apply(current.state)) try {
this.lastStateTotalCount += 1;
var next = this.transition.apply(current.state, action);
var cost = this.cost.apply(current.state, next, action);
var dist = this.heuristic.apply(next, goal);
@@ -129,8 +138,18 @@ public class AStar<State, Action> {
}
public int lastStateVisitedCount() {
return this.lastStateVisitedCount;
}
public int lastStateTotalCount() {
return this.lastStateTotalCount;
}
/**
* Classe privata per mantenere i dati all'interno della PriorityQueue.
* Non è stata messa statica dato che ho bisogno dello stato e dell'azione.
*/
private class NodeState implements Comparable<NodeState> {
NodeState parent;

View File

@@ -21,7 +21,7 @@ public class Puzzle8 implements Iterable<Integer> {
/**
* Possibili movimenti della tessera "vuota"
*/
public enum Move {
public static enum Move {
UP,
DOWN,
LEFT,