Skip to content

Instantly share code, notes, and snippets.

@jarib
Created January 23, 2014 12:27
Show Gist options
  • Save jarib/8577733 to your computer and use it in GitHub Desktop.
Save jarib/8577733 to your computer and use it in GitHub Desktop.
# TODO: extract to gem, w/ configurable index
class AlphaId
INDEX = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]
BASE = INDEX.size
def self.encode(int)
return INDEX.first if int.zero?
res = ''
start = (Math.log(int) / Math.log(BASE)).floor
start.downto(0) do |n|
idx = (int / BASE ** n) % BASE
res << INDEX.fetch(idx)
end
res.reverse
end
def self.decode(str)
chars = str.split(//).reverse
length = chars.size
res = 0
chars.each_with_index do |char, i|
res += INDEX.index(char) * (BASE ** (length - i - 1))
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment