Advent of Code – Day 2 – Functional Solution

Advent of Code – Day 2 – Functional Solution

Reading Time: 6 minutes

So a great blog (To Code [Hebrew]) that I follow started a social coding challenge which involve solving AOC challenges together and sharing the code. I posted my solution for the first challenge and Ynon made me think differently a bit on how to solve the challenges. He made me think more functional when solving this kind of problems. The key in functional thinking is that for each input of piece of smaller problem out of the bigger problem you get the output and you can chain those actions to make them work as a pipeline to solve the bigger problem. So I’ll try to post the way I think, and the way I tackled the 2nd day challenge.

The problem

TL;DR the problem is to get as an input a spreadsheet of numbers. The output should be the sum of the differences of the max and min value of each row. For example:

My solution

The input in the real AOC challenge that I got (each user gets different input, so copy my answer won’t help you :)) is:

Well first thing after understanding the problem is to divide the big problem into small problems. So I start by creating a list of the tasks I should do get it work:

  1. get each line to be a value in an array so we can model it as follows
  2. each line in the array should be an array of the numbers in the line
  3. sort each line so you get the max and min values in the corners
  4. zip each line to include only the max and min values (could be combined with step 3)
  5. zip the difference on each line into one value, the cool feature used here is called deconstructing assignment (thank you Ynon), much more readable way to access known size array
  6. sum the lines and return the result

Solution

36766

P.S

There is nothing wrong with declaring or extending the javascript’s Array prototype and adding custom helper functions in order to create even more readable and declarative code.

cheers,