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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay