Skip to content

Instantly share code, notes, and snippets.

@sridhar02
Last active August 3, 2022 18:50
Show Gist options
  • Save sridhar02/b158704d5733efb268a6ec55b44f3983 to your computer and use it in GitHub Desktop.
Save sridhar02/b158704d5733efb268a6ec55b44f3983 to your computer and use it in GitHub Desktop.
Tic Tac Toe CLI MM
// A simple Tic-Tac-Toe game implmented in javascript
/**
// function takes input in format [4,0,1,3,7]
// output is either winner, incomplete, draw
// Max number of inputs that can be given are 9
// 9 boxes
// 2 users are going to play this game
*/
function ticTacToe(input) {
// possible patterns
const possibleWinnerPatterns = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
// For loop over the all the inputs to get inputs X and O inputs
let xInputs = [],
oInputs = [];
for (let i = 0; i < input.length; i++) {
if (i % 2 === 0) {
xInputs.push(input[i]);
} else {
oInputs.push(input[i]);
}
}
for (let j = 0; j < possibleWinnerPatterns.length; j++) {
if (possibleWinnerPatterns[j].every((move) => xInputs.includes(move))) {
console.log('X is the winner');
return;
} else if (
possibleWinnerPatterns[j].every((move) => oInputs.includes(move))
) {
console.log('O is the winner');
return;
}
}
console.log('Draw');
}
// Different test cases
ticTacToe([0, 4, 2, 1, 8, 7]); // O is the winner
// ticTacToe([2, 8, 4, 0, 1, 3]); //Draw case
// ticTacToe([2, 1, 4, 3, 7, 6, 9, 8]); //Draw case
// ticTacToe([0, 1, 2, 3, 4, 5, 6, 7, 8]); // X is the winner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment