Repo for advent of code 2021 solutions.
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.

47 lines
1.3 KiB

#!/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}"