[2023][ruby][8.2]
change zsxqpnpumlyozolpwmpnrlnropnytkyz
commit 36fdb830d6735ac3acb8759236c83da33eaf08ae
author Alpha Chen <alpha@kejadlen.dev>
date
parent olrqnpsm
diff --git a/2023/ruby/day_08.rb b/2023/ruby/day_08.rb
index 5f7c2b2..92e73f9 100644
--- a/2023/ruby/day_08.rb
+++ b/2023/ruby/day_08.rb
@@ -1,14 +1,30 @@
+require "prime"
+
 instructions, network = ARGF.read.split("\n\n")
 
 network = network
   .scan(/(\w+) = \((\w+), (\w+)\)/)
   .to_h { [_1, { L: _2, R: _3 }] }
 
-node = "AAA"
-p instructions.chars.map(&:to_sym)
-  .cycle.with_index.lazy
-  .filter_map {|dir, i|
-    node = network.fetch(node).fetch(dir)
-    (node == "ZZZ") ? i+1 : nil
-  }
-  .first
+steps = ->(start, finish) {
+  node = start
+  instructions.chars.map(&:to_sym)
+    .cycle.with_index.lazy
+    .filter_map {|dir, i|
+      node = network.fetch(node).fetch(dir)
+      (node =~ finish) ? i+1 : nil
+    }
+    .first
+}
+
+# part one
+p steps.("AAA", /ZZZ/)
+
+# part two
+nodes = network.keys.select { _1.end_with?(?A) }
+node_steps = nodes.map { steps.(_1, /Z$/) }
+p node_steps
+  .map { Prime.prime_division(_1).to_h }
+  .inject {|acc, fac| acc.merge(fac) {|_,old,new| [old, new].max}}
+  .map { _1**_2 }
+  .inject(:*)