Skip to content

Instantly share code, notes, and snippets.

@jan-osch
Created July 12, 2018 14:11
Show Gist options
  • Save jan-osch/90eb0ccaef38c8c92c887a5e87d34052 to your computer and use it in GitHub Desktop.
Save jan-osch/90eb0ccaef38c8c92c887a5e87d34052 to your computer and use it in GitHub Desktop.
var board = [
['-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', 'R', 'R', 'R', 'R'],
['-', '-', '-', 'Y', 'Y', 'R', 'Y'],
['-', '-', '-', 'Y', 'R', 'Y', 'Y'],
['-', '-', 'Y', 'Y', 'R', 'R', 'R']];
function* getTraverses(matrix) {
const horizontalSize = matrix[0].length;
const verticalSize = matrix.length;
for (let verticalIndex = 0; verticalIndex < verticalSize; verticalIndex++) {
yield matrix[verticalIndex];
}
for (let horizontalIndex = 0; horizontalIndex < horizontalSize; horizontalIndex++) {
yield matrix.map(subArray => subArray[horizontalIndex]);
}
// topRight
for (let verticalIndex = 0; verticalIndex < (horizontalSize + verticalSize - 1); verticalIndex++) {
const partial = [];
let currentVertical = verticalIndex;
let currentHorizontal = 0;
while (currentVertical >= 0) {
if (currentVertical < verticalSize && currentHorizontal < horizontalSize) {
partial.push(matrix[currentVertical][currentHorizontal]);
}
currentVertical--;
currentHorizontal++;
}
yield partial;
}
// downRight
for (let verticalIndex = 0; verticalIndex < (horizontalSize + verticalSize - 1); verticalIndex++) {
const partial = [];
let currentVertical = verticalIndex;
let currentHorizontal = horizontalSize - 1;
while (currentVertical >= 0) {
if (currentVertical < verticalSize && currentHorizontal >= 0) {
partial.push(matrix[currentVertical][currentHorizontal]);
}
currentVertical--;
currentHorizontal--;
}
yield partial;
}
}
const getAccumulator = () => {
let previousToken;
let tokenCount;
return token => {
if (token === '-') {
return false;
}
if (token === previousToken) {
tokenCount++;
} else {
previousToken = token;
tokenCount = 1;
}
return tokenCount === 4 && previousToken;
};
};
function connectFour(board) {
let foundEmpty = false;
for (const traverse of getTraverses(board)) {
const accumulator = getAccumulator();
for (const element of traverse) {
foundEmpty = foundEmpty || element === '-';
const result = accumulator(element);
if (result) {
return result;
}
}
}
return foundEmpty
? 'in progress'
: 'draw';
}
console.log(connectFour(board));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment