How to check if two indexes of a square matrix are diagonal to each other. Consider the array.
[
0 , 1 , 2 , 3 ,
4 , 5 , 6 , 7 ,
8 , 9 , 10, 11,
12, 13, 14, 15
]
Create a function which takes three parameters array and two indexes. It should return a true
if two indexes are diagonal to each other otherwise return false
For above array.
0,15 => true
3,12 => true
11,6 => true
9,6 => true
4,15 => false
8,12 => false
1,10 => false //my code fails for this.
I have tried to create a function but it doesnot work at all.
function check(arr,a,b){
let len = Math.sqrt(arr.length);
let dif = Math.abs(a-b);
return dif % (len+1) === 0 || dif % (len - 1) === 0
}
Can some give a simple solution to it.
D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.
For example, in a 3x3 board, there should be 2 possible diagonal sequences, but the formula calculates only 1.
Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30. Condition for Secondary Diagonal: The row-column condition is row = numberOfRows – column -1.
simply get the col and row, and check if delta is the same.
(don't really need to take an array, so I just take it's dimension)
function check(dim,a,b){
let [x1,y1]=[Math.floor(a/dim),a%dim]
let [x2,y2]=[Math.floor(b/dim),b%dim]
return Math.abs(x1-x2)==Math.abs(y1-y2)
}
console.log(check(4,0,15))
console.log(check(4,3,12))
console.log(check(4,11,6))
console.log(check(4,9,6))
console.log(check(4,4,15))
console.log(check(4,8,12))
console.log(check(4,6,12))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With