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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay