Wednesday, 9 January 2019

Java program to implement Wumpus world. (AI)


import java.util.*;
class Environment
{
Scanner scr=new Scanner(System.in);
//char w[][]=new char[5][5];
int np; //number of pits
int wp,gp; // wumpus position gold position
int pos[]; // position of pits
int b_pos[]=new int[20];
int s_pos[]=new int[20];
void accept(String w[][])
{
for(int i=0;i<20;++i)
{
b_pos[i]=-1;
s_pos[i]=-1;
}
for(int i=0;i<5;++i)
for(int j=0;j<5;++j)
w[i][j]="";
int count=1;
System.out.println("The positions are as follows.");
for(int i=1;i<=4;++i)
{
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for(int j=1;j<=4;++j)
System.out.print((count++)+"\t|\t");
}
System.out.println("\n-----------------------------------------------------------------");
System.out.println("\nAgent start position: 13");
w[4][1]="A";
System.out.println("\nEnter the number of pits.");
np=scr.nextInt();
pos=new int[np];
System.out.println("Positions of pit, gold and wumpus should not overlap.");
System.out.println("Enter the position of pits.");
for(int i=0;i<np;++i)
{
pos[i]=scr.nextInt();
show_sense(pos[i],1,w);
}
System.out.println("Enter the position of wumpus.");
wp=scr.nextInt();
show_sense(wp,2,w);
System.out.println("Enter the position of gold.");
gp=scr.nextInt();
insert(w);
}
void insert(String w[][])
{
int temp=0;
int count=0;
int flag1=0,flag2=0;
for(int i=0;i<np;++i)
{
temp=pos[i];
count=0;
for(int j=1;j<=4;++j)
{
for(int k=1;k<=4;++k)
{
++count;
if(count==temp)
w[j][k]+="P";
else
if(count==gp && flag1==0)
{
w[j][k]+="G";
flag1=1;
}
else
if(count==wp && flag2==0)
{
w[j][k]+="W";
flag2=1;
}
}
}
}
display(w);
}
void show_sense(int a,int b,String w[][])
{
int t1,t2,t3,t4;
t1=a-1;
t2=a+1;
t3=a+4;
t4=a-4;
if(a==5 || a==9)
t1=0;
if(a==8 || a==12)
t2=0;
if(a==4)
t2=0;
if(a==13)
t1=0;

if(t3>16)
t3=0;
if(t4<0)
t4=0;
//int temp[]=new int[4];
if(b==1)
{b_pos[0]=t1;b_pos[1]=t2;b_pos[2]=t3;b_pos[3]=t4;}
else
if(b==2)
{s_pos[0]=t1;s_pos[1]=t2;s_pos[2]=t3;s_pos[3]=t4;}
int temp1,count;
for(int i=0;i<4;++i)
{
if(b==1)
temp1=b_pos[i];
else
temp1=s_pos[i];
count=0;
for(int j=1;j<=4;++j)
{
for(int k=1;k<=4;++k)
{
++count;
if(count==temp1 && b==1 && !w[j][k].contains("B"))
{
w[j][k]+="B";
}
else
if(count==temp1 && b==2 && !w[j][k].contains("S"))
w[j][k]+="S";
}
}
}
//display(w);
}
void display(String w[][])
{
System.out.println("\nThe environment for problem is as follows.\n");
for(int i=1;i<=4;++i)
{
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for(int j=1;j<=4;++j)
System.out.print(w[i][j]+"\t|\t");
}
System.out.println("\n-----------------------------------------------------------------");
}
}
class tiles
{
int safe=0;
int unsafe=0;
int wump=0;
int pit=0;
int gold=0;
int doubt_pit=0;
int doubt_wump=0;
String env;
int num=0;
int br=0;
int bl=0;
int bu=0;
int bd=0;
int visited=0;
int l,r,u,d;
String back="";
tiles(String s,int n)
{
env=s;
num=n;
l=r=u=d=0;
if(n==9 || n==5)
bl=1;
if(n==8 || n==12)
br=1;
if(n==1)
{
bu=1;bl=1;
}
if(n==13)
{
bd=1;bl=1;
}
if(n==4)
{
bu=1;br=1;
}
if(n==16)
{
bd=1;br=1;
}
}
int sense()
{
if(env.contains("B"))
return 1;
else
if(env.contains("S"))
return 2;
else
if(env.contains("G"))
return 3;
if(env.contains("W"))
return 4;
else
return 0;
}
}
class wumpus
{
static int scream=0;
static int score=0;
static int complete=0;
static boolean check(tiles t)
{
int temp=t.sense();
if(temp==1 || temp==2)
return false;
return true;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
Environment e=new Environment();
String w[][]=new String[5][5];
e.accept(w);
System.out.println("\n\nFinding the solution...");
tiles t[]=new tiles[17];
int c=1;
out:for(int i=1;i<5;++i)
{
for(int j=1;j<5;++j)
{
if(c>16)
break out;
t[c]=new tiles(w[i][j],c);
++c;
}
}
t[13].safe=1;
t[13].visited=1;
int pos=13;
int condition;
int limit=0;
String temp1,temp2;
do
{
++limit;
condition=-1;
if(t[pos].env.contains("G"))
{
complete=1;
System.out.println("Gold Found!!");
break;
}

if(t[pos].br!=1 && t[pos].r!=1 && t[pos+1].doubt_pit<1 && t[pos+1].doubt_wump<1 && t[pos+1].pit!=1 && t[pos+1].wump!=1 && !(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
{
////////////
temp1="l";
///////////
t[pos].r=1;
++pos;
System.out.println("\nfront pos="+pos);
++score;
//t[pos].visited=1;
////////////////
t[pos].back+=temp1;
////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1 )
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;

t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
/*else
if(condition==4)
{
score=score+100;
t[pos].safe=1;
}*/
else
if(condition==0)
t[pos].safe=1;
t[pos].visited=1;
}
else
if(t[pos].bl!=1 && t[pos].l!=1 && t[pos-1].doubt_pit<1 && t[pos-1].doubt_wump<1 && t[pos-1].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
{
////////////////////
temp1="r";
///////////////////
t[pos].l=1;
pos=pos-1;
System.out.println("\nback pos= "+pos);
++score;
//t[pos].visited=1;

//////////////////////
t[pos].back+=temp1;
/////////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;
t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;
t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;
t[pos].visited=1;
}
else
if(t[pos].bu!=1 && t[pos].u!=1 && (pos-4)>=1 && t[pos-4].doubt_pit<1 && t[pos-4].doubt_wump<1 && t[pos-4].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) ))
{
/////////////////////
temp1="d";
/////////////////////
t[pos].u=1;
pos=pos-4;
System.out.println("\nUp pos= "+pos);
++score;
//t[pos].visited=1;
///////////////////////
t[pos].back+=temp1;
/////////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;
t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;

t[pos].visited=1;
}
else
if(t[pos].bd!=1 && t[pos].d!=1 && (pos+4)<=16 && t[pos+4].doubt_pit<1 && t[pos+4].doubt_wump<1 && t[pos+4].pit!=1 && t[pos+4].wump!=1)
{
/////////////////
temp1="u";
////////////////
t[pos].d=1;
pos=pos+4;
System.out.println("\ndown pos= "+pos);
++score;
//t[pos].visited=1;

//////////////////

t[pos].back+=temp1;
//////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;

t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;

t[pos].visited=1;
}
else
if(limit>50)
{
int temp3=pos;
int flag_1=0,flag2=0,flag3=0,flag4=0;

System.out.println("\nCurrently at position "+temp3+".\nThinking....");
//if(!(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
while(t[pos].visited==1 && t[pos].br!=1)
{
++pos;
++score;
}


if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].br==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag_1=1;
}

if(flag_1==0)
t[pos].back+="l";

//if(!(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) ))
while(pos+4>=1 && t[pos].bu!=1 && t[pos].visited==1)
{
pos-=4;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bu==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag3=1;
}

if(flag3==0)
t[pos].back+="d";

//if(!(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
while(t[pos].visited==1 && t[pos].bl!=1)
{
--pos;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bl==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag2=1;
}

if(flag2==0)
t[pos].back+="r";



//if(!(t[pos].back.contains("d") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].u!=1) && check(t[pos]) ))
while(pos+4<=16 && t[pos].bd!=1 && t[pos].visited==1)
{
pos+=4;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bd==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag4=1;
}
//t[pos-1].r=0;
//++pos;
//if(!t[pos].env.contains("P") && !t[pos].env.contains("W"))

if(flag4==0)
t[pos].back+="u";

t[pos].safe=1;
t[pos].visited=1;
System.out.println("reached at position "+pos);
limit=0;
}
if(t[pos].env.contains("W") && scream!=1)
{
score+=100;
scream=1;
t[pos].safe=1;
System.out.println("\n\nWumpus killed >--0-->");
t[pos].env.replace("W"," ");
for(int l=1;l<=16;++l)
{
t[l].doubt_wump=0;
t[l].env.replace("S"," ");
}
}

if(t[pos].env.contains("P"))
{
score+=50;
t[pos].pit=1;
System.out.println("\n\nFallen in pit of position "+pos+".");
}

for(int k=1;k<=16;++k)
{
if(t[k].doubt_pit==1 && t[k].doubt_wump==1)
{
t[k].doubt_pit=0;
t[k].doubt_wump=0;
t[k].safe=1;
}
}

for(int y=1;y<=16;++y)
{
if(t[y].doubt_wump>1)
{
t[y].wump=1;
for(int h=1;h<=16;++h)
{
if(h!=y)
{
t[h].doubt_wump=0;
t[h].env.replace("S"," ");
}
}

}

}

///////////////////////////
for(int y=1;y<=16;++y)
{
if(t[y].doubt_pit>1)
{t[y].pit=1;
//System.out.println("\nPit confirmed at position "+y);
}
}
///////////////////////////


try{Thread.sleep(200);}catch(Exception p){}

}
while(complete==0);

if(complete==1)
{
//score=score*2;
//if(scream==1)
//score-=100;

score*=-1;
score+=1000;
}
System.out.println("The score of the agent till he reaches gold is "+score+".\nNow he will return back following the best explored path.");

}
}

