他们是“相同"的吗?CodeWars [英] Are they the "same"? CodeWars
问题描述
完整说明在这里
给出两个数组a和b编写一个函数comp(a,b)(在Clojure中为compSame(a,b)),该函数检查两个数组是否具有相同"元素,并且具有相同的多重性.相同"在这里表示b中的元素是平方的元素,而与顺序无关.
Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.
示例
有效数组
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的元素,这将变得显而易见:
It gets obvious if we write b's elements in terms of squares:
无效的数组
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
:
If we change the first number to something else, comp
may not return true
anymore:
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
.
comp(a,b)
returns false
because in b
, 132 is not the square of any number of 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的平方.
comp(a,b)
returns false
because in b
, 36100 is not the square of any number of a.
备注
-
a
或b
可能是[]
(所有语言). -
a
或b
可能为nil
或null
或None
(除在Haskell,Elixir,C ++,Rust). - 如果
a
或b
为nil
(或者为null或无),则该问题没有任何意义,因此返回false
. - 如果
a
或b
为空,则结果是显而易见的.
a
orb
might be[]
(all languages).a
orb
might benil
ornull
orNone
(except in Haskell, Elixir, C++, Rust).- If
a
orb
arenil
(or null or None), the problem doesn't make sense so returnfalse
. - If
a
orb
are empty the result is evident by itself.
C的注释
- 两个数组具有相同的大小(> 0),这些大小在函数comp中作为参数给出.
我的问题:
您能提出一个我不符合要求的测试用例吗?规格?
Can you come up with a test case where I do not meet the desired specefications??
我被困于1个基本测试未通过(预期)结果:true,但是我的代码返回false)
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();
}
这篇关于他们是“相同"的吗?CodeWars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!