You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
advent-of-code/2023/ruby/day_08.rb

27 lines
554 B

require "prime"
instructions, network = ARGF.read.split("\n\n")
network = network
.scan(/(\w+) = \((\w+), (\w+)\)/)
.to_h { [_1, { L: _2, R: _3 }] }
steps = ->(start, finish) {
node = start
instructions.chars.map(&:to_sym)
.cycle.with_index.lazy
.filter_map {|dir, i|
node = network.fetch(node).fetch(dir)
(node =~ finish) ? i+1 : nil
}
.first
}
# part one
p steps.("AAA", /ZZZ/)
# part two
nodes = network.keys.select { _1.end_with?(?A) }
node_steps = nodes.map { steps.(_1, /Z$/) }
p node_steps.inject(1, :lcm)