Skip to content

Instantly share code, notes, and snippets.

@sshkarupa
Forked from zumbojo/bijective.rb
Created March 19, 2021 08:54
Show Gist options
  • Save sshkarupa/0aa768bc98546d1632cbb2b8c6e02630 to your computer and use it in GitHub Desktop.
Save sshkarupa/0aa768bc98546d1632cbb2b8c6e02630 to your computer and use it in GitHub Desktop.

Revisions

  1. @zumbojo zumbojo revised this gist Jul 10, 2011. 1 changed file with 7 additions and 1 deletion.
    8 changes: 7 additions & 1 deletion bijective.rb
    Original file line number Diff line number Diff line change
    @@ -30,8 +30,14 @@ def bijective_decode(s)
    i
    end

    # A little demo:
    # Two little demos:

    # Encoding ints, decoding them back:
    num = 125
    (num..(num+10)).each do |i|
    print i, " ", bijective_encode(i), " ", bijective_decode(bijective_encode(i)), "\n"
    end

    # Decoding string mentioned in original SO question:
    puts bijective_decode("e9a")

  2. @zumbojo zumbojo created this gist Jul 9, 2011.
    37 changes: 37 additions & 0 deletions bijective.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    # 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 =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split(//)
    # 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
    # with only minor modification
    return ALPHABET[0] if i == 0
    s = ''
    base = ALPHABET.length
    while i > 0
    s << ALPHABET[i.modulo(base)]
    i /= base
    end
    s.reverse
    end

    def bijective_decode(s)
    # based on base2dec() in Tcl translation
    # at http://rosettacode.org/wiki/Non-decimal_radices/Convert#Ruby
    i = 0
    base = ALPHABET.length
    s.each_char { |c| i = i * base + ALPHABET.index(c) }
    i
    end

    # A little demo:
    num = 125
    (num..(num+10)).each do |i|
    print i, " ", bijective_encode(i), " ", bijective_decode(bijective_encode(i)), "\n"
    end