advent_of_code/2023_2.rb
Code:
# Advent of Code 2023, Day 2: Cube Conundrum
# https://adventofcode.com/2023/day/2
require_relative './helpers.rb'
MAX_RED = 12
MAX_GREEN = 13
MAX_BLUE = 14
def parse(dataset)
result = {}
dataset.each do |line|
game, pulls = line.split(': ')
result[game.split(' ')[1].to_i] = pulls.split('; ').map { |x| x.split(', ') }
end
return result
end
def part_one(dataset)
sum = 0
parse(dataset).each do |game, rounds|
valid = true
rounds.each do |pulls|
r = g = b = 0
pulls.each do |pull|
n, color = pull.split(' ')
r += n.to_i if color == 'red'
g += n.to_i if color == 'green'
b += n.to_i if color == 'blue'
end
valid = false if (r > MAX_RED) || (g > MAX_GREEN) || (b > MAX_BLUE)
end
sum += game if valid
end
return sum
end
def part_two(dataset)
sum = 0
parse(dataset).each do |game, rounds|
min_r = min_g = min_b = 0
rounds.each do |pulls|
r = g = b = 0
pulls.each do |pull|
n, color = pull.split(' ')
r += n.to_i if color == 'red'
g += n.to_i if color == 'green'
b += n.to_i if color == 'blue'
end
min_r = [r, min_r].max
min_g = [g, min_g].max
min_b = [b, min_b].max
end
sum += min_r * min_g * min_b
end
return sum
end
example_data = get_dataset(year: 2023, day: 2, type: 'example')
input_data = get_dataset(year: 2023, day: 2, type: 'input')
# puts "Part One: #{part_one(example_data)}"
# puts "Part Two: #{part_two(example_data)}"
puts "Part One: #{part_one(input_data)}"
puts "Part Two: #{part_two(input_data)}"
Output:
Part One: 2317
Part Two: 74804