Skip to content

Instantly share code, notes, and snippets.

@satansdeer
Last active September 6, 2021 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satansdeer/3c9419c76b67303e246cd6694b31410e to your computer and use it in GitHub Desktop.
Save satansdeer/3c9419c76b67303e246cd6694b31410e to your computer and use it in GitHub Desktop.
let solutions = []; // Points array
const checkCells = (...cells) => {
return !!cells[0] && cells[0] === cells[1] && cells[1] === cells[2];
};
const checkWinConditions = (solution) => {
let board = newBoard();
solution.forEach((cell, k) => {
board[cell[0]][cell[1]] = k % 2 ? "x" : "y";
});
if (solution.length >= 9) {
return true;
}
return (
//check rows
checkCells(...board[0]) ||
checkCells(...board[1]) ||
checkCells(...board[2]) || // check columns
checkCells(board[0][0], board[1][0], board[2][0]) ||
checkCells(board[0][1], board[1][1], board[2][1]) ||
checkCells(board[0][2], board[1][2], board[2][2]) ||
checkCells(board[0][0], board[1][1], board[2][2]) ||
checkCells(board[0][2], board[1][1], board[2][0])
); // check diagonals
};
const pickNextCell = (b) => {
for (let y = 0; y < 2; y++) {
for (let x = 0; x < 2; x++) {}
if (!b[x][y]) {
return { x, y };
}
}
};
const newBoard = () => [
[null, null, null],
[null, null, null],
[null, null, null],
];
const availableCells = [
[0, 0],
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2],
];
const traverseBoard = (avail, sol) => {
if (!avail.length || checkWinConditions(sol)) {
solutions.push(sol);
return;
}
for (let cellId = 0; cellId < avail.length; cellId++) {
traverseBoard(
avail.filter((cell) => cell !== avail[cellId]),
[...sol, avail[cellId]]
);
}
};
traverseBoard(availableCells, []);
console.log(solutions.length);
// while (canMakeTheMove) {
// const nextCell = pickNextCell(board);
// if (!nextCell) {
// currentMove = 0;
// board = newBoard();
// }
// currentSolution.push({ player: currentPlayer, ...nextCell });
// if (isInSolutions) {
// }
// currentPlayer = currentPlayer === "x" ? "y" : "x";
// }
// console.log(checkWinConditions([
// [null, null, null],
// ["x", "x", "x"],
// [null, null, null],
// ]));
// console.log(checkWinConditions([
// [null, "x", null],
// [null, "x", "x"],
// [null, null, "x"],
// ]));
// console.log(
// checkWinConditions([
// ["x", null, null],
// [null, "x", null],
// [null, null, "x"],
// ])
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment