c++ - Generating random number between 4 ints -
what efficient way generate random numbers between 4 ints? ex:
it pick numbers 2 ranges 4 8 , 14 17.. thought picking middle number: 11 make randomizer have 2 options
- add between (3-5)
- subtract between (3-5)
i waiting replies , answers pls in c++ dont use stdio.h
if ranges inclusive, have (r1b-r1a+1)+(r2b-r2a+1)
numbers choose from. use rand
(or better random number library) pick non-negative integer (r1b-r1a+1)+(r2b-r2a+1)
(exclusive), map result onto 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 before range 2.
- overlapping ranges.
- negative range endpoints.
Comments
Post a Comment