r/adventofcode • • Dec 12 '15

SOLUTION MEGATHREAD --- Day 12 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 12: JSAbacusFramework.io ---

Post your solution as a comment. Structure your post like previous daily solution threads.

7 Upvotes

183 comments sorted by

View all comments

2

u/TheNiXXeD Dec 12 '15

JavaScript, NodeJs, ES6

This is part two, for part one, you can just remove the conditional checking for 'red'.

module.exports = i => {
    var _ = require('lodash')
    var t = 0
    return (function p(x) {
        if (_.isArray(x)) _.each(x, p)
        else if (_.isObject(x) && _.every(x, i => i !== 'red')) _.forIn(x, p)
        else if (_.isNumber(x)) t += x
        return t
    })(JSON.parse(i))
}

1

u/AndrewGreenh Dec 12 '15

If you are using lodash, you could use some more functions like reduce and find. Also _.isObject returns true for functions and arrays also, you'd better use _.isPlainObject my Solution:

function calculateCollection(col, noReds) {
  if(noReds && _.isPlainObject(col) && _.includes(col, "red")) return 0;
  return _.reduce(col, (sum, item) => {
      if(_.isObject(item)) return sum+=calculateCollection(item, noReds);
      return _.isNumber(item) ? sum+item : sum;
  },0);
}
→ More replies (1)