Last active
April 6, 2016 13:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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