CodeSOD: Plenty of IDs

Venkat joined a new team in the middle of a big refactoring effort. The code was quite a mess, glued together by long Python scripts with main functions longer than a Tolstoy novel. It was this effort to clean up the code into neat modules that highlighted some logical issues with their implementation.

 def generate_random_number():
 """ Generate a 5 digit random number.
 """
    return "".join(map(str, random.sample(range(0,10),5)))

The script this function comes from is a launcher script that provisions a VM to execute code. The VM needs a unique identifier, and we get that random number this way.

The random.sample function, in Python, samples a population without replacement. So here, we pass it a range of 0-10 (which is 0-9 inclusive), and ask for five random entries from it. Again, without replacement, so a range that could concievably contain up to 100,000 possible values is significantly constrained down to 30,000 or so- only the numbers less than 100,000 that contain no duplicate digits.

We then map the resulting array into an array of strings, then join that into a final output string.

Now, for most of us, I do suspect that 30,240 unique values is probably enough for how ever many VMs we might need to reserve at any one time; if you're not working for Amazon or Google or whatever, you're probably fine. Then again, the chances of an accidental collision are surprisingly high: after only 26 requests, there's a 1% chance of a collision. And thanks to the birthday problem, it takes 206 requests to get to a 50% chance of collision. So maybe 30,240 is not enough for anybody.

[Advertisement] Plan Your .NET 9 Migration with Confidence
Your journey to .NET 9 is more than just one decision.Avoid migration migraines with the advice in this free guide. Download Free Guide Now!

Source link

Stay in the Loop

Get the daily email from CryptoNews that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

You might also like...