aboutsummaryrefslogtreecommitdiff
path: root/rb/day19.rb
diff options
context:
space:
mode:
Diffstat (limited to 'rb/day19.rb')
-rwxr-xr-xrb/day19.rb48
1 files changed, 48 insertions, 0 deletions
diff --git a/rb/day19.rb b/rb/day19.rb
new file mode 100755
index 0000000..d9e4133
--- /dev/null
+++ b/rb/day19.rb
@@ -0,0 +1,48 @@
+#!/usr/bin/env ruby
+
+def getreps(str, from, to)
+ re = Regexp.new(from)
+ md = str.match(re)
+
+ reps = []
+ until md.nil?
+ reps << str[0...md.begin(0)] + to + str[md.end(0)..-1]
+ md = str.match(re, md.end(0))
+ end
+
+ reps
+end
+
+*istrs, _, init = File.readlines("day19.input").map(&:strip)
+istrs.map! { |istr| istr.split(" => ") }
+
+results = Set.new
+istrs.each do |from, to|
+ results += getreps(init, from, to)
+end
+
+puts "Part 1: #{results.length}"
+
+
+istrs.map! { |from, to| [to, from] }
+
+space = [[init, 0]]
+mindis = init.length
+
+loop do
+ break if space.empty?
+ this, thisdis = space.pop
+
+ if this == ?e
+ mindis = thisdis if thisdis < mindis
+ next
+ end
+
+ istrs.each do |from, to|
+ getreps(this, from, to).each do |rep|
+ space.push([rep, thisdis + 1])
+ end
+ end
+end
+
+puts "Part 2: #{mindis}"