Skip to content

Instantly share code, notes, and snippets.

@mweppler
Last active December 15, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mweppler/5228214 to your computer and use it in GitHub Desktop.
Save mweppler/5228214 to your computer and use it in GitHub Desktop.
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