Output:

codept@aiktc20 ~/Desktop $ javac wumpus.java
codept@aiktc20 ~/Desktop $ java wumpus
The positions are as follows.

-----------------------------------------------------------------
| 1 | 2 | 3 | 4 |
-----------------------------------------------------------------
| 5 | 6 | 7 | 8 |
-----------------------------------------------------------------
| 9 | 10 | 11 | 12 |
-----------------------------------------------------------------
| 13 | 14 | 15 | 16 |
-----------------------------------------------------------------

Agent start position: 13

Enter the number of pits.
4
Positions of pit, gold and wumpus should not overlap.
Enter the position of pits.
10
7
4
9
Enter the position of wumpus.
6
Enter the position of gold.
11

The environment for problem is as follows.


-----------------------------------------------------------------
| | S | B | P |
-----------------------------------------------------------------
| BS | BW | SP | B |
-----------------------------------------------------------------
| BP | BSP | BG | |
-----------------------------------------------------------------
| AB | B | | |
-----------------------------------------------------------------


Finding the solution...

front pos=14

back pos= 13

Up pos= 9


Fallen in pit of position 9.

down pos= 13

Currently at position 13.
Thinking....
reached at position 15

Currently at position 15.
Thinking....
reached at position 16

Currently at position 16.
Thinking....
reached at position 12

back pos= 11
Gold Found!!
The score of the agent till he reaches gold is 941.
Now he will return back following the best explored path.
codept@aiktc20 ~/Desktop $

Java program to implement local search algorithm (Hill climbing algorithm) (AI)


import java.util.Scanner;

public class hillClimbing {

public static void main(String[] args) {
int n,i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of nodes in graph");
n=sc.nextInt();
int[][] graph=new int[n][n];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
graph[i][j]=0;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
System.out.println("Is "+i+" is connected to "+ j);
graph[i][j]=sc.nextInt();
}
}
System.out.println("The adjacency matrix is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ System.out.print(graph[i][j]+ "\t");
}
System.out.println();
}
}
}

Output:

Enter number of nodes in graph
4
Is 0 is connected to 1
0
Is 0 is connected to 2
1
Is 0 is connected to 3
0
Is 1 is connected to 2
1
Is 1 is connected to 3
1
Is 2 is connected to 3
0
The adjacency matrix is:
0 0 1 0
0 0 1 1
0 0 0 0
0 0 0 0


Java program to implement Minimax Algorithm. (AI)


import java.io.*;
import java.util.*;
class MinMax{
static int minimax(int depth, int nodeIndex, boolean isMax,
int scores[], int h)
{

if (depth == h)
return scores[nodeIndex];

if (isMax)
return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h),
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
else
return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h),
minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
static int log2(int n)
{
return (n==1)? 0 : 1 + log2(n/2);
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter Length of Element :");
int n = sc.nextInt();
int scores[] = new int[n];
System.out.println("Enter Element :");
for(int i=0;i<n;i++){
scores[i]=sc.nextInt();
}
int h = log2(n);
int res = minimax(0, 0, true, scores, h);
System.out.println( "The optimal value is : " +res);
}
}

