2025! Ruby, day 1

This commit is contained in:
Bill Rossi 2025-12-01 04:03:24 -05:00
parent 5453166f0e
commit 7c063782df
4 changed files with 130 additions and 0 deletions

6
ruby/2025/1/bin/problem Normal file
View File

@ -0,0 +1,6 @@
#/usr/bin/env ruby
require "combination"
combination = Combination.for STDIN.read.chomp
puts "Part 1: #{combination.zero_count}"
puts "Part 2: #{combination.zero_click_count}"

View File

@ -0,0 +1,65 @@
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

View File

View File

@ -0,0 +1,59 @@
require "minitest/autorun"
require "combination"
TEST_COMBINATION = <<END
L68
L30
R48
L5
R60
L55
L1
L99
R14
L82
END
class TestCombination < Minitest::Test
def test_safe
safe = Combination::Safe.new
assert_equal 50, safe.count
assert_equal 0, safe.zero_clicks
safe.apply_step Combination::Step.for("L68")
assert_equal 82, safe.count
assert_equal 1, safe.zero_clicks
safe.apply_step Combination::Step.for("L30")
assert_equal 52, safe.count
assert_equal 1, safe.zero_clicks
safe.apply_step Combination::Step.for("R48")
assert_equal 0, safe.count
assert_equal 2, safe.zero_clicks
safe.apply_step Combination::Step.for("R300")
assert_equal 0, safe.count
assert_equal 5, safe.zero_clicks
safe.apply_step Combination::Step.for("L602")
assert_equal 98, safe.count
assert_equal 11, safe.zero_clicks
0.upto(99) do |count|
safe = Combination::Safe.new
safe.apply_step Combination::Step.for("L50")
safe.apply_step Combination::Step.new("R", count)
assert_equal count, safe.count
assert_equal 1, safe.zero_clicks
end
end
def test_zero_count
combination = Combination.for TEST_COMBINATION
assert_equal 3, combination.zero_count
end
def test_zero_clicks
combination = Combination.for TEST_COMBINATION
assert_equal 6, combination.zero_click_count
combination = Combination.for "R1000"
assert_equal 10, combination.zero_click_count
end
end