Wednesday, 9 January 2019

Java program to implement to implement A* algorithm (AI)



import java.util.Iterator;


import org.json.JSONObject;


public class Tree {
String s = "{"
+"\"s\" : { \"a\": 1, \"b\":2 },"
+"\"a\": {\"y\": 7, \"z\": 4},"
+"\"b\": {\"c\": 7, \"d\": 1},"
+"\"y\": {\"e\": 3},"
+"\"z\": {\"e\": 2},"
+"\"c\": {\"e\": 5},"
+"\"d\": {\"e\": 12},"
+"\"e\": 0"
+"}";

String h_str ="{"
+"\"s\" : 10,"
+"\"a\" : 5,"
+"\"b\" : 6,"
+"\"c\" : 4,"
+"\"d\" : 15,"
+"\"z\" : 5,"
+"\"y\" : 8,"
+"\"e\" : 0,"
+"}";

JSONObject graph = new JSONObject(s);
JSONObject h = new JSONObject(h_str);

JSONObject list_1 = new JSONObject();
JSONObject list_2 = new JSONObject();

String root = "s";
String goal = "e";

public void astar(String node, String f, int g) {

// System.out.println(f+" "+g);
try {
Iterator itr = graph.getJSONObject(node).keySet().iterator();
while(itr.hasNext()) {
String e = (String)itr.next();
// System.out.println();
if (e != root) {
list_1.put(f, g+h.getInt(node));
astar(e,f+"-"+e,g+graph.getJSONObject(node).getInt(e));
}else {
System.out.println(node);
}
}

}catch(Exception e){
list_2.put(f, g);
}
}


}


public class Run {
public static void main(String args[]) {
Tree a = new Tree();
a.astar(a.root, a.root, 0);
System.out.println("Traversed paths -> ");
Iterator itr = a.list_1.keySet().iterator();
while(itr.hasNext()) {
String key = (String)itr.next();
System.out.println(key+" -> "+a.list_1.get(key));
}
String p = null;
int v = 1000;
System.out.println("Successfull paths found ->");
Iterator itr2 = a.list_2.keySet().iterator();
while(itr2.hasNext()) {
String key = (String)itr2.next();
System.out.println(key+" -> "+a.list_2.getInt(key));
if (a.list_2.getInt(key)<v) {
v = a.list_2.getInt(key);
p = key;
}
}
System.out.print("The shortest path is : (");
System.out.print(p+") with value: "+v);
}

}
Output ->
Traversed paths ->
s -> 10
s-b-c -> 13
s-b-d -> 18
s-a -> 6
s-a-y -> 16
s-b -> 8
s-a-z -> 10
Successfull paths found ->
s-b-d-e -> 15
s-b-c-e -> 14
s-a-y-e -> 11
s-a-z-e -> 7
The shortest path is : (s-a-z-e) with value: 7


No comments:

Post a Comment