Define a function comp(a, b) (also called compSame(a, b) in Clojure) that determines whether two arrays a and b have the same elements with the same multiplicities. In this case, "same" means that every element in array b is the square of an element in array a, regardless of the order.
Examples
Valid arrays
a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
The function
comp(a, b)
should return true because each element in b is the square of the corresponding element in a. For example, 121 is the square of 11, 14641 is the square of 121, 20736 is the square of 144, and so on.
Initially, I attempted to compare each item in one array to its squared version in the other array. Here's the code I used:
function comp(array1, array2){
return array2.every((item)=>{
let a = array1.indexOf((item ** 2));
if(a >=0){
return true;
} else{
return false;
}
})
}
console.log(comp([121, 144, 19, 161, 19, 144, 19, 11], [121, 14641, 20736, 361, 25921, 361, 20736, 361]));
It is expected that this example will return true, but the function does not work as intended. Additionally, when an empty array is used as the second argument, the function incorrectly returns false.