Breadth first and Depth first are finished, hopefully they work ass supposed
[ailab2.git] / src / MySearcher.java
blobc037a77b16e42d6ff59588407d7876c5f8248fb2
1 import java.io.File;
2 import java.io.IOException;
3 import java.util.Iterator;
4 import java.util.List;
5 import java.util.LinkedList;
6 import java.util.PriorityQueue;
7 import java.util.Hashtable;
8 import java.util.Enumeration;
9 import org.jdom.*;
11 /**
12 * Beskrivning av klassen.
14 public class MySearcher extends MapSearcher {
15 private Graph map;
17 /**
18 * Skapar en ny MySearcher-instans.
20 public MySearcher () {
21 super ();
24 /**
25 * Specificerar kartan.
27 * @param map Den XML-fil som representerar kartan.
29 * @TODO fixa this.map.insertEdge() för alla noder.
31 public void setMap(File mapFile) {
32 Document doc;
33 List<Element> cityElements;
34 try {
35 doc = loadXmlMap(mapFile);
36 cityElements = doc.getRootElement().getChildren();
37 map = new Graph(cityElements.size(), 5);
39 // Iterate through cityElements
40 for (Element cityElement: cityElements) {
41 // Prints names of cities
42 String cityName = cityElement.getAttributeValue("id");
43 int cityX = Integer.parseInt(cityElement.getAttributeValue("x"));
44 int cityY = Integer.parseInt(cityElement.getAttributeValue("y"));
45 GraphNode cityNode = map.insertNode(cityName, cityX, cityY);
46 //System.out.println(cityName + " at position (" + cityX + ", " + cityY + ")");
48 // Iterate through roadElements
49 List<Element> roadElements = cityElement.getChildren();
50 for (Element roadElement: roadElements) {
51 String roadTo = roadElement.getAttributeValue("to");
52 Double roadSpeed = Double.parseDouble(roadElement.getAttributeValue("speed"));
53 // Prints all roads connected to the current cityElement
54 //System.out.println(" road to -> " + roadElement.getAttributeValue("to"));
55 Double time = 1.0;
56 if (map.isInGraph(roadTo)) { // @FIX declare var in if condition
57 GraphNode roadToNode = map.getNode(roadTo);
58 Double distance = Math.hypot((cityNode.getX() - roadToNode.getX()),
59 (cityNode.getY() - roadToNode.getY()));
60 time = distance / (roadSpeed / 3.6);
62 map.insertEdge(cityName, roadTo, time);
63 // @FIX change roadSpeed to time
67 catch (IOException e) {
68 System.err.println ("Could not read/find file.");
69 System.exit(1);
70 } catch (JDOMException e) {
71 System.err.println ("File is not in valid XML format?");
72 System.exit(1);
73 } catch (NumberFormatException e) {
74 System.err.println ("Coordinates cannot be parsed.");
78 /**
79 * Utför sökning med Greedy Search.
81 * @param from Den plats sökningen börjar från.
82 * @param to Den plats sökningen avslutas på.
84 public String greedySearch (String from, String to) {
85 // 1. Set N to be a sorted list of initial nodes;
86 PriorityQueue<GraphNode> bigN =
87 new PriorityQueue<GraphNode>(this.map.getNodes());
88 GraphNode n;
89 while (!bigN.isEmpty()) { // 2. If N is empty,
90 // 3. set n to be the first node in N, and remove n from N;
91 // 4. If n is a goal node, exit and signal success;
92 // 5. Otherwise add the children of n to N, sort the nodes in N
93 // according to the value on their evaluation function and return to
94 // step 2.
96 // 2. ... exit and signal failure
97 return null;
101 * Utför sökning med A*.
103 * @param from Den plats sökningen börjar från.
104 * @param to Den plats sökningen avslutas på.
105 * @param fastest Om <code>true</code>, hitta snabbaste vägen,
106 * annars den kortaste.
108 public String aStar (String from, String to, boolean fastest) {
109 // skapa en tabell över hur långt det är från alla platser på
110 // kartan till målet för sökningen
111 // Hashtable<String, Double> targetDistTable =
112 // new Hashtable<String, Double>(map.size());
113 // // spara ned målnoden
114 // GraphNode targetLocation = map.getNode(to);
115 // GraphNode tempNode;
116 // Enumeration e;
117 // // för alla noder
118 // for (e = map.getNodes(),
119 // tempNode = (GraphNode) e.nextElement();
120 // e.hasMoreElements(); // medan e har element
121 // tempNode = (GraphNode) e.nextElement()) {
122 // // spara avståndet till målnoden för varje nod
123 // targetDistTable.put(tempNode.getName(),
124 // Math.hypot(targetLocation.getX()-tempNode.getX(),
125 // targetLocation.getY()-tempNode.getY()));
128 * implementation av aStar.
130 return "";
134 * Utför bredden-förstsökning.
136 * @param from Den plats sökningen börjar från.
137 * @param to Den plats sökningen avslutas på.
139 public String breadthFirst (String from, String to) {
140 // Comments fetched from
141 // http://en.wikipedia.org/wiki/Breadth-first_search
142 // at Tue Oct 14 12:57:18 2008
143 LinkedList<GraphNode> q = new LinkedList<GraphNode>();
144 String expandedNodes = "";
145 String pathToGoal = "";
146 // 1. Put the root node on the queue.
147 q.add(map.getNode(from));
148 while (!q.isEmpty()) {
149 // 2. Pull a node from the beginning of the queue and examine it.
150 GraphNode n = q.removeFirst();
151 // * If the searched element is found in this node, quit
152 // * the search and return a result.
153 if (n.getName().equals(to)) {
154 expandedNodes += to;
155 while (n != map.getNode(from)) {
156 pathToGoal = n.getName() + ", " + pathToGoal;
157 n = n.getParent();
159 pathToGoal = n.getName() + ", " + pathToGoal;
160 break;
162 // * Otherwise push all the (so-far-unexamined) successors
163 // * (the direct child nodes) of this node into the end of
164 // * the queue, if there are any.
165 else {
166 expandedNodes += n.getName() + ", ";
167 for (Enumeration e = n.getNeighbours(); e.hasMoreElements();) {
168 GraphNode neighbour = (GraphNode) e.nextElement();
169 neighbour.setParent(n);
170 q.add(neighbour);
173 // If the queue is empty, every node on the graph has been
174 // examined -- quit the search and return "not found".
175 if (q.isEmpty()) {
176 return "\nGoal not found!";
179 return "\nAll visited nodes:\n" + expandedNodes + "\n\n"
180 + "Path to goal:\n" + pathToGoal;
184 * Utför djupet-förstsökning.
186 * @param from Den plats sökningen börjar från.
187 * @param to Den plats sökningen avslutas på.
189 public String depthFirst (String from, String to) {
190 LinkedList<GraphNode> s = new LinkedList<GraphNode>();
191 String expandedNodes = "";
192 String pathToGoal = "";
193 // 1. Push the root node onto the stack.
194 s.add(map.getNode(from));
195 while (!s.isEmpty()) {
196 // 2. Pop a node from the stack
197 GraphNode n = s.removeLast();
198 // * Mark this node as visited
199 n.visit();
200 // * If the searched element is found in this node, quit
201 // * the search and return a result.
202 if (n.getName().equals(to)) {
203 expandedNodes += to;
204 while (n != map.getNode(from)) {
205 pathToGoal = n.getName() + ", " + pathToGoal;
206 n = n.getParent();
208 pathToGoal = n.getName() + ", " + pathToGoal;
209 break;
211 // * Otherwise push all the unvisited connecting nodes of n
212 else {
213 expandedNodes += n.getName() + ", ";
214 for (Enumeration e = n.getNeighbours();
215 e.hasMoreElements();) {
216 GraphNode neighbour = (GraphNode) e.nextElement();
217 if (!neighbour.isVisited()) {
218 neighbour.setParent(n);
219 s.add(neighbour);
223 // If the stack is empty, every node on the graph has been
224 // examined -- quit the search and return "not found".
225 if (s.isEmpty()) {
226 return "\nGoal not found!";
229 return "\nAll visited nodes:\n" + expandedNodes + "\n"
230 + "Path to goal:\n" + pathToGoal;
233 public String toString() {
234 return map.toString();