Skip to content

Instantly share code, notes, and snippets.

@sauron
Created March 25, 2014 23:40
Show Gist options
  • Save sauron/9773864 to your computer and use it in GitHub Desktop.
Save sauron/9773864 to your computer and use it in GitHub Desktop.
Basic hash creation methods for a given dictionary.
#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)
@mhewedy
Copy link

mhewedy commented Apr 29, 2014

I Like your solution, and I've translated to Java as a fork (here https://gist.github.com/MuhammadHewedy/11380342)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment