Class: Jtrie
- Inherits:
-
Object
- Object
- Jtrie
- Defined in:
- lib/jtrie.rb
Instance Attribute Summary collapse
-
#dictionary ⇒ Object
Returns the value of attribute dictionary.
-
#root ⇒ Object
Returns the value of attribute root.
Instance Method Summary collapse
- #add(word) ⇒ Object
- #delete_word(word) ⇒ Object
- #find(word) ⇒ Object
- #include?(word) ⇒ Boolean
-
#initialize ⇒ Jtrie
constructor
A new instance of Jtrie.
- #list(prefix) ⇒ Object
Constructor Details
Instance Attribute Details
#dictionary ⇒ Object
Returns the value of attribute dictionary.
13 14 15 |
# File 'lib/jtrie.rb', line 13 def dictionary @dictionary end |
#root ⇒ Object
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
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 |