[2024][ruby][6.2]
change klunqzkzllqsrlmqtypvwopvxlqkwyrk
commit f52a1ede888f56abd20710195f90e9d1b7b4c420
author Alpha Chen <alpha@kejadlen.dev>
date
parent oxtpuqux
diff --git a/2024/ruby/day_06.rb b/2024/ruby/day_06.rb
index 18011d7..6ebad39 100644
--- a/2024/ruby/day_06.rb
+++ b/2024/ruby/day_06.rb
@@ -5,32 +5,55 @@ 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__