Class: Manywords::DictionaryNode

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDictionaryNode

Returns a new instance of DictionaryNode.



7
8
9
10
11
# File 'lib/manywords/dictionary_node.rb', line 7

def initialize
  @count = 0;
  @letters = {}
  @word = false
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



5
6
7
# File 'lib/manywords/dictionary_node.rb', line 5

def count
  @count
end

Instance Method Details

#add_word(word, idx = 0) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/manywords/dictionary_node.rb', line 13

def add_word(word, idx = 0)
  # If we've reached the end of the word, mark it as so
  if idx == word.length
    @word = true
    return
  end

  # A word will be added, so increment
  @count += 1

  # Get the letter and add it to the tree if we need to
  letter = word[idx]
  @letters[letter] = DictionaryNode.new unless @letters.key?(letter)

  # Go to the next letter
  @letters[letter].add_word word, idx + 1
end

#find_word(word, idx = 0) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/manywords/dictionary_node.rb', line 31

def find_word(word, idx = 0)
  if !word.is_a?(String) && !word.is_a?(Array)
    raise "find_word requires an Array or a String"
  end

  # We've reached the end, so this is either a word or a partial word
  if idx == word.length
    return @word ? :yes : :maybe
  end

  # Check if this letter is valid
  letter = word[idx]
  if @letters.key? letter
    # Valid, so go to the next letter
    @letters[letter].find_word word, idx + 1
  else
    :no
  end
end