[英]CodeWars Javascript Challenge: Are they the “same”?
卡塔: 链接
我的解决方案:
function comp(array1, array2) {
let result;
if (Array.isArray(array1) && Array.isArray(array2) && array1.length && array2.length) {
result = true;
const squares = array2.map(e => Math.sqrt(e));
squares.forEach((e) => {
if (array1.includes(e)) return;
result = false;
});
} else {
result = false
}
return result;
}
我不想要另一个解决方案。 我想弄清楚为什么我的没有通过所有的测试。 (两次测试失败,但我看不到哪个)
我怀疑如果 arrays 都是[]
,则测试期望为true
。 但 Kata 的描述另有说明:
如果 a 或 b 为 nil(或 null 或 None),则问题没有意义,因此返回 false。
帮助将不胜感激。
工作解决方案基于答案:
function comp(array1, array2) {
let result;
if (Array.isArray(array1) && Array.isArray(array2)) {
result = true;
const sortedArray1 = array1.sort((a, b) => a - b);
const squares = array2.map(e => Math.sqrt(e)).sort((a, b) => a - b);
squares.forEach((e, i) => {
if (sortedArray1[i] === e) return;
result = false;
});
} else {
result = false
}
return result;
}
如果有多个相同的数字,但这里和那里的计数不同,它将在您的代码中返回 true,因为它includes
在 arrays 中。 您应该对其进行排序并按索引迭代以进行比较,以确保数组中的每个项目仅使用一次。
这对我有用:
function comp(array1, array2){
if(!array1 || !array2) return false;
array1 = array1.map(t => t**2).sort((a,b)=>a-b);
array2 = array2.sort((a,b)=>a-b);
for(let i=0;i<array1.length;i++){if(array1[i] !== array2[i])return false}
return true;
}
确保你能理解这个想法,并在你现有的代码中做一些调整
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.