Skip to content

Instantly share code, notes, and snippets.

@iladriano
Created February 12, 2012 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iladriano/1809310 to your computer and use it in GitHub Desktop.
Save iladriano/1809310 to your computer and use it in GitHub Desktop.
Short URL from a counter
package com.ghosthack.turismo.util;
public class Encoder
{
protected static final String DEFAULT_ALPHABET = "ed82j6rhkyf5amu9x4qbgpstn7vc3w1ioz";
protected static final int DEFAULT_BLOCK_SIZE = 22;
private String alphabet;
private int blockSize;
private int mask;
private int[] mapping;
public Encoder()
{
this.alphabet = DEFAULT_ALPHABET;
this.blockSize = DEFAULT_BLOCK_SIZE;
this.mask = (1 << blockSize) - 1;
this.mapping = new int[blockSize];
for(int i = 0; i<blockSize; i++) {
mapping[i] = blockSize-i-1;
}
}
public static void main(String[] args)
{
for(int i = 1; i<10; i++) {
System.out.println(new Encoder().toKey(i));
}
}
public String toKey(int id) {
return enbase(encode(id));
}
private String enbase(int n)
{
return enbase(n, 0);
}
private String enbase(int n, int minLength)
{
String result = _enbase(n);
StringBuilder sb = new StringBuilder();
int a = minLength - result.length();
if(a > 0) {
for(int i=0; i<a; i++) {
sb.append(alphabet.charAt(0));
}
}
String padding = sb.toString();
return String.format("%s%s", padding, result);
}
private String _enbase(int x)
{
int n = alphabet.length();
if(x < n) {
return alphabet.charAt(x)+"";
}
return enbase(x/n) + alphabet.charAt(x%n);
}
private int encode(int n)
{
return (n & ~mask) | _encode(n & mask);
}
private int _encode(int n)
{
int result = 0;
for(int i = 0; i<mapping.length; i++) {
int b = mapping[i];
if((n & (1<<i)) != 0) {
result |= (1 << b);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment