

Ask HN: how can I generate youtube style id? - jacktang

Given sample URL: http://www.youtube.com/watch?v=xqvObyU2ITs, any availabale algorithm to generate youtube style video id (xqvObyU2ITs)? Thanks!<p>-Jack
======
jcapote
def generate_code(len = 5)

    
    
      (1..len).map { (("a".."z").to_a + ("A".."Z").to_a + (0..9).to_a)[rand(62)] }.join
    

end

~~~
wooby
That rocks dude.

------
compay
Here's a very quick and dirty one for Ruby:

require 'zlib'

base = "whatever"

salt = "whatever"

Zlib.crc32(base + salt).to_s(36)

This will generate 6-7 character strings. Not sure how likely collisions are,
but they should be rare enough that a simple check/regenerate should work.

------
staunch
First thought is that they're generating a globally unique video ID number and
base-62 encoding it to keep the URL shorter. Maybe not though?

You could do that easily by just base-62 encoding your table's auto-generated
primary key.

------
wooby
Or, using C with /dev/urandom: <http://alan.dipert.org/post/84526522/random-
strings-with-c>

------
HeyLaughingBoy
What's wrong with starting with '0' for the first item and incrementing up
from there? Guaranteed uniqueness.

~~~
throw_away
a) impossible to do in a distributed fashion, b) may leak information about
your operations to competitors. of course, OP may not care about these things.

~~~
HeyLaughingBoy
I understand (b), and in fact I considered it a potential weakness, but why
does (a) matter if you're selling from a single site? Even if you got multiple
simultaneous orders, storing the last license generated in a DBMS should make
it multiprocess-safe.

------
inklesspen
uh, in python:

    
    
      import string, random
      ''.join(random.sample((string.letters+string.digits), 12))
    

I hope that's what you were asking for. If not, you might want to clarify your
question.

~~~
aristus
On morning's light, that won't do what you think. random.sample() gives you a
unique sampling. No character will be repeated. try this instead:

    
    
        alphanum = string.letters+string.digits
        ''.join([alphanum[random.randint(0,61)] for i in xrange(12)])

~~~
inklesspen
You're quite right; I should have caught that.

