This repository was archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise10.rb
More file actions
116 lines (89 loc) · 2.36 KB
/
Copy pathexercise10.rb
File metadata and controls
116 lines (89 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# Exercise 10
class Transition
attr_reader :through, :to
def initialize(through,to)
@through, @to = through, to
end
end
class Node
attr_reader :id, :accepting
def initialize(id)
@id, @transitions, @accepting = id, [], false
end
def addTransition(tr)
@transitions << tr
end
def nextFor(symbol)
transition = @transitions.find { |tr| tr.through == symbol}
return transition&.to
end
def accept
@accepting = true
end
end
def getNode(nodes,id)
node = nodes.find { |nd| nd.id == id }
if(node.nil?)
node = Node.new(id)
nodes << node
end
return node
end
def checkString(nodes,string)
# find start node
currentNode = nodes.find { |nd| nd.id.zero? }
# check if path to accepting state exists
string.each_char do |ch|
currentNode = currentNode.nextFor(ch)
break if currentNode.nil?
return true if currentNode.accepting
end
# no accepting state found
return false
end
def createNodes(transitions)
nodes = []
transitions.each do |tr|
# read transition from string
arr = tr.split
fromId, toId, through, acc = arr[0].to_i, arr[2].to_i, arr[1], arr[3]
# get or create nodes if necessary
fromNode = getNode(nodes,fromId)
toNode = getNode(nodes,toId)
# if transition was marked with Y, target node is in accepting state
toNode.accept if(acc=='Y')
# add transition
fromNode.addTransition(Transition.new(through,toNode))
end
return nodes
end
def main
# get transitions from user
puts "Enter state transitions"
transitions = []
input = gets.chomp
while(input!="")
transitions << input
input = gets.chomp
end
# create nodes from input strings
nodes = createNodes(transitions)
# get test string
puts "Enter string"
str = gets.chomp
# test input string and print answer
answer = checkString(nodes,str) ? "valid" : "invalid"
puts "String \"#{str}\" is #{answer}"
end
# main
# -------------------------------------------------------------
# TESTS
# -------------------------------------------------------------
ER = "Error"
transitions = ["0 A 1 N","1 B 1 N", "1 A 2 Y"]
nodes = createNodes(transitions)
raise ER if checkString(nodes,"ABBBB")
raise ER if checkString(nodes,"BABBBB")
raise ER unless checkString(nodes,"ABBBBA")
raise ER unless checkString(nodes,"ABBBBAAAA")
# -------------------------------------------------------------