AoC2021/day04/solution.rb

48 lines
1.3 KiB
Ruby
Raw Normal View History

2021-12-04 20:22:11 +00:00
#!/bin/env ruby
require 'pry'
# Part 1
def bingo?(line)
line.select { _1.nil? }.count == line.count
end
bingo = File.readlines('./input')
draws = bingo[0].strip.split(',').map(&:to_i)
cards = bingo[1..-1].reject { _1 == "\n" }.map(&:strip)
.each_slice(5)
.map { |card| card.map { _1.split(' ').map(&:to_i) } }
winner = nil
last_draw = 0
catch :bingo do
draws.each do |draw|
last_draw = draw
cards.map! { _1.map! { |row| row.map! { |number| number == draw ? nil : number } } }
cards.each do |card|
card.each { |line| winner = card if bingo?(line) }
card.transpose.each { |line| winner = card if bingo?(line) }
throw :bingo unless winner.nil?
end
end
end
score = winner.flatten.reject(&:nil?).sum * last_draw
puts "Winning Board Score: #{score}"
# Part 2
catch :last_winner do
draws.each do |draw|
last_draw = draw
winner = nil
cards.map! { _1.map! { |row| row.map! { |number| number == draw ? nil : number } } }
cards.each do |card|
card.each { |line| winner = card if bingo?(line) }
card.transpose.each { |line| winner = card if bingo?(line) }
cards.delete(winner) unless winner.nil?
end
throw :last_winner if cards.count == 0
end
end
score = winner.flatten.reject(&:nil?).sum * last_draw
puts "Last Winning Board Score: #{score}"