Skip to content

Instantly share code, notes, and snippets.

@micimize
Last active May 8, 2017 23:36
Show Gist options
  • Save micimize/be5e09d58aae0c4906c31dcc5ef02b37 to your computer and use it in GitHub Desktop.
Save micimize/be5e09d58aae0c4906c31dcc5ef02b37 to your computer and use it in GitHub Desktop.
Core logic for a bitwise tic-tac-toe board checker
function flatten(arrays) {
return [].concat.apply([], arrays)
}
function zip(...arrays) {
let zipped = []
for(var index = 0; index < arrays[0].length; index++){
zipped.push(arrays.map(a => a[index]))
}
return zipped
}
function equals(a, b) {
var i = a.length;
if (i != b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
}
function bitwiseAnd(a, b) {
return zip(a, b).map(([bitA, bitB]) => bitA & bitB)
}
const winningBitboards = [
[1, 1, 1,
0, 0, 0,
0, 0, 0],
[0, 0, 0,
1, 1, 1,
0, 0, 0],
[0, 0, 0,
0, 0, 0,
1, 1, 1],
[1, 0, 0,
1, 0, 0,
1, 0, 0],
[0, 1, 0,
0, 1, 0,
0, 1, 0],
[0, 0, 1,
0, 0, 1,
0, 0, 1],
[1, 0, 0,
0, 1, 0,
0, 0, 1],
[0, 0, 1,
0, 1, 0,
1, 0, 0]
]
// takes a vector board with vector rows of symbols/strings/ints, or a sring board,
// returns a bitboard for the given sign
function compileBitboard(board, sign) {
board = (typeof(board) == 'string')
? board = board.replace(/\s/g, '').split('')
: flatten(board)
return board.map(c => Number(c === sign))
}
// returns true if the given bitboard contains one of the states in the second argument
function bitboardStatematch(bitboard, [firstState, ...states]) {
return Boolean(equals(bitwiseAnd(bitboard, firstState), firstState) ||
(states.length && bitboardStatematch(bitboard, states)))
}
function isBitVictory(bitboard) {
return bitboardStatematch(bitboard, winningBitboards)
}
function isVictory(board, sign) {
return isBitVictory(compileBitboard(board, sign))
}
console.log(isVictory([
["x", "o", null],
["x", null, "o"],
["x", "o", null]
], "x"))
console.log(isVictory(" ono\n xon\n xno", "o"))
const otherInputs = [
[[[1 0 null] [1 null 0 ] [1 0 null]], 1], // ture
[[["x" "o" null] ["x" null "o"] ["x" "o" null]] "o"] // false
]
@micimize
Copy link
Author

micimize commented May 8, 2017

js adaption of an old clojure sample

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment