Skip to content

Instantly share code, notes, and snippets.

@yamatt
Forked from zumbojo/bijective.rb
Created October 24, 2011 10:21
Show Gist options
  • Save yamatt/1308732 to your computer and use it in GitHub Desktop.
Save yamatt/1308732 to your computer and use it in GitHub Desktop.
Simple bijective function (base(n) encode/decode) in Python
# Simple bijective function
# Basically encodes any integer into a base(n) string,
# where n is ALPHABET.length.
# Based on pseudocode from http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener/742047#742047
ALPHABET = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
# make your own alphabet using:
# (('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a).shuffle.join
def bijective_encode(i):
# from http://refactormycode.com/codes/125-base-62-encoding
if i == 0:
return ALPHABET[0]
s = ''
base = len(ALPHABET)
while i > 0:
s += ALPHABET[i % base]
i /= base
return s[::-1] # reverse string
def bijective_decode(s):
# based on base2dec() in Tcl translation
# at http://rosettacode.org/wiki/Non-decimal_radices/Convert#Ruby
i = 0
base = len(ALPHABET)
for char in s:
i = i * base + ALPHABET.index(char)
return i
# Two little demos:
numbers = 95769
result = bijective_encode(number)
print result #xyz
letters = 'abc'
new_number = bijective_decode(letters)
print new_number #66
@yamatt
Copy link
Author

yamatt commented Oct 24, 2011

Will classify this soon

@yamatt
Copy link
Author

yamatt commented Oct 25, 2011

@mickaelandrieu
Copy link

the 2 demo samples are wrong.

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