C++ MyProgrammingLab Problem: Define a recursive function int evaluateR( char bo
ID: 3562380 • Letter: C
Question
C++ MyProgrammingLab Problem:
Define a recursive function
int evaluateR(char board[])
that returns 1, -1 or 0 depending on whether the board is a guaranteed win for X, O or an eventual cat's game.
The board array always has nine elements , representing the squares on a 3 by 3 tic tac toe board.
That means board[i] represents the square at row i / 3 + 1 and column i % 3 + 1.
Assume that each square contains one of three characters : 'X' ,'O' or '-'.
The number of X's is either equal to the number of O's or exceeds it by 1. In the first case, it's X's turn. In the second case it is O's turn.
Examples:
If board = {X,X,O,-,-,O,-,-,-} then evaluateR(board) will return -1, since this is a guaranteed win for O.
If board = {-,-,-,-,-,-,-,-,-} then evaluateR(board) will return 0, since this is an eventual cat's game.
If board = {X,O,X,-,-,-,O,-,-} then evaluateR(board) will return 1, since this is a guaranteed win for X.
Here is the pseudocode for this function:
Do not write the entire program or any other functions. Just write the code for this function only: int evaluateR(char board[])
Explanation / Answer
int evaluateR(char board[])
{
if(board.length>9)
{
for(int i=0; i<9;i++)
{
if(checkforWin(board[i])==1)
p++;
if(checkforWin(board[i])==-1)
q++;
if(checkforWin(board[i])==0)
r++;
}
}
bool xTurn=true;
for(int i=0;i<9;i++)
{
if(board[i]==null)
{
if(xTrun)
{
board[i]=’X’;
xTrun=false;
}
else
{
board[i]=’O’;
xturn=true;
}
evaluate(board[i]);
}
if(p>r && q>r)
bestofSoFar= p;
else if( q> p && q>r)
bestofSoFar=q;
else
bestofSoFar=r;
}
return bestofSoFar;
}
int checkforWin(char board[])
{
if(board[0]==board[1]==board[2]==’X’||
board[3]==board[4]==board[5]== ’X’||
board[6]==board[7]==board[8]== ’X’)
return 1;
if(board[0]==board[1]==board[2]==’O’||
board[3]==board[4]==board[5]== ’O’||
board[6]==board[7]==board[8]== ’O’)
return -1;
if(board[0]==board[1]==board[2]==’-‘||
board[3]==board[4]==board[5]==’-‘||
board[6]==board[7]==board[8]==’-‘)
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.