The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Generating a Unique Number

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jake Scruggs

Posts: 336
Nickname: aurorae314
Registered: Feb, 2008

Jake Scruggs is a developer at ThoughtWorks
Generating a Unique Number Posted: Feb 19, 2008 12:55 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jake Scruggs
Latest Posts From Jake Scruggs

Advertisement
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:

MAXIMUM_FOR_10_DIGITS = 0xffffffffff
(MAXIMUM_FOR_10_DIGITS + cart_id + Time.now.to_i + rand(100_000_000)).to_s(16)
I was thinking about using hex, but I was worried about what would happen if the number got too big and went to 12 digits. So I did this calculation:

irb(main):001:0> 0xfffffffffff - 0x10000000000
=> 16492674416639
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.

Read: Generating a Unique Number

Topic: Genghiscon 2008 Wrap Up Previous Topic   Next Topic Topic: Handling nil in method calls

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use