Output:

Enter Length of Element :
10
Enter Element :
7
8
9
4
5
6
3
1
2
0
The optimal value is : 8


Java program to implement Depth-first search (AI)

        import java.util.InputMismatchException;
        import java.util.Scanner;
        import java.util.Stack;
       
        public class DFS
        {
            private Stack<Integer> stack;
       
            public DFS()
            {
                stack = new Stack<Integer>();
            }
       
            public void dfs(int adjacency_matrix[][], int source)
            {
                int number_of_nodes = adjacency_matrix[source].length - 1;
       
                int visited[] = new int[number_of_nodes + 1];
                int element = source;
                int i = source;
                System.out.print(element + "\t");
                visited[source] = 1;
                stack.push(source);
       
                while (!stack.isEmpty())
                {
                    element = stack.peek();
                    i = element;
            while (i <= number_of_nodes)
            {
                      if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
                {
                            stack.push(i);
                            visited[i] = 1;
                            element = i;
                            i = 1;
                            System.out.print(element + "\t");
                    continue;
                        }
                        i++;
            }
                    stack.pop();
                }
            }
       
            public static void main(String...arg)
            {
                int number_of_nodes, source;
                Scanner scanner = null;
          try
                {
            System.out.println("Enter the number of nodes in the graph");
                    scanner = new Scanner(System.in);
                    number_of_nodes = scanner.nextInt();
       
            int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_of_nodes; i++)
                for (int j = 1; j <= number_of_nodes; j++)
                            adjacency_matrix[i][j] = scanner.nextInt();
       
            System.out.println("Enter the source for the graph");
                    source = scanner.nextInt();
                   //System.out.println("Enter the goal for the graph");
               //int goal = scanner.nextInt();
                    System.out.println("The DFS Traversal for the graph is given by ");
                    DFS dfs = new DFS();
                    dfs.dfs(adjacency_matrix, source);
                }catch(InputMismatchException inputMismatch)
                {
                    System.out.println("Wrong Input format");
                }
                scanner.close();
            }
        }
     
Output:

        $javac DFS.java
        $java DFS
        Enter the number of nodes in the graph
        4
        Enter the adjacency matrix
        0 1 0 1
        0 0 1 0
        0 1 0 1
        0 0 0 1
        Enter the source for the graph
        1
        The DFS Traversal for the graph is given by
        1 2 3 4
        */

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


Java program to implement Alpha-Beta Pruning (AI)


