Class: Jtrie

Inherits:
Object
  • Object
show all
Defined in:
lib/jtrie.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeJtrie

Returns a new instance of Jtrie.



15
16
17
18
19
20
# File 'lib/jtrie.rb', line 15

def initialize
  @root = TrieNode.new
  @dictionay = []
  @csv_dictionary = Csv.new
  @test = []
end

Instance Attribute Details

#dictionaryObject

Returns the value of attribute dictionary.



13
14
15
# File 'lib/jtrie.rb', line 13

def dictionary
  @dictionary
end

#rootObject

Returns the value of attribute root.



13
14
15
# File 'lib/jtrie.rb', line 13

def root
  @root
end

Instance Method Details

#add(word) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/jtrie.rb', line 22

def add(word)
  @dictionay << word
  # @test << word
  word_chars = word.chars
  current = @root
  0.upto(word.length - 1) do |i|
    letter = word_chars[i].ord - 'a'.ord
    current.children[letter] = TrieNode.new if current.children[letter].nil?
    current = current.children[letter]
  end
  current.is_end = true
end

#delete_word(word) ⇒ Object



57
58
59
60
# File 'lib/jtrie.rb', line 57

def delete_word(word)
  @dictionay.delete(word)
  delete_recursively(word, 0, root)
end

#find(word) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/jtrie.rb', line 35

def find(word)
  word_chars = word.chars
  current = @root
  (0..word.length - 1).each do |i|
    letter = word_chars[i].ord - 'a'.ord
    return false if current.children[letter].nil?

    current = current.children[letter]
  end
  current.is_end
end

#include?(word) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/jtrie.rb', line 53

def include?(word)
  find(word) { |found, root| return found && root.word }
end

#list(prefix) ⇒ Object



47
48
49
50
51
# File 'lib/jtrie.rb', line 47

def list(prefix)
  result = []
  @dictionay.each { |word| result << word if word.start_with?(prefix) }
  result.length.zero? ? 'word is not in dictionary' : result
end