Skip to content

Instantly share code, notes, and snippets.

@evolutionxbox
Last active April 6, 2016 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evolutionxbox/47ca2984264b2e83c857e69518c7b2e0 to your computer and use it in GitHub Desktop.
Save evolutionxbox/47ca2984264b2e83c857e69518c7b2e0 to your computer and use it in GitHub Desktop.
You are given a 3 × 3 Tic-tac-toe board stored as a two-dimensional array. Find out the winner of the game, or return ' ' if there is no winner.
TicTacToe = (board) => {
let winbits = [7,56,73,84,146,273,292,448];
board = Array.prototype.concat.apply([], board);
query = player => {
num = 0;
board.forEach((cell, i) => {
var i = (board.length-i)-1;
num += (cell === player)<<i;
});
return num;
};
test = player => {
result = query(player);
return !winbits.every(winbit => {
return !((result&winbit) === winbit);
});
};
if (test('x')) {
return 'x';
} else if (test('o')) {
return 'o';
} else {
return ' ';
}
}
// The boards
let boardOne = [['x', 'x', 'x'],
[' ', 'o', ' '],
['o', ' ', 'x']];
let boardTwo = [['x', 'x', 'o'],
[' ', 'o', ' '],
['o', ' ', 'x']];
let boardThree = [['x', ' ', ' '],
[' ', 'x', ' '],
[' ', ' ', 'o']];
let winnerOne = TicTacToe(boardOne); // winnerOne === 'x'
let winnerTwo = TicTacToe(boardTwo); // winnerTwo === 'o'
let winnerThree = TicTacToe(boardThree); // winnerThree === ' '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment