aoc_omni/ruby/2025/1/lib/combination.rb
2025-12-01 04:03:24 -05:00

66 lines
1.2 KiB
Ruby

class Combination
attr_reader :steps
def initialize(steps)
@steps = steps
end
def self.for(string)
new string.split("\n").map{ |line| Step.for line }
end
def zero_count
safe = Safe.new
zc = 0
steps.each do |step|
safe.apply_step step
zc += 1 if safe.count.zero?
end
zc
end
def zero_click_count
safe = Safe.new
steps.each do |step|
safe.apply_step step
end
safe.zero_clicks
end
class Step
attr_reader :dir, :count
def initialize(dir, count)
@dir = dir
@count = dir == "R" ? count : -count
end
def self.for(string)
new string[0], string[1..].to_i
end
end
class Safe
attr_reader :count
attr_reader :zero_clicks
def initialize
@count = 50
@zero_clicks = 0
end
def apply_step(step)
if step.dir == "R"
0.upto(step.count - 1) do
@count += 1
@count = @count % 100
@zero_clicks += 1 if @count.zero?
end
else
0.upto(-step.count - 1) do
@count -= 1
@count = @count % 100
@zero_clicks += 1 if @count.zero?
end
end
end
end
end