这是完整的问题描述
给定两个数组 a 和 b,编写一个函数 comp(a, b)(Clojure 中的 compSame(a, b))来检查这两个数组是否具有“相同”元素以及相同的重数。这里,“相同”意味着 b 中的元素是 a 平方中的元素,无论顺序如何。
示例
有效数组
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
comp(a, b)
返回 true
因为在 b
中:
- 121 是 11 的平方,
- 14641 是 121 的平方,
- 20736 144 的平方,
- 361 19 的平方,
- 25921 161 的平方,依此类推。
如果我们将 b 的元素写成平方,结果就很明显了:
无效数组
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
如果我们将第一个数字更改为其他数字,comp
可能不再返回true
:
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]
comp(a,b)
返回 false
,因为在 b
中,132 不是任意数量 a< 的平方
.
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361]
comp(a,b)
返回 false
,因为在 b
中,36100 不是任意数字 a 的平方。
备注
a
或b
可能是[]
(所有语言)。a
或b
可能为nil
或null
或None
(除非(Haskell、Elixir、C++、Rust)。- 如果
a
或b
为nil
(或 null 或 None),则问题没有意义,因此返回false
。 - 如果
a
或b
为空,结果本身就很明显。
C 注释
- 这两个数组具有相同的大小 (> 0),作为函数 comp 中的参数给出。
我的问题:
Can you come up with a test case where I do not meet the desired specefications??
I am stuck on 1 basic test not being passed (expected result: true but my code returns false)
我的代码尝试
function isTrue(el){
return el === true;
}
function comp(array1, array2){
if(array1.length === 0 || array2.length === 0){
return false;
}
var arr = array1.map(function(num){return num*num});
var arr2 = [];
for(var i = 0; i < arr.length; i++){
if(array2.includes(arr[i])){
arr2.push(true);
var a = array2.indexOf(arr[i]);
array2.splice(a,1);
} else{
arr2.push(false);
}
}
return arr2.includes(false) ? false : true;
}
最佳答案
最简单的方法:
const comp = (a1, a2) => {
if (!a1 || !a2 || a1.length !== a2.length) return false;
return a1.map(x => x * x).sort().toString() === a2.sort().toString();
}
关于javascript - 它们是 "same"吗?代码大战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45048414/