Home > Back-end >  Removing Duplicates of an Array in an Array That Has the Possible Sums of a Number
Removing Duplicates of an Array in an Array That Has the Possible Sums of a Number

Time:11-27

The sum Function

Problem

A beginner JS programmer here.

This question was created out of curiosity: I've created a function called sum in which takes value, a number, as an argument and returns the possible sums of that number, which was stored in variable a.

function sum(value) {
  let a = [];
  for(let i = 0; i <= value; i  ) {
    for(let j = 0; j <= value; j  ) {
      if(i   j === value) {
        a.push([i, j]);
      }
    }
  }
  return a;
}

Using sum(5) returns [[0, 5], [1, 4], [2, 3], [3, 2], [4, 1], [5, 0]].

The question is: is there any way to remove those duplicates?

Or I want sum(5), for example, to just return [[0, 5], [1, 4], [2, 3]].

What I Tried

I tried using a Set while using the variable a as an array of i and j, but since objects are unique, the Set, b, still stored the duplicate, resulting in a Set still storing those duplicates.

function sum(value) {
  let a;
  let b = new Set();
  for(let i = 0; i <= value; i  ) {
    for(let j = 0; j <= value; j  ) {
      a = [i, j]; // Forgot that objects are unique in JS.
      b.add(a);
    }
  }
  return b;
}

I've expected the Set to return the possible sums, but as I said, objects are unique in JS, so it still returned the duplicates.

CodePudding user response:

Although you could remove the duplicates afterwards using some methods, a nicer approach would be to instead iterate only over values that will definitely sum to the target - and to stop once halfway to the target, because after that, you'd be adding duplicates.

function sum(value) {
  const a = [];
  for(let i = 0; i <= value / 2; i  ) {
    a.push([i, value - i]);
  }
  return a;
}
console.log(sum(5));

  • Related