Created
February 2, 2018 06:22
-
-
Save nileshtrivedi/9d61ecc2e18f84980b28cf6d3b331218 to your computer and use it in GitHub Desktop.
Multiplication of two state machines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = {a: [:b, :c], b: [:c]} | |
def get_edges(sm) | |
res = [] | |
sm.each do |s, e| | |
e.each do |d| | |
res.push([s,d]) | |
end | |
end | |
res | |
end | |
def get_nodes(sm) | |
get_edges(sm).flatten.uniq | |
end | |
def get_starts(sm) | |
get_nodes(sm) - get_edges(sm).collect(&:last) | |
end | |
b = {p: [:q]} | |
def multiply_starts(a,b) | |
# starting nodes of the combined state machine | |
get_starts(a).product(get_starts(b)) | |
end | |
def multiply_traverse(a, b, ns) | |
f = ns.first | |
l = ns.last | |
# puts "f = #{f}, l = #{l}" | |
res = [] | |
a[f].to_a.each do |e| | |
res.push([e,l]) | |
end | |
b[l].to_a.each do |g| | |
res.push([f,g]) | |
end | |
res | |
end | |
def multiply(a,b) | |
r = {} | |
multiply_starts(a,b).each do |pair| | |
r[pair] = multiply_traverse(a,b, pair) | |
end | |
r.values.flatten(1).each do |pair| | |
next if pair.nil? | |
r[pair] ||= multiply_traverse(a,b,pair) | |
end | |
return r | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment