in C++ please 3.1 String-representation tttresult Write a function with the foll
ID: 3903450 • Letter: I
Question
in C++ please
3.1 String-representation tttresult Write a function with the following signature char tttresult (string tttboard); The string tttboard has nine characters representing the current situation in a game of tic tac toe x represents x o represents o # represents an unplayed space The first three characters are the top row, the next three the middle row, and the last three are the bottom row So the line: represents the board The program should classify the board as one of the following . t: tie game and no spaces left . x: valid, x has won . o: valid, o has won * c: valid, game continues i invalid . e: error condition (bad shape of board, bad chars) An invalid game board is one in which there was a rule violation. A game can be invalid for many reasons, such as too many winners, unbalanced number of x's and o's, etc Do not "anticipate" tie games: a game is considered a tie only if all the spaces are filled 3.1.1 Examples tttresult("xox#x#xox" ) returns i It is invalid because x played 5 times and o only played 2 times tttresult( "xoxoxoxox") returns xExplanation / Answer
Given below is the code for the function. I have also given a main program to test that the function works correctly.
Please do rate the answer if it was helpful. Thank you
#include <iostream>
#include <string>
using namespace std;
char tttresult(string tttboard)
{
int countX = 0, countO = 0;
if(tttboard.length() != 9) //check length
return 'e';//invalid board
//check if valid chars
for(int i = 0; i < 9; i++)
{
char c = tttboard[i];
if(c == 'x')
countX++;
else if(c == 'o')
countO++;
else if(c != '#')
return 'e'; //invalid board
}
if(countO != countX) //not played equal, unbalanced plays
return 'i';
bool xwon = false , owon = false;
//check rows
for(int i = 0; i < 9; i+= 3)
{
if(tttboard[i] == tttboard[i+1] && tttboard[i+1] == tttboard[i+2])
{
if(tttboard[i] == 'x')
xwon = true;
else if(tttboard[i] =='o')
owon = true;
}
}
//check col
for(int i = 0; i < 3; i += 3)
{
if(tttboard[i] == tttboard[i+3] && tttboard[i+3] == tttboard[i+6])
{
if(tttboard[i] == 'x')
xwon = true;
else if(tttboard[i] =='o')
owon = true;
}
}
//check diagonals
if((tttboard[0] == tttboard[4] && tttboard[4] == tttboard[8]) ||
(tttboard[2] == tttboard[4] && tttboard[4] == tttboard[6]))
{
if(tttboard[4] == 'x')
xwon = true;
else if(tttboard[4] =='o')
owon = true;
}
if(xwon && owon)
return 'i'; //both winning is invalid
else if(xwon)
return 'x';
else if(owon)
return 'o';
else if(countO+countX == 9) //tie
return 't';
else
return 'c';
}
int main()
{
string s1 = "xox#x#xox";
string s2 = "xoxoxoxo#";
cout << "For " << s1 <<", result: " << tttresult(s1) << endl;
cout << "For " << s2 <<", result: " << tttresult(s2) << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.