From 6a44b074f0169a1b0f9e92347af929c5e471746e Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Sat, 18 Apr 2015 13:44:44 +0200 Subject: Reorganised projects --- Week6 Sliding game solver/src/Node.java | 92 +++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Week6 Sliding game solver/src/Node.java (limited to 'Week6 Sliding game solver/src/Node.java') diff --git a/Week6 Sliding game solver/src/Node.java b/Week6 Sliding game solver/src/Node.java new file mode 100644 index 0000000..cb5c900 --- /dev/null +++ b/Week6 Sliding game solver/src/Node.java @@ -0,0 +1,92 @@ +import java.util.ArrayList; + +/** + * For maintaining lists of T-elements enabling + * a structure suited for backwards traversal + * + * @author Pieter Koopman, Sjaak Smetsers + * @author Camil Staps, s4498062 + * + * @param The element this node is based on + */ +@SuppressWarnings("Convert2Diamond") // We disable these warnings for Java <=1.7 compatibility. +public class Node implements Comparable> +{ + // the data field + private final T item; + // a reference to the predecessor + private final Node previous; + + /* A constructor that initializes each node + * with the specified values + * @param from the node preceding the current node + * @param item the initial data item + */ + public Node (Node from, T item) { + this.previous = from; + this.item = item; + } + + /* a getter for the item + * @return item + */ + public T getItem() { + return item; + } + + /* + * a getter for the predecessor + * @return previous + */ + public Node getPrevious() { + return previous; + } + + /* + * determines the length of the current list + * @return the length as an integer + */ + public int length () { + int length = 1; + Node prev = previous; + while ( prev != null ) { + prev = prev.previous; + length++; + } + return length; + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + + ArrayList> path; + path = new ArrayList>(); + Node prev = this; + while ( prev != null ) { + path.add(prev); + prev = prev.previous; + } + + for (int i = path.size() - 1; i >= 0; i--) + result.append(path.size() - i - 1).append(":\n").append(path.get(i).getItem().toString()); + + return result.toString(); + } + + /** + * Just comparing the items isn't very clever. The Manhattan distance is a fairly small number. + * With large queues, many nodes will then have the same priority. It's much better to select + * on both Manhattan distance and path length. That way, we will find shorter paths. + * Note though that since we're prioritizing on Manhattan distance primarily, this does not + * mean that we necessarily find the shortest path. + * @param t + * @return + */ + @Override + public int compareTo(Node t) { + if (this.item.compareTo(t.item) == 0) + return Integer.compare(length(), t.length()); + return this.item.compareTo(t.item); + } +} -- cgit v1.2.3