Ruby's standard library makes this so easy

This commit is contained in:
Bill Rossi 2025-11-25 20:54:42 -05:00
parent 29a614dc60
commit 384f4a28e5

55
ruby/2017/2/problem.rb Normal file
View File

@ -0,0 +1,55 @@
class Row
attr_reader :values
def initialize(values)
@values = values.sort.reverse
end
def self.for(string)
new string.split("\t").map(&:to_i)
end
def to_s
values.to_s
end
def difference
values.first - values.last
end
def quotient
x, y = values.combination(2).find { |a, b| a % b == 0 }
x / y
end
end
class Spreadsheet
attr_reader :rows
def initialize(rows)
@rows = rows
end
def self.for(string)
new string.split("\n").map{ |row| Row.for row }
end
def to_s
rows.map(&:to_s).join("\n")
end
def checksum
rows.map(&:difference).sum
end
def evenly_divisible_values
rows.map(&:quotient).sum
end
end
sheet = Spreadsheet.for STDIN.read.chomp
part_1 = sheet.checksum
puts "Part 1: #{part_1}"
part_2 = sheet.evenly_divisible_values
puts "Part 2: #{part_2}"