Skip to content

Instantly share code, notes, and snippets.

@jacky810124
Created April 29, 2022 21:56
Show Gist options
  • Save jacky810124/637a4befbd4e51467ec0a348f78d891c to your computer and use it in GitHub Desktop.
Save jacky810124/637a4befbd4e51467ec0a348f78d891c to your computer and use it in GitHub Desktop.
Tic-tac-toe scan all blocks solution
var getWinners = (blocks, amount) => {
for (let i = 0; i < amount; i++) {
const rowBlocks = [];
const columnBlocks = [];
const slashBlocks = [];
const backSlashBlocks = [];
for (let j = 0; j < amount; j++) {
rowBlocks.push(blocks[i * amount + j]);
columnBlocks.push(blocks[j * amount + i]);
backSlashBlocks.push(blocks[j * amount + j]);
slashBlocks.push(blocks[j * amount + (amount - j - 1)]);
}
if (getIsSame(rowBlocks) != null) {
console.log("row", rowBlocks);
return getIsSame(rowBlocks);
}
if (getIsSame(columnBlocks) != null) {
console.log("column", columnBlocks);
return getIsSame(columnBlocks);
}
if (getIsSame(slashBlocks) != null) {
console.log("slash", slashBlocks);
return getIsSame(slashBlocks);
}
if (getIsSame(backSlashBlocks) != null) {
console.log("backSlash", backSlashBlocks);
return getIsSame(backSlashBlocks);
}
}
};
const getIsSame = (items) => {
return items.every((item) => item === items[0] && item !== 2) ? items[0] : null;
};
console.log("Winner is: ", getWinners([
1, 1, 1, 2,
0, 1, 1, 2,
1, 1, 1, 2,
2, 2, 2, 2
], 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment