[2024][ruby][6.2]

main
Alpha Chen 6 days ago
parent 2a88deecc7
commit a7822ce4f1
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -5,33 +5,56 @@ input = DATA.readlines(chomp: true)
} }
}.to_h }.to_h
turns = { TURNS = {
[-1,0] => [0,1], [-1,0] => [0,1],
[0,1] => [1,0], [0,1] => [1,0],
[1,0] => [0,-1], [1,0] => [0,-1],
[0,-1] => [-1,0], [0,-1] => [-1,0],
} }
start = input.find { _2 == ?^ }.first Loop = Class.new(Exception)
dir = [-1,0]
path = [start] def patrol(lab)
loop do start = lab.find { _2 == ?^ }.first
peek = path.last.zip(dir).map {|i,di| i + di } path = [[start, [-1,0]]]
case input.fetch(peek, nil) seen = path.to_set
when ?. loop do
path << peek pos, dir = path.last
when ?^ peek = pos.zip(dir).map {|i,di| i + di }
path << peek raise Loop if seen.include?([peek, dir])
when ?# seen << [peek, dir]
dir = turns.fetch(dir)
when nil case lab.fetch(peek, nil)
break when ?., ?^
else path << [peek, dir]
fail when ?#
path.last[1] = TURNS.fetch(dir)
when nil
return path
else
fail
end
end end
end end
pp path.to_set.length def loop?(lab)
patrol(lab)
false
rescue Loop
true
end
pp patrol(input).map(&:first).to_set.length
pp input
.select { _2 == ?. }
.select {|xy, _|
# pp xy
input[xy] = ?#
res = loop?(input)
input[xy] = ?.
res
}.size
__END__ __END__
....#..... ....#.....

Loading…
Cancel
Save