ai lab final

Upload: nitesh-tirkey

Post on 10-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Ai Lab Final

    1/53

    A PROJECT REPORT ON

    ARTIFICIAL

    INTELLIGENCE

  • 8/8/2019 Ai Lab Final

    2/53

    CONTENTS

    S.No. Name of Experiment Date ofsubmission

    Remarks

    1. Relationships 2-11-2010

    2. Travelling salesman 2-11-2010

    3. Water jug 2-11-2010

    4. Breadth first 2-11-2010

    5. Depth first 2-11-2010

    6. Misssionaries and

    cannibals

    2-11-2010

    7. Simple hill climbing 2-11-2010

    8. Steepest hill climbing 2-11-2010

    9. AO* algorithm 2-11-2010

    10. MINIMAX algorithm 2-11-2010

  • 8/8/2019 Ai Lab Final

    3/53

    Experiment 1

    Aim

    To define simple relation and find relatives.

    Theory

    In this method simple clauses are defined to relate a person with another.

    Then the other relations are found based upon this.

    Examples

    If John is the father ofGary

    And son relation is the inverse offather.

    Then we can infer that Gary is the son ofJohn.

    Language

    PROLOG

    Program

    PREDICATES

    son(string,string).

    father(string,string).

    married(string,string).

    mother(string,string).

    brother(string,string).

    sister_in_law(string,string).

    CLAUSES

    son("John", "Dan").

    brother("Dan","Max").

    married("John", "Suzie").

  • 8/8/2019 Ai Lab Final

    4/53

    married("Dan", "Mary").

    married("Max","Julie").

    father(A,B):-son(B,A).

    mother(A,C):-father(A,B),married(B,C).

    sister_in_law(A,C):-brother(A,B),married(B,C).

    GOAL

    sister_in_law("Dan",P).

    Output

    1 solution

    Julie

  • 8/8/2019 Ai Lab Final

    5/53

    Experiment 2

    Aim

    To solve the classical travelling salesman problem of AI.

    Theory

    A salesman has a list of cities, each of which he must exactly visit once. There

    are direct road between each pair of cities on the list. This program finds the

    root the salesman should follow for the shortest possible path between any

    pair of cities.

    Examples

    The distance between city Aand B is 200 km.

    The distance between city B and C is 300 km.

    The distance between city C and D is 200 km.

    The distance between city B and D is 300 km.

    We have to find the path from A to D.

    The various routs can be

    ABCD with total distance of 700 km

    ABD with total distance of 500 km

    Hence ABDis the preferable route.

    Language

    PROLOG

    Program

    DOMAINS

    town = symbol

    distance = integer

  • 8/8/2019 Ai Lab Final

    6/53

    PREDICATES

    nondeterm road(town,town,distance)

    nondeterm route(town,town,distance)

    CLAUSES

    road(delhi,mumbai,200).

    road(kolkata,delhi,300).

    road(mumbai,kolkata,100).

    road(mumbai,raipur,120).

    road(kolkata,raipur,130).

    route(Town1,Town2,Distance):-

    road(Town1,Town2,Distance).

    route(Town1,Town2,Distance):-

    road(Town1,X,Dist1),

    route(X,Town2,Dist2),

    Distance=Dist1+Dist2,!.

    GOAL

    route(delhi,raipur,Z).

    Output

    1 Solution

    320

  • 8/8/2019 Ai Lab Final

    7/53

    Experiment 3

    Aim

    To solve the classical water jug problem of AI.

    Theory

    In this we are given two jugs, a 4- litre one and a 3-litre one. Neither has any

    measuring markers on it. There is a pump that can be used to fill the jugs with

    water. The task is to get exactly 2- litres of water in the 4- litre jug.

    Examples

    The steps taken are

    4-litre 3-litre Step

    0 0 Start

    0 3 Pour water in 3- litre jug

    3 0 Pour water from 3- litre jug to 4- litre jug

    3 3 Pour water in the 3- litre jug

    4 2 Pour water from 3- litre jug to 4- litre jug

    0 2 Empty the 4- litre jug

    2 0 Pour water from 3- litre jug to 4- litre jug

    Language

    C

    Program

    #include

    #include

    void main()

    {

  • 8/8/2019 Ai Lab Final

    8/53

    clrscr();

    int x=0,y=0; //x=Jug A and y=Jug B

    while(x!=2 || y!=0)

    {

    if(x!=4 && y=4 && y>0)

    {

    y=y-(4-x);

    x=4;

    printf("Pour water from the three litre jug into the four litre jug until the fourlitre jug is full\n");

    }

    if(y==2)

    {

  • 8/8/2019 Ai Lab Final

    9/53

    x=0;

    printf("Empty the four litre jug on the ground \n");

    }

    if(x==0 && y==2)

    {

    x=2;

    y=0;

    printf("Pour the 2 litre water from the three litre jug into the four litre jug \n");

    }

    }

    printf("The water jug problem is solved");

    getch();

    }

    Output

  • 8/8/2019 Ai Lab Final

    10/53

    Experiment 4

    Aim

    To implement the Breadth first search algorithm for finding the goal node from

    the tree.

    Theory

    BFS is an uninformed search method that aims to expand and examine all

    nodes of a graph or combination of sequences by systematically searching

    through every solution. In other words, it exhaustively se arches the entire

    graph or sequence without considering the goal until it finds it. It does not use

    aheuristic algorithm.

    From the standpoint of the algorithm, all child nodes obtained by expanding anode are added to a FIFO (i.e., First In, First Out) queue. In typical

    implementations, nodes that have not yet been examined for their neighbors

    are placed in some container (such as a queue or linked list) called "open" and

    then once examined are placed in the container "closed".

    Examples

    The tree used in this program is

    A

    B C

    D E F G

    H

    The traversing will be done as follows A,B,C,D,E,H

    Language

  • 8/8/2019 Ai Lab Final

    11/53

    C

    Program

    #include

    #include

    void main()

    {

    clrscr();

    /* The tree is

    a

    / \

    b c

    /\ /\

    d e f g

    /

    h

    The initial state is a and goal state is h

    */

    char bintree[15]={'a','b','c','d','e','f','g',' ',' ','h',' ',' ',' ', ' ',' '};

    char TRAV_LIST[15];

    char temp1,temp2;

    int i=0;

    while(temp1!='h' && temp2!='h')

    {

  • 8/8/2019 Ai Lab Final

    12/53

    TRAV_LIST[i]=bintree[i];

    temp1=bintree[2*i+1];

    temp2=bintree[2*i+2];

    i++;

    }

    TRAV_LIST[i]='h';

    printf("The traversing path is :\n");

    for(int j=0;j

  • 8/8/2019 Ai Lab Final

    13/53

    Experiment 5

    Aim

    To implement the Depth first search algorithm for finding the goal node from

    the tree.

    Theory

    DFS is an uninformed search that progresses by expanding the first child node

    of the search tree that appears and thus going deeper and deeper until a goal

    node is found, or until it hits a node that has no children. Then the

    search backtracks, returning to the most recent node it hasn't finished

    exploring. In a non-recursive implementation, all freshly expanded nodes are

    added to a stack for exploration.

    Examples

    The tree used in this program is

    A

    B C

    D E F G

    H

    The traversing will be done as follows A,B,D,E,C,F,G,H

    Language

    C

  • 8/8/2019 Ai Lab Final

    14/53

    Program

    #include

    #include

    void main()

    {

    clrscr();

    /* The tree is

    a

    / \

    b c

    /\ /\

    d e f g

    /

    h

    The initial state is a and goal state is h

    */

    char bintree[15]={'a','b','c','d','e','f','g',' ',' ',' ',' ',' ',' ', 'h',' '};

    char TRAV_LIST[15];

    char temp1,temp2;

    int i=0,k=0;

    TRAV_LIST[0]=bintree[0];

    while(TRAV_LIST[i]!='h')

    {

  • 8/8/2019 Ai Lab Final

    15/53

    for(k=0;k=i+1;j--)

    {

    TRAV_LIST[j+1]=TRAV_LIST[j];

    }

    TRAV_LIST[i+1]=bintree[2*k+1];

    }

    if(bintree[2*k+2]!=' ')

    {

    for(int j=13;j>=i+2;j--)

    {

    TRAV_LIST[j+1]=TRAV_LIST[j];

    }

    TRAV_LIST[i+2]=bintree[2*k+2];

    }

    i++;

    }

  • 8/8/2019 Ai Lab Final

    16/53

    printf("The traversing path is :\n");

    for(int j=0;j

  • 8/8/2019 Ai Lab Final

    17/53

    Experiment 6

    Aim

    To solve the missionaries and cannibals problem by taking suitable start state

    and goal state.

    Theory

    The problem says that we have three missionaries and three cannibals who

    have to be transported across a river in a boat. Only two persons are allowed

    to go in the boat at a given time. The number of cannibals should never be

    more than that of the missionaries , otherwise the missionaries will be killed.

    Examples

    The goal state is given by

    3 missionaries and 3 cannibals on the other side of the river.

    If the initial state is

    3 missionaries and three cannibals on one side.

    We have to put a series of steps to get to the goal state.

    Language

    C

    Program

    #include

    #include

    using namespace std;

    structStateSTR

    {

  • 8/8/2019 Ai Lab Final

    18/53

    intMlhs; //nr missionaries on LHS of river

    intClhs; //nr cannibals on LHS of river

    intpos; //boat on LHS (0) or RHS(1) of river

    intMrhs; //nr missionaries on RHS of river

    intCrhs; //nr cannibals on RHS of river

    StateSTR *parent;//pointer to parent state

    bool operator==(constStateSTR&rhs) const

    {

    return ((Mlhs == rhs.Mlhs) && (Clhs == rhs.Clhs) &&

    (Mrhs == rhs.Mrhs) && (Crhs == rhs.Crhs) &&

    (pos == rhs.pos));

    }

    constStateSTR operator=(constStateSTR&rhs)

    {

    Mlhs =rhs.Mlhs;

    Clhs =rhs.Clhs;

    pos = rhs.pos;

    Mrhs =rhs.Mrhs;

    Crhs =rhs.Crhs;

    parent= rhs.parent;

    return *this;

    }

    };

  • 8/8/2019 Ai Lab Final

    19/53

    ostream& operator

  • 8/8/2019 Ai Lab Final

    20/53

    //Apply each of ten possible operations to state.

    m c side(0=left,1=right)

    case 0: C(0,1,0) --> carry one cannibal to LHS

    case 1: C(0,2,0) --> carry two cannibals to LHS

    case 2: C(1,0,0)

    case 3: C(2,0,0)

    case 4: C(1,1,0)

    case 5: C(0,1,1)

    case 6: C(0,2,1)

    case 7: C(1,0,1) --> carry one missionary to RHS

    case 8: C(2,0,1)

    case 9: C(1,1,1)

    StateSTRnextState(StateSTR&X, constint j)

    {

    StateSTR S = X;

    switch (j)

    {

    case 0: { S.pos -= 1;

    S.Mlhs += 0;

    S.Clhs += 1;

    S.Mrhs -= 0;

    S.Crhs -= 1;}

  • 8/8/2019 Ai Lab Final

    21/53

    break;

    case 1: { S.pos -= 1;

    S.Mlhs += 0;

    S.Clhs += 2;

    S.Mrhs -= 0;

    S.Crhs -= 2;}

    break;

    case 2: { S.pos -= 1;

    S.Mlhs += 1;

    S.Clhs += 0;

    S.Mrhs -= 1;

    S.Crhs -= 0;}

    break;

    case 3: { S.pos -= 1;

    S.Mlhs += 2;

    S.Clhs += 0;

    S.Mrhs -= 2;

    S.Crhs -= 0;}

    break;

    case 4: { S.pos -= 1;

    S.Mlhs += 1;

    S.Clhs += 1;

    S.Mrhs -= 1;

  • 8/8/2019 Ai Lab Final

    22/53

    S.Crhs -= 1;}

    break;

    case 5: { S.pos += 1;

    S.Mrhs += 0;

    S.Crhs += 1;

    S.Mlhs -= 0;

    S.Clhs -= 1;}

    break;

    case 6: { S.pos += 1;

    S.Mrhs += 0;

    S.Crhs += 2;

    S.Mlhs -= 0;

    S.Clhs -= 2;}

    break;

    case 7: { S.pos += 1;

    S.Mrhs += 1;

    S.Crhs += 0;

    S.Mlhs -= 1;

    S.Clhs -= 0;}

    break;

    case 8: { S.pos += 1;

    S.Mrhs += 2;

    S.Crhs += 0;

  • 8/8/2019 Ai Lab Final

    23/53

    S.Mlhs -= 2;

    S.Clhs -= 0;}

    break;

    case 9: { S.pos += 1;

    S.Mrhs += 1;

    S.Crhs += 1;

    S.Mlhs -= 1;

    S.Clhs -= 1;}

    break;

    }

    return S;

    }

    boolnotFound(StateSTR Y, list OPEN,

    list CLOSED)

    {

    list::iterator sRslt1 = find(OPEN.begin(), OPEN.end(), Y);

    list::iterator sRslt2

    = find(CLOSED.begin(), CLOSED.end(), Y);

    if( (sRslt1 == OPEN.end()) && (sRslt2 == CLOSED.end()) )

    return true;

    return false;

  • 8/8/2019 Ai Lab Final

    24/53

    }

    voidaddChildren(list& OPEN,

    list& CLOSED,

    StateSTR& X )

    {

    StateSTRtmpState;

    for(int i = 0; i < 10; i++)

    {

    tmpState = nextState(X, i);

    if( (validState(tmpState)) &&

    (notFound(tmpState, OPEN, CLOSED)) )

    {

    tmpState.parent = &X;

    OPEN.push_front(tmpState);

    }

    }

    return;

    }

    //MAIN section

    int main() {

    boolsearchResult = false;

  • 8/8/2019 Ai Lab Final

    25/53

    StateSTR START = {3,3,0,0,0,NULL};

    StateSTR GOAL = {0,0,1,3,3,NULL};

    StateSTR X;

    StateSTRtempState;

    list OPEN;

    list CLOSED;

    OPEN.push_front(START);

    while(!OPEN.empty())

    {

    X = OPEN.front(); //stack-like operation

    OPEN.pop_front(); //

    if (X == GOAL)

    {

    searchResult = true;

    GOAL = X;

    break;

    }

    else

    {

    addChildren(OPEN, CLOSED, X);

    CLOSED.push_back(X);

    }

  • 8/8/2019 Ai Lab Final

    26/53

    }

    //Display results

    if(searchResult == true)

    {

    cout

  • 8/8/2019 Ai Lab Final

    27/53

    Move two cannibals to the left.

    Move one cannibal back to the right.

    Move two cannibals to the left.

  • 8/8/2019 Ai Lab Final

    28/53

    Experiment 7

    Aim

    To solve the simple hill climbing problem by taking suitable start state and goal

    state.

    Theory

    The problem says that we are on the bottom of a hill. We have to go on the top

    of it i.e to reach the highest point on the hill. For this we will perform breadth

    first search algorithm to find the highest node in the tree which represents the

    hill.

    Examples

    The goal state is given by

    Highest point in the tree is reached.

    If the initial state is

    The root node of the tree.

    We have to put a series of steps to get to the goal state.

    Language

    C

    Program

    //conditions for plateau, cliff and ridge are not shown

    #include

    #include

    #include

    struct tree

    {

    int value;

  • 8/8/2019 Ai Lab Final

    29/53

    float weight;

    int parent;

    struct tree *next;

    };

    main()

    {

    struct tree *HEAD,*PTR,*PAR;

    charch;

    int MAX,MIN_WEIGHT;

    int flag=0;

    while(1)

    {

    struct tree *temp;

    printf("Enter the new node (value weight parent) (Use . to indicate a parent

    node):");

    scanf("%d%f%d",&temp->value,&temp->weight,parent);

    if(flag==0)

    {

    HEAD=temp;

    PAR=temp;

    PTR=temp;

    flag=1;

    }

    else

  • 8/8/2019 Ai Lab Final

    30/53

    {

    PTR->next=temp;

    PTR=temp;

    }

    while(PAR->next!=null)

    {

    if(PAR->value==parent)

    {

    PAR->next=temp;

    }

    }

    printf("Want to add more node(y/n):");

    scanf("%c",&ch);

    if(ch=='n' || ch=='N')

    {

    PTR->next=null;

    break;

    }

    }

    printf("\nHill Created Successfully\n");

    printf("Finding the maximum peak point:\n");

    printf("Path Traversed: ");

    MAX=HEAD->value;

  • 8/8/2019 Ai Lab Final

    31/53

    PTR=HEAD;

    MIN_WEIGHT=HEAD->weight;

    while(1)

    {

    if(PTR->next==null)

    break;

    if(PTR->weightvalue;

    MAX=PTR->value;

    MIN_WEIGHT=PTR->weight;

    PTR=PTR->next;

    }

    else

    {

    PTR=PTR->next;

    }

    }

    printf("\nMaximum Height: %d",MAX);

    }

    Output

    Enter new node

  • 8/8/2019 Ai Lab Final

    32/53

    2

    Want to add new node

    y

    Enter new node

    6

    Want to add new node

    8

    Enter new node

    10

    Want to add new node

    y

    Enter new node

    14

    Want to add new node

    y

    Enter new node

    13

    Want to add new node

    n

    Highest peak in the hill: 14

  • 8/8/2019 Ai Lab Final

    33/53

    Experiment 8

    Aim

    To solve the steepest hill climbing problem by taking suitable start state and

    goal state.

    Theory

    The problem says that we are on the bottom of a hill. We have to go on the top

    of it i.e to reach the highest point on the hill. But the twist is that we hwve

    more than one peaks in the hill and hence we have to find out the highest peak

    of the hill. For this we will perform best first search algorithm to find the

    highest node in the tree which represents the hill.

    Examples

    The goal state is given by

    Highest peak in the tree is reached.

    If the initial state is

    The root node of the tree.

    We have to put a series of steps to get to the goal state.

    Language

    C

    Program

    #include

    #include

    #include

    struct tree

    {

    int value;

  • 8/8/2019 Ai Lab Final

    34/53

    float weight;

    int parent;

    int type;

    struct tree *next;

    };

    main()

    {

    struct tree *HEAD,*PTR,*PAR;

    charch;

    int MAX,MIN_WEIGHT;

    int flag=0;

    while(1)

    {

    struct tree *temp;

    printf("Enter the new node (value weight Parent Type) (Use 0 to AND Arc and 1

    to indicate an OR arc):");

    scanf("%d%f%d%d",&temp->value,&temp->weight,parent,type);

    if(flag==0)

    {

    HEAD=temp;

    PAR=temp;

    PTR=temp;

    flag=1;

    }

  • 8/8/2019 Ai Lab Final

    35/53

    else

    {

    PTR->next=temp;

    PTR=temp;

    }

    while(PAR->next!=null)

    {

    if(PAR->value==parent)

    {

    PAR->next=temp;

    }

    }

    printf("Want to add more node(y/n):");

    scanf("%c",&ch);

    if(ch=='n' || ch=='N')

    {

    PTR->next=null;

    break;

    }

    }

    printf("\nTree Created Successfully\n");

    printf("Finding the desired node:\n");

    printf("Path Traversed: ");

  • 8/8/2019 Ai Lab Final

    36/53

    MAX=HEAD->value;

    PTR=HEAD;

    MIN_WEIGHT=HEAD->weight;

    while(1)

    {

    if(PTR->next==null)

    break;

    if(PTR->type==0)

    {

    //Handling AND Arcs

    weight=PTR->weight*PAR->weight;

    }

    else

    {

    weight=PTR->weight;

    }

    if(weightvalue);

    MAX=PTR->value;

    MIN_WEIGHT=weight;

    PTR=PTR->next;

    }

  • 8/8/2019 Ai Lab Final

    37/53

    else

    {

    PTR=PTR->next;

    }

    }

    printf("Desired Node: %d",MAX);

    getch();

    }

    Output

    Enter new node

    2

    Want to add more nodes?

    y

    Enter new node

    4

    Want to add more nodes?

    y

    Enter new node

    6

    Want to add more nodes?

    y

    Enter new node

  • 8/8/2019 Ai Lab Final

    38/53

    16

    Want to add more nodes?

    y

    Enter new node

    10

    Want to add more nodes?

    y

    Enter new node

    18

    Want to add more nodes?

    n

    Highest point in the hill 18

  • 8/8/2019 Ai Lab Final

    39/53

    Experiment 9

    Aim

    To implement the AO* algorithm.

    Theory

    AO*is a best-first algorithm for solving a cyclic AND/OR graphs. Starting

    with a partial graph G containing only the initial states0 , two operations

    are performediteratively : first, a best partial policy over G is constructed

    and a non-terminal tip state s reachable with this policy is expanded ;

    second, the value function and best policy over the updated graph are

    incrementally recomputed. This process continues until the best partial

    policy is complete. The second step, called the cost revision step, ex ploits

    the acyclicity of the AND/OR graph for recomputing the optimal costs andpolicy over the partial graph G in as inglepass, unlike Value Iteration. In

    this computation, the states outside G are regarded as terminal states

    with costs given by their heuristic values. When the AND/Or graph

    contains cycles, however, this basic costrevision operation is not

    adequate. In this paper, we use the AO* variant developed in

    (Jimenez&Torras2000),calledCFCrev, which is based in the cost revision

    operation and is able to handle cycles.

    Examples

    The following code can only handle single branch child .

    Language

    C

    Program

    #include

    #include

    #include

    #include

    struct tree

  • 8/8/2019 Ai Lab Final

    40/53

    {

    int value;

    float weight;

    int parent;

    int type;

    struct tree *next;

    };

    main()

    {

    struct tree *HEAD,*PTR,*PAR;

    charch;

    int MAX,MIN_WEIGHT;

    int flag=0;

    int weight;

    while(1)

    {

    struct tree *temp;

    printf("Enter the new node (value weight parent type) (Use 0 to AND Arc and 1

    to indicate an OR arc):");

    scanf("%d%f%d%d",&temp->value,&temp->weight,parent,type);

    if(flag==0)

    {

    HEAD=temp;

    PAR=temp;

  • 8/8/2019 Ai Lab Final

    41/53

    PTR=temp;

    flag=1;

    }

    else

    {

    PTR->next=temp;

    PTR=temp;

    }

    while(PAR->next!=null)

    {

    if(PAR->value==parent)

    {

    PAR->next=temp;

    }

    }

    printf("Want to add more node(y/n):");

    scanf("%c",&ch);

    if(ch=='n' || ch=='N')

    {

    PTR->next=null;

    break;

    }

    }

  • 8/8/2019 Ai Lab Final

    42/53

    printf("\nTree Created Successfully\n");

    printf("Finding the desired node:\n");

    printf("Path Traversed: ");

    MAX=HEAD->value;

    PTR=HEAD;

    MIN_WEIGHT=HEAD->weight;

    while(1)

    {

    if(PTR->next==null)

    break;

    if(PTR->type==0)

    {

    weight=PTR->weight*PAR->weight;

    }

    else

    {

    weight=PTR->weight;

    }

    if(weightvalue);

    MAX=PTR->value;

    MIN_WEIGHT=weight;

  • 8/8/2019 Ai Lab Final

    43/53

    PTR=PTR->next;

    }

    else

    {

    PTR=PTR->next;

    }

    }

    printf("Desired Node: %d",MAX);

    getch();

    }

    Output

    Add new node

    2

    Want to add another node

    y

    Add new node

    4

    Want to add another node

    Y

  • 8/8/2019 Ai Lab Final

    44/53

    Add new node

    8

    Want to add another node

    y

    Add new node

    10

    Want to add another node

    Y

    Add new node

    12

    Want to add another node

    N

    Path traversed:

    2 4 12

    Node Desired: 12

  • 8/8/2019 Ai Lab Final

    45/53

    Experiment 10

    Aim

    To implement the minmax algorithm.

    Theory

    Minimax (sometimes minmax) is a decision rule used in decision theory, game

    theory, statistics and philosophy forminimizing the possible loss while maximizing

    the potential gain. Alternatively, it can be thought of as maximizing the minimum gain

    (maximin). Originally formulated for two-player zero-sum game theory, covering both

    the cases where players take alternate moves and those where they make

    simultaneous moves, it has also been extended to more complex games and to

    general decision making in the presence of uncertainty .

    .

    Language

    Java

    Program

    import java.io.*;

    importjava.util.*;

    public class Connect {

    private static final int WIDTH=7, HEIGHT=6;

    private static final int MAX_RECURDEPTH=6;

    private static BufferedReader in;

    privateint[][] grid=new int[WIDTH][HEIGHT];

    privateint[] columnHeight=new int[WIDTH];

    private static intrecurDepth=0;

  • 8/8/2019 Ai Lab Final

    46/53

    public static void main(String[] args) {

    in=new BufferedReader(new InputStreamReader(System.in));

    new Connect4();

    }

    public Connect4() {

    int column;

    int player=1;

    Vector moves=new Vector();

    while(true) {

    if(player==1) {

    printGrid();

    do {

    System.out.print("Make your move (1-7): ");

    column=readInt()-1;

    } while(column=WIDTH ||

    columnHeight[column]>=HEIGHT);

    } else {

    moves.removeAllElements();

    column=0;

    intprevValue=-MAX_RECURDEPTH-1;

    for(int x=0; x=HEIGHT) continue;

  • 8/8/2019 Ai Lab Final

    47/53

    int value=minmax(2, x);

    if(value>prevValue) {

    moves.removeAllElements();

    prevValue=value;

    }

    if(value==prevValue) moves.add(new Integer(x));

    }

    if(moves.size()>0) {

    Collections.shuffle(moves);

    column=((Integer)moves.get(0)).intValue();

    }

    if(moves.size()==0) {

    System.out.println("Its a draw.");

    break;

    }

    }

    grid[column][columnHeight[column]]=player;

    columnHeight[column]++;

    int won=0;

    won=fourInARow();

    if(won>0) {

    printGrid();

    }

  • 8/8/2019 Ai Lab Final

    48/53

    player=3-player;

    }

    }

    intminmax(int player, int column) {

    int value=0;

    if(columnHeight[column]>=HEIGHT) return 0;

    recurDepth++;

    grid[column][columnHeight[column]]=player;

    columnHeight[column]++;

    if(fourInARow()>0) {

    if(player==2)

    value=MAX_RECURDEPTH+1-recurDepth;

    else value=-MAX_RECURDEPTH-1+recurDepth;

    }

    if(recurDepth

  • 8/8/2019 Ai Lab Final

    49/53

    int v=minmax(3-player, x);

    if(value==(MAX_RECURDEPTH+1)) value=v;

    else if(player==2) { if(value>v) value=v; }

    else if(v>value) value=v;

    }

    }

    recurDepth--;

    columnHeight[column]--;

    grid[column][columnHeight[column]]=0;

    return value;

    }

    intfourInARow() {

    intnum, player;

    for(int y=0; y

  • 8/8/2019 Ai Lab Final

    50/53

    }

    for(int x=0; x

  • 8/8/2019 Ai Lab Final

    51/53

    num=0; player=0;

    for(int x=xStart, y=yStart; x=0; x++, y--) {

    if(grid[x][y]==player) num++;

    else { num=1; player=grid[x][y]; }

    if(num==4 && player>0) return player;

    }

    if(yStart==HEIGHT-1) xStart++;

    elseyStart++;

    }

    return 0;

    }

    voidprintGrid() {

    for(int y=HEIGHT-1; y>=0; y--) {

    for(int x=0; x

  • 8/8/2019 Ai Lab Final

    52/53

    intreadInt() {

    try {

    String input=in.readLine();

    int number=Integer.parseInt(input);

    return number;

    } catch(NumberFormatException e) {

    return -1;

    } catch(IOException e) {

    return -1;

    }}}

    Output

  • 8/8/2019 Ai Lab Final

    53/53