Skip to content

Instantly share code, notes, and snippets.

@mk-pmb
Last active November 13, 2017 00:47
Show Gist options
  • Save mk-pmb/67ddb459e0fc40c249c6318510b48c94 to your computer and use it in GitHub Desktop.
Save mk-pmb/67ddb459e0fc40c249c6318510b48c94 to your computer and use it in GitHub Desktop.
/*jslint indent: 2, maxlen: 80, continue: false, unparam: false, node: true */
/* -*- tab-width: 2 -*- */
'use strict';
function displayGame(field, colSep, rowSep) {
return field.map(String).join(rowSep).replace(/,/g, colSep);
}
function mg0(txt, rgx) { return (rgx.exec(txt) || false)[0]; }
function checkWinner(gst) {
var dis = displayGame(gst, '', ':'), size = gst.length,
rxHoriz = new RegExp('\\b(1{#}|2{#})\\b'.replace(/#/g, size)),
rxVert = new RegExp('1(.{#}1){_}|2(.{#}2){_}'.replace(/#/g, size
).replace(/_/g, size - 1));
return (mg0(dis, rxHoriz) || mg0(dis, rxVert) || '-').substr(0, 1);
}
function luciferCheck(gst) {
var winner = 0, size = gst.length, x, y;
// Horizontal Check
function horiz(a, b) {
console.log('horiz?', { y: y, a: a, b: b, eq: (a === b) });
return ((a === b) ? a : 0);
}
for (y = 0; y < size; y += 1) {
winner = gst[y].reduce(horiz);
console.log('horiz?', { winner: winner });
if (winner) { return winner; }
}
// Vertical Check
function vert(a, b) {
console.log('vert?', { x: x, ax: a[x], bx: b[x], eq: (a[x] === b[x]) });
return (a[x] === b[x] ? a[x] : 0);
// Nope: Returning a number will crash the [x] lookup in the next iteration.
// Log line: vert? { x: 0, ax: undefined, bx: 1, eq: false }
}
for (x = 0; x < size; x += 1) {
winner = gst.reduce(vert);
console.log('vert?', { winner: winner });
if (winner) { return winner; }
}
return 0;
}
function eachFor(f, a) { a.forEach(f); }
eachFor(function (field) {
console.log([
displayGame(field, ' ', '\n'),
checkWinner(field),
luciferCheck(field),
].join('\t') + '\n');
}, [
[ [ 0, 2, 2 ],
[ 1, 0, 2 ],
[ 1, 0, 1 ] ],
[ [ 2, 2, 2 ],
[ 1, 0, 2 ],
[ 1, 0, 1 ] ],
[ [ 1, 2, 2 ],
[ 1, 0, 2 ],
[ 1, 0, 1 ] ],
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment