Consider an array whose length will be always product of two numbers. For below array l is 4 and w is 5.
There is also a given index. I want to get the two arrays containing elements which lie on the diagonal line which passes through that particular index.
[
0, 1, 2, 3, 4
5, 6, 7, 8, 9
10, 11, 12, 13, 14
15, 16, 17, 18, 19
]
index = 7 => [3, 7, 11, 15] and [1, 7, 13, 19]
index = 16 => [4, 8, 12, 16] and [10, 16]
index = 0 => [0, 6, 12, 18] and [0]
I have tried following:
let arr = Array(20).fill().map((x,i) => i);
function getDias(arr, l, w, ind){
let arr1 = [];
let arr2 = [];
for(let i = 0;i<l;i++){
arr1.push(arr[ind + (i * w) + i])
arr1.push(arr[ind - (i * w) - i])
arr2.push(arr[ind + (i * w) + i])
arr2.push(arr[ind - (i * w) - i])
}
const remove = arr => [...new Set(arr.filter(x => x !== undefined))];
return [remove(arr1),remove(arr2)];
}
console.log(getDias(arr, 4, 5, 7))
The code have two problems. Both the arrays in the result are same. And secondly they are not in order.
Note: I don't want to use sort() to reorder the array. And also I don't want loop through all 20 elements. Just want to get the elements of that diagonal row