Mah*_*Ali 12 javascript arrays algorithm
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
]
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Can some give a simple solution to it.
app*_*ple 13
只需获取col和row,并检查delta是否相同。
(实际上并不需要采用数组,所以我只是采用维度)
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))
Run Code Online (Sandbox Code Playgroud)
You could take the absolute delta and check with the remainder operator if the delta is multiple of the length minus one or plus one.
function check(array, i, j) {
var length = Math.sqrt(array.length),
delta = Math.abs(i - j),
lines = Math.abs(Math.floor(i / length) - Math.floor(j / length));
return delta === lines * (length - 1) || delta === lines * (length + 1);
}
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
console.log(check(array, 0, 15)); // true
console.log(check(array, 3, 12)); // true
console.log(check(array, 11, 6)); // true
console.log(check(array, 9, 6)); // true
console.log(check(array, 4, 15)); // false
console.log(check(array, 8, 12)); // false
console.log(check(array, 8, 3)); // false
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)