Skip to content

Instantly share code, notes, and snippets.

@sashak007
Created July 13, 2017 07:21
Show Gist options
  • Save sashak007/427a5256ba60bf0311ed479854f795b7 to your computer and use it in GitHub Desktop.
Save sashak007/427a5256ba60bf0311ed479854f795b7 to your computer and use it in GitHub Desktop.
// create a method that determines a winner from a given board. Manipulting matrix datasets.
var board = [
['x','x', 'o'],
['x', 'o', 'x'],
['x',null, null],
];
var board2 = [
['o', null, 'o'],
['x', 'x', 'x'],
['o',null, null],
];
var board3 = [
['o',null, 'o'],
['o', 'x', 'x'],
['o',null, null],
];
var board4 = [
['o',null, 's'],
['x', 'o', 's'],
['o',null, 's'],
];
var board5 = [
['x',null, 'o'],
['o', 'x', 'x'],
['o',null, 'x'],
];
function isWinner(board) {
var winner = true;
for(var grid = 0; grid < board.length; grid++) {
/** checks horizontal matches **/
for(var row = 0; row < board.length; row++){
if(!board[grid][row] || board[grid][row] !== board[grid][0]){
winner = false;
}
if (winner && row === board.length-1) return board[grid][0];
}
winner = true; // find a better way to reset winner state?
/** checks vertical matches **/
for(var col = 0; col < board.length; col++){
if(!board[col][grid] || board[col][grid] !== board[0][grid]){
winner = false;
}
if (winner && col === board.length-1) return board[col][grid];
}
winner = true;
/** checks diagonal matches from right to left **/
for(var d = board.length -1; d >= 0; d--){
if(!board[grid][board.length-1] || !board[board.length-1][grid] || board[grid][board.length-1] === board[board.length-1][grid]){
winner = false;
}
if (winner && grid === board.length-1) return board[grid][board.length-1];
}
winner = true;
/** checks diagonal matches from left to right [IMPORTANT - the placement was critical]**/
if(!board[grid][grid] || board[grid][grid] !== board[0][0]) {
winner = false
}
if (winner && grid === board.length-1) {
return board[grid][grid];
}
winner = true;
}
return 'No winner';
}
console.log('board '+isWinner(board))
console.log('board2 '+isWinner(board2))
console.log('board3 '+isWinner(board3))
console.log('board4 '+isWinner(board4))
console.log('board5 '+isWinner(board5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment