Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'net/http'
- # Load from a file first, web second
- if File.exist? "dictionary"
- text = File.read("dictionary")
- else
- url = "https://pastebin.com/raw/ejKQvqMa"
- text = Net::HTTP.get(URI(url))
- File.write("dictionary", text)
- end
- @words = text.split("\n").map(&:chomp)
- puts "Dictionary loaded"
- # Create the spelling map and populate it word by word
- @spellmap = {}
- @spellmap.instance_eval do
- # Adds a word to the spelling map
- # By default, this adds a complete word to the base map. This method is called
- # recursively to add smaller chunks to lower levels of the map.
- # @param word the word to add to the specified lettermap
- # @param baseword (optional) the base word that triggered the add action
- # @param lettermap (optional) the lettermap to add word to
- def add_word(word, baseword = word, lettermap=self)
- return nil unless baseword # Don't do anything without a base
- if word.empty? # Word is empty, assign it and return the current map
- lettermap[:word] = baseword
- return lettermap
- end
- i0 = word[0] # Get the first character of the chunk
- child_map = lettermap[i0] ||= {} # Make a new map if one doesn't exist
- child_map[:parent] = lettermap # Set parent property
- add_word(word[1..-1], baseword, child_map) # Add the resulting chunk to the child map
- end
- # Retrieve a word from the spelling map. This calls itself recursively as it
- # traverses the word to search for
- # @param word the word to search for in the specified lettermap
- # @param lettermap (optional) the lettermap to search
- def get_word(word, lettermap=self)
- return nil unless word && lettermap
- return get_word(word[1..-1], lettermap[word[0]]) unless word.empty?
- lettermap
- end
- end
- @words.each { |word| @spellmap.add_word(word) }
- puts "Dictionary processed"
- @processing = @words.select { |word| word.length == 2 }
- @longest = nil
- until @processing.empty?
- chunk = @processing.pop
- chunk = @spellmap.get_word(chunk) if chunk.class == String
- next unless chunk && chunk[:word]
- if @longest.nil? || chunk[:word].size > @longest[:word].size
- @longest = chunk
- puts "New longest word: #{@longest[:word]}"
- end
- chunk.each_pair do |k, v|
- next unless k.length == 1 && v.class == Hash
- @processing << v unless v[:word].nil?
- end
- ('a'..'z').each { |letter| @processing << (letter + chunk[:word]) }
- end
- puts @longest[:word]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement