DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 1: Report Repair

Collapse
willsmart profile image
willsmart

Yep, this'll be another year fighting the urge to pre-optimise xmas code 🤦

Anyway, here's a nice efficient implementation in JS... (linear for part one, which is nice. Square for part two which could be improved but, like, why?)

const input = JSON.parse(require('fs').readFileSync('1a.json', 'utf-8'));

// sort ascending
input.sort((a, b) => a - b);


function go(c, tgt) {
  // tgt is the target sum we're aiming for
  // a is an index which moves through the array, 
  // b is ahead of a but retreats to maintain a sum <= to target.

  for (let a = c, b = input.length - 1; a < input.length; a++) {
    let { [a]: av, [b]: bv } = input;
    while (av + bv > tgt && b >= a) bv = input[--b];
    if (av + bv == tgt) return { a, b };
  }
}

let res;
// Part 1
(res = go(0, 2020)) &&
  console.log({
    part: 1,
    sum: input[res.a] + input[res.b],
    prod: input[res.a] * input[res.b],
  });

// Part 2
for (const c in input)
  (res = go(c, 2020 - input[c])) &&
    console.log({
      part: 2,
      sum: input[res.a] + input[res.b] + input[c],
      prod: input[res.a] * input[res.b] * input[c],
    });
Enter fullscreen mode Exit fullscreen mode
Collapse
willsmart profile image
willsmart

I'm liking Ryan's idea of using this to practice new languages and get out of the comfort zone (though JS is just so comfy now 😌 )
Plan is to make myself a twister-style spinner with 5 or so languages, and force myself to use whichever one the arrow lands on on the day.