import java.io.*;
import java.util.*;
class AlphaBeta{
static int MAX = 1000;
static int MIN = -1000;
static int minimax(int depth, int nodeIndex,
Boolean maximizingPlayer,
int values[], int alpha,
int beta)
{
if (depth == 3)
return values[nodeIndex];
if (maximizingPlayer)
{
int best = MIN;
for (int i = 0; i < 2; i++)
{
int val = minimax(depth + 1, nodeIndex * 2 + i,
false, values, alpha, beta);
best = Math.max(best, val);
alpha = Math.max(alpha, best);
if (beta <= alpha)
break;
}
return best;
}
else
{
int best = MAX;
for (int i = 0; i < 2; i++)
{
int val = minimax(depth + 1, nodeIndex * 2 + i,
true, values, alpha, beta);
best = Math.min(best, val);
beta = Math.min(beta, best);
if (beta <= alpha)
break;
}
return best;
}
}
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Length of Element :");
int n = sc.nextInt();
int values[] = new int[n];
System.out.println("Enter Element :");
for(int i=0;i<n;i++){
values[i]=sc.nextInt();
}
System.out.println("The optimal value is : " +
minimax(0, 0, true, values, MIN, MAX));
}
}


Output:

Desktop $ javac AlphaBeta.java
Desktop $ java AlphaBeta

Enter Length of Element :
16
Enter Element :
10
5
7
11
12
8
9
8
5
12
11
12
9
8
7
10
The optimal value is : 8

Breadth-first search implementation in Java (AI)



    import java.util.InputMismatchException;

    import java.util.LinkedList;

    import java.util.Queue;

    import java.util.Scanner;

   

    public class BFS

    {

      private Queue<Integer> queue;

   

        public BFS()

        {

            queue = new LinkedList<Integer>();

        }

   

        public void bfs(int adjacency_matrix[][], int source)

        {

            int number_of_nodes = adjacency_matrix[source].length - 1;

   

            int[] visited = new int[number_of_nodes + 1];

            int i, element;

   

            visited[source] = 1;

            queue.add(source);

   

            while (!queue.isEmpty())

            {

                element = queue.remove();

                i = element;

                System.out.print(i + "\t");

                while (i <= number_of_nodes)

                {

                    if (adjacency_matrix[element][i] == 1 && visited[i] == 0)

                    {

                        queue.add(i);

                        visited[i] = 1;

                    }

                    i++;

                }

            }

        }

   

        public static void main(String... arg)

        {

            int number_no_nodes, source;

            Scanner scanner = null;

   

            try

            {

                System.out.println("Enter the number of nodes in the graph");

                scanner = new Scanner(System.in);

                number_no_nodes = scanner.nextInt();

   

                int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];

                System.out.println("Enter the adjacency matrix");

                for (int i = 1; i <= number_no_nodes; i++)

                    for (int j = 1; j <= number_no_nodes; j++)

                        adjacency_matrix[i][j] = scanner.nextInt();

   

                System.out.println("Enter the source for the graph");

                source = scanner.nextInt();

   

                System.out.println("The BFS traversal of the graph is ");

                BFS bfs = new BFS();

                bfs.bfs(adjacency_matrix, source);

   

            } catch (InputMismatchException inputMismatch)

            {

                System.out.println("Wrong Input Format");

            }

            scanner.close();

        }

    }

codept@aiktc11 ~/Desktop $ java BFS
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0 1 0 1
0 0 1 0
0 1 0 1
0 0 0 1
Enter the source for the graph
1
The BFS traversal of the graph is
1 2 4 3

Sunday, 22 July 2018

A Java Program to illustrate Caesar Cipher Technique (CSS)


class CaesarCipher
{
    // Encrypts text using a shift od s
    public static StringBuffer encrypt(String text, int s)
    {
        StringBuffer result= new StringBuffer();

        for (int i=0; i<text.length(); i++)
        {
            if (Character.isUpperCase(text.charAt(i)))
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 65) % 26 + 65);
                result.append(ch);
            }
            else
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 97) % 26 + 97);
                result.append(ch);
            }
        }
        return result;
    }

    // Driver code
    public static void main(String[] args)
    {
        String text = "ATTACKATONCE";
        int s = 4;
        System.out.println("Text  : " + text);
        System.out.println("Shift : " + s);
        System.out.println("Cipher: " + encrypt(text, s));
    }
}