« Attention conditional playback | Home | Postbox email client »
July 24, 2009
Tiny UID Algorithm generation
There are lots of web services that offer link shortening. The tiny uid they create is what fascinates me. A google search didn't throw any good info so here it is an algorithm for you to use.
There are lots of url shortening websites but my very favorite is ir.pe
It's interface is clean and it's url is very short (5 chars if you count the dot).
I've been using the ir.pe service since it was created so i pretty much figured out how the uid where conceived. Here is the logic:
You start with a list of characters that you want to use. For example:
"abcdefghijklmnopqrstuvwxyz0123456789_-"
uids will be:
1 - a
2 - b
3 - c
...
39 - aa
40 - ab
41 - ac
...
78 - ba
79 - bb
80 - bc
And so on. Noticed the pattern?
Ok, if you are a developer take 10 minutes and try to create an algorithm that will generate those uids :)
-- Solution below, don't cheat! --
This algorithm needs to be fast!
I always add a new layer of complexity to this kind of exercise, the code needs to be not only fast but short. Fun Fun! (I'm a nerd, i know. You don't need to shout! :p
function generateCode(i:uint):String{
var s:String = "abcdefghijklmnopqrstuvwxyz0123456789_-";
return (i<s.length) ? s.charAt(i): arguments.callee((i/s.length)-1)+s.charAt(i%s.length);
}
It's ActionScript code if you wonder but the logic could be easily translated to a mysql/postresql/sql function (i recommend using a database function rather than a backend method creation).
In flash it takes 5871 ms to create 1 million uids and less than a ms to create 1.
Leave a comment with your own version!
--fernando
Hi Fernando. I have also been playing with this short URLs concept for a wile. The best resource I found is
http://ir.pe/2b3
Probe con:
trace( generateCode(9999999999999999) );
trace( generateCode(10000000000000000) );
Y ambas me devuelven "wyf9x6".
Quizás exageré :P , pero pasa.
@otakurzo thats because of the limitation a uint has. Try changing uint to Number and that should be fixed.
Hi Fernando. This is a implementation of your algorithm in python:
def irpe(i, s=None):
s = 'abcdefghijklmnopqrstuvwxyz0123456789' if s is None else s
i = int(i)
return s[i] if i
Thanks :D
Fernando Net Tuts + have just post an artivle related
http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/
Problem with the characters that you use is that you could get actual words generated. This means that you could generate dirty words as well.
Greetz Erik
Exactly. But can we count that as a feature? ;)