-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet.rb
63 lines (60 loc) · 1.57 KB
/
net.rb
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
require 'trie'
require_relative 'helper'
# Class of networks
class Net
attr_accessor :rev_arr, :max_word
# Constructor of a network
def initialize(file, trie)
@max_word = []
@end_point = []
@letter_arr = []
@rev_arr = []
@trie = trie
file.each_line do |line|
line = line.strip
content = line.split(';')
content[0] = content[0].to_i
@letter_arr[content[0]] = content[1]
if content[2].nil?
@end_point << content[0]
else
dest = content[2].split(',')
dest.each do |x|
x = x.to_i
@rev_arr[x] = [] if @rev_arr[x].nil?
@rev_arr[x] << content[0]
end
end
end
end
def find_word
@max_length = 0
@end_point.each do |ep|
traverse ep, 1, @letter_arr[ep]
end
@max_word
end
def traverse(start, length, str)
unless @trie.get(str).nil?
if length >= @max_length
if length > @max_length
@max_word = []
@max_length = length
end
@max_word << @trie.get(str)
# Check if there are other words with the same sorted form (stored with '.' extended)
if @trie.has_key?(str + '.')
temp = str.dup + '.'
@max_word << @trie.get(temp)
temp += '.'
while @trie.has_key?(temp)
@max_word << @trie.get(temp)
temp += '.'
end
end
end
end
# Check all the linked nodes, call self on them
@rev_arr[start].each { |x| traverse(x, length + 1, insert_sort(str, @letter_arr[x])) } unless @rev_arr[start].nil?
end
end