Advent of Code #9 (in Crystal)

sethcalebweeks

Caleb Weeks

Posted on December 9, 2023

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
💖 💪 🙅 🚩
sethcalebweeks
Caleb Weeks

Posted on December 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code #14 (in Crystal)
crystal Advent of Code #14 (in Crystal)

December 17, 2023

Advent of Code #12 (in Crystal)
crystal Advent of Code #12 (in Crystal)

December 17, 2023

Advent of Code #13 (in Crystal)
crystal Advent of Code #13 (in Crystal)

December 17, 2023

Advent of Code #11 (in Crystal)
crystal Advent of Code #11 (in Crystal)

December 12, 2023

Advent of Code #7 (in Crystal)
crystal Advent of Code #7 (in Crystal)

December 7, 2023