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_02.rb

40 lines
738 B

10 months ago
input = ARGF.read
10 months ago
def parse_cubes(input)
10 months ago
input
.scan(/(\d+) (\w+)/)
.to_h(&:reverse)
.transform_values(&:to_i)
end
10 months ago
bag = parse_cubes("12 red cubes, 13 green cubes, and 14 blue cubes")
10 months ago
Game = Data.define(:id, :reveals) do
def possible?(bag)
reveals.all? {|reveal|
bag.all? {|color, n| n >= reveal.fetch(color, 0) }
}
end
end
games = input
.scan(/^Game (\d+): ((?~\n))/)
.map {|id, reveals|
Game.new(
id.to_i,
10 months ago
reveals.split(?;).map { parse_cubes(_1) }
10 months ago
)
}
# part one
p games.select { _1.possible?(bag) }.sum(&:id)
# part two
p games
.map {|game|
game.reveals.inject {|bag, reveal|
bag.merge(reveal) { [_2, _3].max }
}
}
.sum {|bag| bag.values.inject(:*) }