Skip to content

Instantly share code, notes, and snippets.

@safiire
Last active December 3, 2023 21:17
Show Gist options
  • Save safiire/3cbb87a31119265e0d9df29a9181c77f to your computer and use it in GitHub Desktop.
Save safiire/3cbb87a31119265e0d9df29a9181c77f to your computer and use it in GitHub Desktop.
Advent of Code 2023 Day 2
#!/usr/bin/env ruby
INPUT_FILE = 'part_one.input'
View = Data.define(:r, :g, :b) do
REGEX = /(\d+) red|(\d+) green|(\d+) blue/
def total = r + g + b
def power = r * g * b
def +(o) = self.class[r + o.r, g + o.g, b + o.b]
def self.zero = self[0, 0 ,0]
def self.parse(string)
string.scan(REGEX).reduce(self.zero) do |sum, (r, g, b)|
sum + new(r: r.to_i, g: g.to_i, b: b.to_i)
end
end
def possible?(bag)
!(total > bag.total || r > bag.r || g > bag.g || b > bag.b)
end
def smoosh(o)
self.class[
(r > o.r) ? r : o.r,
(g > o.g) ? g : o.g,
(b > o.b) ? b : o.b
]
end
end
Game = Data.define(:id, :views) do
def self.parse(string)
_, id, body = string.match(/Game (\d+): (.+)/).to_a
views = body.split(';').map { |view| View.parse(view) }
self.new(id: id.to_i, views: views)
end
def possible?(bag)
views.all? { |view| view.possible?(bag) }
end
end
bag = View[12, 13, 14]
games = File.read(INPUT_FILE).split("\n").map do |line|
Game.parse(line)
end
possible = games.select { |game| game.possible?(bag) }
puts "The sum of possible game ids is #{possible.map(&:id).sum}"
sum = games.map do |game|
game.views.reduce(View.zero) do |sum, view|
sum.smoosh(view)
end.power
end.sum
puts "The sum of the power of smooshed sets is #{sum}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment