56 lines
851 B
Ruby
56 lines
851 B
Ruby
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}"
|