r/adventofcode • • Dec 02 '15

Spoilers Day 2 solutions

Hi! I would like to structure posts like the first one in r/programming, please post solutions in comments.

15 Upvotes

161 comments sorted by

View all comments

Show parent comment

1

u/Aneurysm9 Dec 02 '15

arr.map() should return a new array with the mapped values, so I'd do something like this:

function howMuchRibbon(arr) {
  return arr.map(function(item) {
    var box = item.split('x').map(function(len) {
      return parseInt(len, 10);
    });
    var cubed = box.reduce(function(a, b) {
      return a * b;
    });
    // find biggest number
    // maybe sort and pop the item from the end?
    var biggest = box.reduce(function(a, b) {
      return a > b ? a : b;
    });
    // remove biggest item from array
    box.splice(box.indexOf(biggest), 1);

    return cubed + (box[0] * 2) + (box[1] * 2);
  }).reduce(function(a,b) {
    return a + b;
  });
}

I haven't actually tested this and I'm not much of a javascript programmer, but it looks correct-ish! :)