Multi-dimensional Array - Check For Diagonal Consecutive Values
Writing a check for an array to determine if there are any potential consecutive values within it, be it horizontal, vertical, or either way diagonal. The example below is a sample
Solution 1:
Have you tried:
(b[i][j]==="X" && i===j) ? dl++ : 0;
(b[j][i]==="X" && (i+j)===(len-1)) ? dr++ : 0;
?
dl
or the left diagonal would have i
and j
equal(so (0,0) (1,1) and (2,2))
dr
or the right diagonal would have the sum of i
and j
equal to side-length minus 1(so (0,2) (1,1) (2,0))
This would work when the length of the diagonal is the same as the length of the matrix, full-body diagonal in a tic-tac-toe game, for example. For partial diagonals you can modify the code slightly to something like:
var diff = 0;
var sum = len - 1;
(b[i][j]==="X") ? diff = (i-j) : diff = 0;
(b[i][j]==="X") ? sum= (i+j) : sum = len;
(b[i][j]==="X" && (i-j)===diff) ? dl++ : 0;
(b[j][i]==="X" && (i+j)===sum) ? dr++ : 0;
Solution 2:
Final answer (due to @tewathia's answer and some further research)
function testWin() {
var win=3, len=b.length, r=0, c=0, dr=0, dl=0;
for(var i=0;i<len;i++){
for(var j=0;j<len;j++){
(b[j][i]==="X") ? c++ : c=0;
(b[i][j]==="X") ? r++ : r=0;
if(b[i][j]==="X" && i<len-win+1){ dr=0; dl=0;
for(var z=0;z<win;z++){
(b[i+z][j+z]==="X") ? dr++ : dr=0;
(b[i+z][j-z]==="X") ? dl++ : dl=0;
}
}
if(c===win || r===win || dr===win || dl===win){ alert("YOU WIN!"); return true;}
} r=0;
}
}
Post a Comment for "Multi-dimensional Array - Check For Diagonal Consecutive Values"