I am trying to check for matching instances of arrays within a larger array. To do this, I am implementing a condition where if two of three numbers in an array match two of the three members of any of the arrays within a larger array, there is a continue statement to go back to a previous loop:
var threeSum = function (nums) {
let result = [];
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
loop1: for (let k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] === 0) {
let smallArray = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
for (let l = 0; l < smallArray.length && result[l]; l++) {
if (
smallArray[0] == result[l][0] &&
smallArray[1] == result[l][2]
) {
console.log("we already have this array")
continue loop1;
}
}
result.push(smallArray);
}
}
}
}
return result;
};
Thus, for example threeSum([-1, 0, 1, 2, -1, -4]) should return [[-1, 0, 1], [-1, -1, 2]] when is instead is returning [[-1, 0, 1], [-1, -1, 2], [-1, 0, 1]]. I have checked using the console.log in the inner most conditional, and the if statement is never returning as true, so it is never entering the continue command. But the first and third arrays should meet the requirements of this, so it seems as if when checking the third array, the function should kick back the command.
I am a bit puzzled as to what is going wrong.
A single loop approach but with recursion and filtering for arrays with same values.
function threeSum(array, temp = [], sum = 0, i = 0) {
if (temp.length === 3) return sum ? [] : [temp];
const result = [];
while (i < array.length) {
result.push(...threeSum(array, [...temp, array[i]], sum + array[i], ++i));
}
return result.filter((s => a => (b => !s.has(b) && s.add(b))([...a].sort().join('|')))(new Set));
}
console.log(threeSum([-1, 0, 1, 2, -1, -4]));