Last active
August 29, 2015 14:03
-
-
Save dux/be462728762cebf16b72 to your computer and use it in GitHub Desktop.
Encode any integer to string base of choice. Just replace keys with one you want to encode into. StringBase.encode(11111111) == "frgh"
This file contains hidden or 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
module StringBase | |
KEYS = 'bcdfghjklmnpqrstvwxyz' | |
def self.encode( value ) | |
ring = Hash[KEYS.chars.map.with_index.to_a.map(&:reverse)] | |
base = KEYS.length | |
result = [] | |
until value == 0 | |
result << ring[ value % base ] | |
value /= base | |
end | |
result.reverse.join | |
end | |
def self.decode( string ) | |
ring = Hash[KEYS.chars.map.with_index.to_a] | |
base = KEYS.length | |
# Ruby < 2 string.reverse.chars.with_index.inject(0) do |sum,(char,i)| | |
string.reverse.chars.map.with_index.inject(0) do |sum,(char,i)| | |
sum + ring[char] * (base**i) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment