DEV Community

Caleb Weeks
Caleb Weeks

Posted on

Advent of Code #9 (in Crystal)

The confusing year of Advent of Code continues... I thought weekend puzzles were meant to be harder than weekday puzzles, but today seemed like another soft ball. I suppose it nudged you towards a recursive solution, but it wasn't all that difficult once I wrapped my head around the recursion aspect. In previous years, there seemed to be a steeper ramp up in difficulty, but this year started a little harder than usual and hasn't really climbed as fast.

So after live streaming my solutions to today's puzzle, I went on to refactor my code (also livestreamed). I really like how the code turned out, using a combination of OOP and FP.

Here it is!

input = File.read("input").strip

dataset = input.split("\n").map(&.split(" ").map(&.to_i))

class Array

  def differences
    (1..(self.size - 1)).map do |x|
      self[x] - self[x - 1]
    end
  end

  def extrapolate(direction = 1)
    if self.uniq.size == 1
      self[0]
    else
      differences = self.differences
      if direction == 1
        self[-1] + differences.extrapolate
      else
        self[0] - differences.extrapolate(-1)
      end
    end
  end

end

part1 = dataset.map(&.extrapolate).sum
puts part1

part2 = dataset.map(&.extrapolate(-1)).sum
puts part2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)