mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-22 16:43:46 +01:00
72 lines
1.5 KiB
JavaScript
72 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;
|
||
|
}
|