'Function to verify if the values in the second array correspond to the square values of the first array using Javascript
I have problem with the if-else statement and also splice seems to be not working.
function same(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
let correctIndex = arr1[i] * 2;
if (correctIndex !== arr2[j]) {
return false;
}
}
console.log(arr2);
arr2.splice(correctIndex, 1)
}
return true;
}
same([1, 2, 3, 2], [9, 1, 4, 4]);
Solution 1:[1]
try this:
const sortNumber = numArray => numArray.sort((a, b) => a - b);
const same = (_arr1, _arr2) => {
const arr2 = sortNumber(_arr2);
return sortNumber(_arr1).every((res,i)=>arr2[i]===res**2);
}
console.log(same([1, 2, 3, 2], [9, 1, 4, 4]))
Solution 2:[2]
You need to loop through the first array, referencing the corresponding index in the second array. You can return false as soon as you find an entry that is not a square.
function same(arr1, arr2){
if(arr1.length !== arr2.length) return false;
arr1.sort();
arr2.sort();
// visit each item in arr1 exactly once
for(let i=0; i<arr1.length; i++){
// if entry at arr2 isn't the square of that entry in arr1, return false immediately
if(arr1[i] * arr1[i] !== arr2[i]) return false;
}
// we've checked each item, return true
return true;
}
There's no need to use splice() here since you only need to return true or false, not modify either array. Also, you don't need to use nested for loops, since you can access each array directly.
Solution 3:[3]
You can also check using the method of frequency counter in O(n) complexity.
function same(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
let fc1 = {};
let fc2 = {};
for (let val of arr1) {
fc1[val] = (fc1[val] || 0) + 1;
}
for (let val of arr2) {
fc2[val] = (fc2[val] || 0) + 1;
}
for (let key in fc1) {
if (!(key ** 2 in fc2)) {
return false;
}
if (fc1[key] !== fc2[key ** 2]) {
return false;
}
}
return true;
}
Solution 4:[4]
You don't need nested loops for this. Here's a one-pass algorithm with a single for loop
function same(arrOne, arrTwo) {
if (arrOne.length === arrTwo.length) {
let totalOne = 0;
let totalTwo = 0;
for (let x = 0; x < arrOne.length; x++) {
totalOne += arrOne[x] ** 2;
totalTwo += arrTwo[x];
}
if (totalOne === totalTwo) {
return true;
} else return false;
}
return false;
}
console.log(same([-1, -2, -3], [4, 1, 9]));
console.log(same([1, 2, 3], [1, 9]));
console.log(same([4, 5, 6], [16, 25, 36]));
console.log(same([1, 2, 3, 2], [9, 1, 4, 4]));
This handles even the case where the items in the second array are not in order.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Sebastian Simon |
| Solution 4 | Naser Mohd Baig |
