diff options
author | Nat Lasseter <user@4574.co.uk> | 2024-11-07 22:27:13 +0000 |
---|---|---|
committer | Nat Lasseter <user@4574.co.uk> | 2024-11-07 22:27:13 +0000 |
commit | 7d86157dfe52a76e03694be4592e32d9dec69ed9 (patch) | |
tree | 2e322463a0c5a15c09a78954334753d374316e31 /rb/day19.rb | |
parent | d7d62da5e9c2ca991885641e0a55c2907eb0fb7e (diff) |
Diffstat (limited to 'rb/day19.rb')
-rwxr-xr-x | rb/day19.rb | 48 |
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}" |