Wednesday, 9 January 2019

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

No comments:

Post a Comment