Create a gist now

Instantly share code, notes, and snippets.

@mweppler /fsmsim.rb
Last active Dec 15, 2015

What would you like to do?
Fsm Simulator from Udacity CS262 implemented in ruby...
# FSM Simulation
edges = {
[1, 'a'] => 2,
[2, 'a'] => 2,
[2, '1'] => 3,
[3, '1'] => 3
}
accepting = [3]
def fsmsim string, current, edges, accepting
if string == ""
return accepting.include? current
else
char = string[0]
if edges.key? [current, char]
remaining_string = string[1..-1]
destination = edges.fetch [current, char]
return fsmsim remaining_string, destination, edges, accepting
else
return false
end
end
end
puts fsmsim("aaa111", 1, edges, accepting)
puts fsmsim("a1a1a1", 1, edges, accepting)
puts fsmsim("a1", 1, edges, accepting)
# edges = {(1, 'a') : 2,
# (2, 'a') : 2,
# (2, '1') : 3,
# (3, '1') : 3}
# accepting = [3]
# def fsmsim(string, current, edges, accepting):
# if string == "":
# return current in accepting
# else:
# letter = string[0]
# # QUIZ: You fill this out!
# # Is there a valid edge?
# if (current, letter) in edges:
# # If so, take it.
# remaining_string = string[1:]
# distination = edges[current, letter]
# # Hint: recursion.
# fsmsim(remaining_string, distination, edges, accepting)
# else:
# # If not, return False.
# return false
# print fsmsim("aaa111",1,edges,accepting)
# >>> True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment