Class: WordFinder::Node

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

Overview

A node in the search tree.

A search is represented by a tree of nodes. Each node represents a branch of valid words.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Node

Returns a new instance of Node.



16
17
18
19
20
21
22
# File 'lib/word_finder/node.rb', line 16

def initialize(options = {})
  @words    = []
  @buf      = ""
  @children = []
  @offset   = 0
  @checker  = Checker.new(options[:lang] || "en_US")
end

Instance Attribute Details

#offsetObject (readonly)

Returns the value of attribute offset.



14
15
16
# File 'lib/word_finder/node.rb', line 14

def offset
  @offset
end

Instance Method Details

#condenseObject



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/word_finder/node.rb', line 36

def condense
  (@offset...(@words.length - 1)).each do |i|
    (@words[i..-1].join).tap do |word|
      if @checker.word?(word)
        @children << dup
        @words[i..-1] = word
        @buf = ""
        @offset = @words.length
        return
      end
    end
  end
end

#initialize_copy(parent) ⇒ Object



59
60
61
62
63
# File 'lib/word_finder/node.rb', line 59

def initialize_copy(parent)
  @words    = parent.instance_variable_get(:@words).dup
  @buf      = parent.instance_variable_get(:@buf).dup
  @children = []
end

#insert(char) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/word_finder/node.rb', line 24

def insert(char)
  @children.each{|c| c.insert(char)}

  @buf << char

  if @checker.word?(@buf)
    @words << @buf
    @buf = ""
    condense
  end
end

#wordsObject



50
51
52
53
54
55
56
57
# File 'lib/word_finder/node.rb', line 50

def words
  (best = @words)
  @children.each do |c|
    other = c.words
    best = other if other.length < best.length
  end
  best
end