If those ranges are inclusive, you have (r1b-r1a+1)+(r2b-r2a+1)
numbers to choose from. Use rand
(or a better random number library) to pick a non-negative integer up to (r1b-r1a+1)+(r2b-r2a+1)
(exclusive), then map that result back onto the ranges.
int pick = rand() % ((r1b-r1a+1)+(r2b-r2a+1));
pick += ( pick < (r1b-r1a+1) ) ? r1a : r2a;
Assumptions:
r1b >= r1a
.r2b >= r2a
.
Supported:
- Range 1 doesn’t have to be before range 2.
- Overlapping ranges.
- Negative range endpoints.
1
solved Generating random number between 4 ints [closed]