So, with my current project, I need to work with 64-bit integers and I need to grab random numbers between ranges up to 100 billion. arc4random()/arc4random_uniform() only works with unsigned 32-bit integers.
I can probably fudge it a little because my min/max range for every call will likely not exceed 2 billion, but I'd like to futureproof myself in case I decide that, well, I do need a broader range.
Any advice?
Here is one neat solution! (methinks anyway, since I just made it up)
Quick test with Swift REPL:
https://repl.it/GeIs/0
As an extension...
Perhaps you can compose it of to 32 bit integers:
Here are some helpers that I usually include in my projects. Note the UInt64 bounded helper, it works largely in the same way to Martin R's answer, except for checks for the frequent case that the range is smaller than UInt32.max and only performs one call to arc4random().
Update: As of Swift 4.2 (distributed with Xcode 10.1) there is a unified random API in the Swift standard library, see
You can simply call
to get a random number in the given range.
(Previous answer for Swift < 4.2:) With
arc4random_buf()
you can create "arbitrary large" random numbers, so this would be a possible solution:This method suffers from the "modulo bias" problem when the upper bound is not a power of 2 (See Why do people say there is modulo bias when using a random number generator?). Here I have translated the answer https://stackoverflow.com/a/10989061/1187415 from above thread to Swift:
(At first sight it looks as if the loop might not terminate, but it can be shown that on average less than 2 iterations are needed.)