twhite96
7/14/2017 - 11:29 PM

From https://www.reddit.com/r/dailyprogrammer/comments/6melen/20170710_challenge_323_easy_3sum/

//sum3.js
const sum3 = seq => {
  const table = new Map(); // key: number in seq, value: true if key has duplicates false otherwise
  const out = [];
  const len = seq.length;

  if (len === 0) {
    return out;
  }

  seq.reduce((aggr, next, index) => {
    if (!aggr.has(next)) {
      aggr.set(next, false);
    }
    else if (!aggr.get(next)) {
      aggr.set(next, true)
    }
    return aggr;
  }, table);

  for (let i = 0; i < len; i++) {
    for (let j = i + 1; j < len; j++) {
      let toFind = -(seq[i] + seq[j]);
      if (table.has(toFind)) {
        if(toFind !== seq[i] && toFind !==seq[j]) {
          out.push([seq[i], seq[j], toFind]);
        }
        else if(table.get(toFind)) {
          out.push([seq[i], seq[j], toFind]);
        }
      }
    }
  }

  return out;
}

const removeDup = sums => new Set(sums.map(s => s.sort((a, b) => a - b).join(" ")));

let input = [
  "9 -6 -5 9 8 3 -4 8 1 7 -4 9 -9 1 9 -9 9 4 -6 -8",
  "4 5 -1 -2 -7 2 -5 -3 -7 -3 1",
  "-1 -6 -3 -7 5 -8 2 -8 1",
  "-5 -1 -4 2 9 -9 -6 -1 -7"
];

let out = input
  .map(str => removeDup(sum3(str.split(" ")
    .map(n => parseInt(n, 10))))
  );

console.log(out);