Skip to content

Instantly share code, notes, and snippets.

@lomereiter
Created May 6, 2013 11:34
Show Gist options
  • Save lomereiter/5524643 to your computer and use it in GitHub Desktop.
Save lomereiter/5524643 to your computer and use it in GitHub Desktop.
Markov algorithm interpreter
# -*- coding: utf-8 -*-
Rule = Struct.new :from, :to, :exit
def parseSingleRule(rule_src)
rule_src =~ /^\s*([^\s]*)\s*=>\s*([\.]?)([^\s]*)\s*$/
r = Rule.new($1, $3)
r.exit = $2 == '.'
r
end
def parseMultipleRules(rules_src)
rules_src.split("\n").map{|x| parseSingleRule x}
end
def applyRules(rules, str, options={})
exit = false
verbose = options[:verbose]
puts str if verbose
loop do
found_rule = false
rules.each do |rule|
if str.index(rule.from)
str.sub!(rule.from, rule.to)
found_rule = true
if verbose then
puts "applying rule #{rule.from} => #{rule.to}:\t#{str}"
end
exit = rule.exit
break
end
end
break if exit or not found_rule
end
str
end
min = <<MIN
$| => |$
|*| => *$
*| => *
β| => β
β* => β
β$ => |β
β => .
=> β
MIN
rules = parseMultipleRules min
puts applyRules(rules, "|||||*|||", verbose: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment