[2023][ruby][3.1]

main
Alpha Chen 11 months ago
parent 5e542d90aa
commit 6581325e8f
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,13 +1,13 @@
input = ARGF.read input = ARGF.read
def cubes(input) def parse_cubes(input)
input input
.scan(/(\d+) (\w+)/) .scan(/(\d+) (\w+)/)
.to_h(&:reverse) .to_h(&:reverse)
.transform_values(&:to_i) .transform_values(&:to_i)
end end
bag = cubes("12 red cubes, 13 green cubes, and 14 blue cubes") bag = parse_cubes("12 red cubes, 13 green cubes, and 14 blue cubes")
Game = Data.define(:id, :reveals) do Game = Data.define(:id, :reveals) do
def possible?(bag) def possible?(bag)
@ -22,7 +22,7 @@ games = input
.map {|id, reveals| .map {|id, reveals|
Game.new( Game.new(
id.to_i, id.to_i,
reveals.split(?;).map { cubes(_1) } reveals.split(?;).map { parse_cubes(_1) }
) )
} }

@ -0,0 +1,43 @@
cur_num = nil
nums = {}
syms = {}
ARGF.readlines(chomp: true).each.with_index do |row, y|
row.chars.each.with_index do |c, x|
case c
when /\d/
if cur_num
cur_num << c
else
cur_num = c
end
else
if cur_num
nums[[y,x-cur_num.length]] = cur_num.to_i
cur_num = nil
end
if c != ?.
syms[[y,x]] = c
end
end
end
if cur_num
nums[[y, row.length-cur_num.length]] = cur_num.to_i
cur_num = nil
end
end
p nums
.filter_map {|(y,x), num|
dy = (-1..1).to_a
dx = (-1..num.digits.length).to_a
if dy.product(dx)
.map {|dy,dx| [y+dy,x+dx] }
.any? { syms.has_key?(_1) }
num
else
nil
end
}
.sum
Loading…
Cancel
Save