Answer the question
In order to leave comments, you need to log in
Algorithm for finding the winner (tic-tac-toe)?
Tell me the most effective algorithm for finding the winner in tic-tac-toe.
This is what I got myself:
function checkWinner(arr) {
let a = 0, b = 0, c = 0;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (arr[i][j] == 1) a++;
if (arr[i][j] == 2) a--;
if (arr[j][i] == 1) b++;
if (arr[j][i] == 2) b--;
if (i == 0 && arr[j][j] == 1 || i == 2 && arr[j][i - j] == 1) c++;
if (i == 0 && arr[j][j] == 2 || i == 2 && arr[j][i - j] == 2) c--;
}
if (a == 3 || b == 3 || c == 3) return 1;
if (a == -3 || b == -3 || c == -3) return 2;
a = 0;
b = 0;
c = 0;
}
return /0/.test(arr.join('')) ? -1 : 0;
}
checkWinner();
Answer the question
In order to leave comments, you need to log in
For any square dimension, the length of the matching characters is adjustable,
default is the length of the array
function checkWinner(arr, length) {
length = length || arr.length;
var winner = [
arr.map(row=>row.join('')).join(' '),
arr.map((_,v)=>arr.map(row=>row[v]).join('')).join(' '),
arr.map((_,v)=>arr[v][v]).join(''),
arr.map((_,v)=>arr[v][arr.length - v - 1]).join(''),
].join(' ').match('1'.repeat(length) + '|' + '2'.repeat(length));
return +((winner || ['0'])[0][0]);
}
function checkWinner(arr) {
function Eq(a, b, c) {
return a != 0 && a == b && a == c;
}
for (let i = 0; i < 3; i++) {
// check rows
if (Eq(arr[0][i], arr[1][i], arr[2][i])) {
return arr[0][i]
}
// check cols
if (Eq(arr[i][0], arr[i][1], arr[i][2])) {
return arr[i][0]
}
}
// check diagonal
if (Eq(arr[0][0], arr[1][1], arr[2][2])) {
return arr[0][0]
}
if (Eq(arr[0][2], arr[1][1], arr[2][1])) {
return arr[0][2]
}
return 0
}
I would designate the first player as a one, and the second as a four.
If the sum in a row, column or diagonal is 3 - the first one won, if it is 12 - the second one won.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question