Skip to content

Instantly share code, notes, and snippets.

@raymondfeng
Last active January 4, 2016 14:49
Show Gist options
  • Select an option

  • Save raymondfeng/8636789 to your computer and use it in GitHub Desktop.

Select an option

Save raymondfeng/8636789 to your computer and use it in GitHub Desktop.
Tie-tac-toe homework
/**
* Check if the given slot is empty (no piece placed)
*/
function isEmpty(s) {
return s !== 'x' && s !== 'o';
}
/**
* Get the state for a row with three slots
*/
function getRowState(s1, s2, s3) {
if(s1 === 'x' && s2 === 'x' && s3 === 'x') {
// All three slots are 'x'. The winner is x
return 'x';
}
(PLEASE FINISH THE FUNCTION HERE)
}
// Let's test the function with different cases
console.log(getRowState('x', 'x', 'x'));
(PLEASE ADD MORE TESTS)
/**
* Get the state of tic-tac-toe board
* @param board An array with 9 slots. Each slot can have
* a value of 'x', 'o', or ' '.
*/
function getBoardState(board) {
var rows = [];
rows[0] = getRowState(board[0], board[1], board[2]);
rows[1] = getRowState(board[3], board[4], board[5]);
rows[2] = getRowState(board[6], board[7], board[8]);
rows[3] = getRowState(board[0], board[3], board[6]);
rows[4] = getRowState(board[1], board[4], board[7]);
rows[5] = getRowState(board[2], board[5], board[8]);
rows[6] = getRowState(board[0], board[4], board[8]);
rows[7] = getRowState(board[2], board[4], board[6]);
// Use a flag to track if the game is still in progress
var inProgress = false;
for(var i=0; i<rows.length; i++) {
if(rows[i] === 'x') {
// Found a row with 3 'x': x wins
return 'x';
}
if(rows[i] === 'o') {
// Found a row with 3 'o': o wins
return 'o';
}
if(rows[i] === 'i') {
// The game is in progress so far
inProgress = true;
}
}
if(inProgress) {
// One of the rows still has empty slots
return 'i';
}
// All slots are taken, it's a tie
return 't';
}
// Let's run some tests
var board = ['x', 'o', ' ', ' ', ' ', 'x', 'o', 'x', 'o'];
console.log('Result: ' + getBoardState(board));
board = ['x', 'o', 'x', 'x', 'x', 'o', 'o', 'x', 'o'];
console.log('Result: ' + getBoardState(board));
board = ['x', 'o', 'o', 'x', 'x', 'x', 'o', 'x', 'o'];
console.log('Result: ' + getBoardState(board));
board = ['o', 'o', 'o', 'x', ' ', 'x', 'x', 'x', 'o'];
console.log('Result: ' + getBoardState(board));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment