Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get diagonal numbers between two number in a matrix?

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.

like image 737
Maheer Ali Avatar asked May 07 '19 09:05

Maheer Ali


People also ask

How do you find the diagonal value of a matrix?

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.

How many diagonals does a 3 by 3 matrix have?

For example, in a 3x3 board, there should be 2 possible diagonal sequences, but the formula calculates only 1.

How do you find the secondary diagonal of a matrix?

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.


1 Answers

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))
like image 98
apple apple Avatar answered Nov 15 '22 13:11

apple apple