Class: GADDAG
- Inherits:
-
Object
- Object
- GADDAG
- Defined in:
- lib/gaddag.rb,
lib/gaddag/arc.rb,
lib/gaddag/node.rb,
lib/gaddag/path.rb,
lib/gaddag/word.rb
Overview
Implementation of the GADDAG data structure
Defined Under Namespace
Classes: Arc, Node, Path, Word
Instance Attribute Summary collapse
-
#root ⇒ Object
readonly
The root node.
Instance Method Summary collapse
-
#add(word) ⇒ GADDAG
Adds a word to the GADDAG.
-
#find(substring) ⇒ Array<String>
Finds all words that contain the given substring.
-
#initialize ⇒ GADDAG
constructor
Initializes a GADDAG.
Constructor Details
Instance Attribute Details
Instance Method Details
#add(word) ⇒ GADDAG
Adds a word to the GADDAG
24 25 26 27 28 29 30 31 32 |
# File 'lib/gaddag.rb', line 24 def add(word) @root.create_final_path(word.chars.reverse + [Path::DELIMITER]) Word.new(word.chars).to_delimited_paths.each do |path| @root.create_final_path(path.letters) end self end |
#find(substring) ⇒ Array<String>
Finds all words that contain the given substring
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/gaddag.rb', line 37 def find(substring) first_letter, second_letter, *last_letters = *substring.chars return [] unless @root.path?(last_letters.reverse) @root.follow_path(last_letters.reverse).final_paths.select do |path| path.start_with?([second_letter, first_letter]) end.map do |path| Path.new(last_letters.reverse + path).to_word.to_s end.uniq end |