Skip to content

Instantly share code, notes, and snippets.

@dydx
Last active June 4, 2016 12:45
Show Gist options
  • Save dydx/9af9b042a914750e7a38 to your computer and use it in GitHub Desktop.
Save dydx/9af9b042a914750e7a38 to your computer and use it in GitHub Desktop.
// theory of tic tac toe win discovery
//
// | 2 | 7 | 6 |
// | 9 | 5 | 1 |
// | 4 | 3 | 8 |
//
// this forms a "magic square" where each
// row, column, or diagonal adds up to 15
//
// as players make moves, the values of
// these spaces are added to an array
//
// to check if a player has won, just
// calculate if any 3 value permutation
// adds up to 15
// this is rather inefficient, but the external API is solid
function combinations (size, array) {
// return the powerset of a given array
function powerset (array) {
var ps = [[]]
for (var i = 0; i < array.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(array[i]))
}
}
return ps
}
// filter a nested array for subsets of a given size
function of_size (size, arr) {
return arr.filter(function (el) {
return (el.length === size)
})
}
// filter our powerset for combinations of a given size
return of_size(size, powerset(array))
}
function has_won (player, board) {
// given the magic square solution to tic tac toe, just filter
// player's space arrays for combinations that sum to 15
function _has_won (spaces) {
var spaces_combinations = combinations(3, spaces)
return spaces_combinations.some(function (spcs) {
return (spcs.reduce(function (x, y) { return x + y }) === 15)
})
}
var player_spaces = board.filter(function (space) {
// get all spaces owned by the player
return (space[1] === player)
}).map(function (space) {
// build a new list of the scores from those spaces
return space[0]
})
return _has_won(player_spaces)
}
var board = [
[2, null],
[7, null],
[6, null],
[9, null],
[5, null],
[1, null],
[4, null],
[3, null],
[8, null]
]
function cellValue (key, board) {
return board.filter(function (cell) {
return cell[0] === key
}).map(function (cell) {
return cell[1]
})[0] // return an Array or just a str?
}
function setCell (key, value, board) {
board[key][1] = value
}
console.log(' -- before playing -- ')
console.log(board)
setCell(6, 'x', board)
setCell(7, 'x', board)
setCell(8, 'x', board)
console.log(cellValue(8, board))
console.log(' -- after playing -- ')
console.log(board)
console.log(`Did 'X' Win?: ${has_won('x', board)}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment