This post originated from an RSS feed registered with Ruby Buzz
by Jake Scruggs.
Original Post: Generating a Unique Number
Feed Title: Jake Scruggs
Feed URL: http://jakescruggs.blogspot.com/feeds/posts/default
Feed Description: Ruby, Rails, Metrics, Testing, and pursuit of clean code.
Weird requirement at work today: We needed a number that was alpha-numeric, exactly 11 digits, unique, and non-sequential. At first we thought of using a hash, but MD5 and Sha1 give you way too many digits. We could truncate to 11, but not knowing much about hashing, that made me pretty nervous that we'd have collisions. After a bunch of discussion, we decided on this:
Turns out there's all sorts of room between the lowest and highest 11 digit hex number. Paul and Schubert did some quick calculations assuming lots of carts per day and figured out that we have about 250,000 years before we run out of space. Now since we use a random number, there is a chance that we could get two matching numbers so we do a database lookup to make sure that a generated number hasn't been used before. There is still a small chance that two identical numbers could be generated in the time between generation and saving to the database, but I think we can live with that.