Last active
December 15, 2015 08:08
-
-
Save mweppler/5228214 to your computer and use it in GitHub Desktop.
Fsm Simulator from Udacity CS262 implemented in ruby...
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
# 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