Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My go-to solution for random id numbers which programmers frequently need
# yields an 11 digit number in base-36
# with an equal probability distribution for all digits
(0..10).to_a.map {(rand*36).to_i.to_s(36)}.join
# this is slightly preferable to the more simple
(rand*(36**11)).to_i.to_s(36)
# because any number so generated will occasionally be "short"
# and because the first digit will follow a non-random distribution
# in terms of frequency due to some strange number theory thing
# that was only proven in the last decade i think
@stalcottsmith

This comment has been minimized.

Copy link
Owner Author

@stalcottsmith stalcottsmith commented Aug 2, 2014

In response to: https://twitter.com/mxlje/status/495600027880783872

Why use space-inefficent UUIDs?

This code gives me numbers like:

tg9wa3kb9ojskx80zlz9
q0j0c8xrt7vxetnekcqw

36**20 is more than enough... usually 5-10 digits is plenty. 8 digits gives you nearly 3 trillion.

Base 36 gives 5.17 bits of entropy for every digit.

Base 36 encoding is great for encoding sequential ids too and much more compact... suitable for url shorteners, etc.

@mxlje

This comment has been minimized.

Copy link

@mxlje mxlje commented Aug 2, 2014

Thanks, I’ll definitely keep that in mind. A nice thing about UUIDs though is that they don’t include o, i, l and some other chars which makes them a lot more readable. Of course that may not be necessary for everything, but for some use cases it’s great. Also iBeacons :)

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