Created
September 24, 2018 14:07
-
-
Save bennacer860/d7a11cb135b1d9ed987ef472fc6d6a89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Indexer | |
attr :dictionary | |
LETTER_TO_NUMBER = { | |
2 => ['a','b','c'], | |
3 => ['d','f','e'], | |
4 => ['g','h','i'], | |
5 => ['j','k','l'], | |
6 => ['m','n','o'], | |
7 => ['p','q','r','s'], | |
8 => ['t','u','v'], | |
9 => ['w','x','y','z'], | |
} | |
def initialize(dictionary) | |
dictionary = dictionary.map{|s| s.strip}.compact.uniq | |
@dictionary = encode_dictionary(dictionary) | |
end | |
# {1233 => ['aa','dd'], 322 => ['e']} | |
def encode_dictionary(dictionary) | |
encoded_dictionary = {} | |
dictionary.each do |string| | |
code = encode(string) | |
unless encoded_dictionary[code] | |
encoded_dictionary[code] = [string] | |
else | |
encoded_dictionary[code] << string | |
end | |
end | |
encoded_dictionary | |
end | |
# string => 123 | |
def encode(string) | |
encoded_string = [] | |
#encode each character | |
string.chars.each do |char| | |
code = LETTER_TO_NUMBER.detect{|k,v| v.include?(char)}[0] | |
encoded_string << code | |
end | |
encoded_string.join() | |
end | |
#222 => abc,aaa,... | |
def decode(encoded_string) | |
@dictionary[encoded_string.gsub(/\D+/, '').strip] | |
end | |
end | |
path = ARGV[0] | |
code = ARGV[1] | |
dictionary = File.readlines('words') | |
p = Indexer.new(dictionary) | |
p p.dictionary | |
p p.decode(code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment