4 回答

TA貢獻1783條經驗 獲得超4個贊
使用everyand includes,這可以用一個簡單的單線寫成:
const a = [121, 144, 19, 161, 19, 144, 19, 11]
const b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
const comp = (a, b) => a.length === b.length && a.every(value => b.includes(value ** 2))
console.log(comp(a, b))
非常明確,此函數檢查兩個數組是否具有相同的長度,以及asquared 的每個值是否都包含在b.

TA貢獻1859條經驗 獲得超6個贊
您的代碼幾乎適用于測試用例。您只需在內部交換數組:
function comp(array1, array2){
return array1.every((item)=>{
let a = array2.indexOf((item ** 2));
if(a >=0){
return true;
} else{
return false;
}
})
}
雖然如果我理解正確,即使數組具有不同的長度,或者如果第二個數組的元素不是第一個元素的多重性,只要第一個在第二個中具有一些多重性,這將返回 true:
console.log(comp([2,4,4,2], [4,16]));
// -> true
console.log(comp([2,4], [4,16, 536]));
// -> true
因此,要忠實于前提,避免 indexOf 或包括:
function comp2(A, B){
if(A.length != B.lengt) return false;
A.sort((a, b) => a-b);
B.sort((a, b) => a-b);
return A.every((a, i)=>{
const b = B[i];
if(a ** 2 == b){
return true;
} else{
return false;
}
})
}
console.log(comp2([2,4,4,2], [4,16]));
// -> false
console.log(comp2([2,4], [4,16, 536]));
// -> false
游樂場:https ://jsfiddle.net/alotropico/9ukmL5g3/13/

TA貢獻1842條經驗 獲得超21個贊
使用 every 和 a set 刪除重復項
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
function compare(a,b){
a=[...new Set(a)]
b=new Set(b)
return a.every(x=>b.has(x*x))
}
console.log(compare(a,b))
添加回答
舉報