Created
March 25, 2014 23:40
-
-
Save sauron/9773864 to your computer and use it in GitHub Desktop.
Basic hash creation methods for a given dictionary.
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
#Hash function which converts hash_me("leep", dictionary) => 13427273 | |
def hash_me(text, dictionary) | |
h = 7 | |
dictionary = "acdegilmnoprstuw" | |
text.size.times do |i| | |
h = (h * 37) + dictionary.index(text[i]).to_i | |
end | |
h | |
end | |
def find_position(number, dictionary) | |
dictionary.split("").each_with_index do |l, i| | |
div, mod = (number - i).divmod(37) | |
if mod == 0 | |
return div, l | |
break | |
end | |
end | |
["", 0] | |
end | |
#Unhash function which converts unhash_me(13427273, dictionary) => "leep | |
def unhash_me(number, dictionary) | |
h = 7 | |
text = "" | |
while number > h | |
number, letter = find_position(number, dictionary) | |
text << letter | |
end | |
text.reverse | |
end | |
#Usage: set the dictionary and the number to be decoded | |
dictionary = "acdegilmnoprstuw" | |
number = 910897038977002 | |
#Call the unhash fuction | |
text = unhash_me(number, dictionary) | |
#Print the victory mark if everything went ok. | |
puts "Sucess!!" if number == hash_me(text, dictionary) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I Like your solution, and I've translated to Java as a fork (here https://gist.github.com/MuhammadHewedy/11380342)