DEV Community

Cover image for Signals and Noise
Robert Mion
Robert Mion

Posted on • Updated on

Signals and Noise

Advent of Code 2016 Day 6

Part 1

No problem!

  • Another character-counting puzzle?
  • I feel like a master by now!
  • This may be a rare time where I chain together two reduce() methods - I've nested them inside one another before, but rarely used one right after another

My algorithm as pseudocode:

Split the input at each newline character into an array of strings
For each string, accumulate an array with as many empty objects as there are characters in the string
  Split each string into an array of characters
  For each character
    Increment the number associated with the character key in the object at the same index in the accumulating array as the character's in the string
For each object, accumulate a string
  The next character is the one who's key is associated with the largest number among all the keys in that object
Return the accumulated string
Enter fullscreen mode Exit fullscreen mode

My algorithm as JavaScript:

input.reduce(
 (counts, line) => {
  line.split('')
   .forEach(
    (char, i) => counts[i][char] = (counts[i][char] || 0) + 1
   )
  return counts
 }, new Array(stream[0].length).fill(null)
                               .map(el => Object.create({}))
).reduce(
 (message, tallies) => {
   return message += Object.entries(tallies)
    .find(
       (el) => el[1] == Math.max(...Object.values(tallies))
    )[0]
 }, ""
)
Enter fullscreen mode Exit fullscreen mode

It generated easter for the example, as expected!

It generated my correct answer, too!

Part 2

Change max to min

That's all I had to do to get the correct answer!

I refactored my algorithm to generate both answers:

function bothParts(fn) {
 input.reduce(
  (counts, line) => {
   line.split('')
    .forEach(
     (char, i) => counts[i][char] = (counts[i][char] || 0) + 1
    )
   return counts
  }, new Array(stream[0].length).fill(null)
                                .map(el => Object.create({}))
 ).reduce(
  (message, tallies) => {
    return message += Object.entries(tallies)
     .find(
        (el) => el[1] == fn(...Object.values(tallies))
     )[0]
  }, ""
 )
}
// Part 1: bothParts(Math.max)
// Part 2: bothParts(Math.min)
Enter fullscreen mode Exit fullscreen mode

Works great!

I did it!!

  • I solved both parts!
  • In what feels like record time for a Day 5 puzzle: under a half hour!
  • And with one long series of chained method calls in under 10 lines of code for the body of the function!
  • I even made a silly GIF to animate how my algorithm works!

Top comments (0)