re: AoC Day 1: Chronal Calibration VIEW POST

VIEW FULL DISCUSSION

Thanks for this Ryan! I've joined the leaderboard. Good luck to everyone!

Here's my solution in Crystal, both parts are included as one class:

class Device
  getter frequency : Int32
  getter duplicate : Int32 | Nil

  def initialize
    @frequency = 0
    @duplicate = nil
    @frequencies = Set{@frequency}
  end

  def update(input : Array(String))
    @frequency = input.map { |string| string.to_i }.reduce(@frequency) do |acc, i|
      frequency = acc + i
      @duplicate = frequency if @frequencies.includes?(frequency) && @duplicate.nil?
      @frequencies.add(frequency)
      frequency
    end
  end

  def find_duplicate(input : Array(String))
    while @duplicate.nil?
      update(input)
    end
  end
end


puts "--- Day 1: Chronal Calibration ---"
input = File.read_lines("./01/input.txt")
device = Device.new
device.update(input)
puts "Frequency result: #{device.frequency}"
device.find_duplicate(input)
puts "Frequency first duplicates at: #{device.duplicate}"

There are also tests here.

code of conduct - report abuse