如何检查方阵的两个索引是否彼此对 Angular 。考虑数组。
[
0 , 1 , 2 , 3 ,
4 , 5 , 6 , 7 ,
8 , 9 , 10, 11,
12, 13, 14, 15
]
创建一个接受三个参数数组和两个索引的函数。如果两个索引彼此成对 Angular 线,它应该返回一个 true
,否则返回 false
对于上面的数组。
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.
我试图创建一个函数,但它根本不起作用。
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
}
有人能给出一个简单的解决方案吗
最佳答案
只需获取列和行,并检查增量是否相同。
(真的不需要取数组,所以我只取它的维度)
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))
关于javascript - 如何获得矩阵中两个数字之间的对 Angular 线数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019344/