1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/5kyu/tic_tac_toe_checker/solution.js
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

71 lines
1.5 KiB
JavaScript

function checkEmpty(board) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] === 0) {
return true;
}
}
}
}
function checkColumn(board, column) {
for (let i = 1; i < 3; i++) {
if (board[i - 1][column] !== board[i][column]) {
return 0;
}
}
return board[0][column];
}
function checkRow(board, row) {
for (let i = 1; i < 3; i++) {
if (board[row][i - 1] !== board[row][i]) {
return 0;
}
}
return board[row][0];
}
function checkDiagonal(board) {
let leftToRight = true;
let rightToLeft = true;
for (let i = 1; i < 3; i++) {
if (board[i - 1][i - 1] !== board[i][i]) {
leftToRight = false;
}
if (board[i - 1][3 - i] !== board[i][2 - i]) {
rightToLeft = false;
}
}
if (leftToRight) {
return board[0][0];
} else if (rightToLeft) {
return board[0][2];
} else {
return 0;
}
}
function isSolved(board) {
for (let i = 0; i < 3; i++) {
const col = checkColumn(board, i);
const row = checkRow(board, i);
if (col != 0) {
return col;
} else if (row != 0) {
return row;
}
}
const diagonal = checkDiagonal(board);
if (diagonal != 0) {
return diagonal;
}
if (checkEmpty(board)) {
return -1;
}
return 0;
}