From a7822ce4f18cf97425dc25869b71e9770f093a7f Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Thu, 5 Dec 2024 21:33:39 -0800 Subject: [PATCH] [2024][ruby][6.2] --- 2024/ruby/day_06.rb | 59 +++++++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/2024/ruby/day_06.rb b/2024/ruby/day_06.rb index c533280..3e6f3ea 100644 --- a/2024/ruby/day_06.rb +++ b/2024/ruby/day_06.rb @@ -5,33 +5,56 @@ input = DATA.readlines(chomp: true) } }.to_h -turns = { +TURNS = { [-1,0] => [0,1], [0,1] => [1,0], [1,0] => [0,-1], [0,-1] => [-1,0], } -start = input.find { _2 == ?^ }.first -dir = [-1,0] -path = [start] -loop do - peek = path.last.zip(dir).map {|i,di| i + di } - case input.fetch(peek, nil) - when ?. - path << peek - when ?^ - path << peek - when ?# - dir = turns.fetch(dir) - when nil - break - else - fail +Loop = Class.new(Exception) + +def patrol(lab) + start = lab.find { _2 == ?^ }.first + path = [[start, [-1,0]]] + seen = path.to_set + loop do + pos, dir = path.last + peek = pos.zip(dir).map {|i,di| i + di } + raise Loop if seen.include?([peek, dir]) + seen << [peek, dir] + + case lab.fetch(peek, nil) + when ?., ?^ + path << [peek, dir] + when ?# + path.last[1] = TURNS.fetch(dir) + when nil + return path + else + fail + 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__ ....#.....