Logo

Programming-Idioms

History of Idiom 15 > diff from v39 to v40

Edit summary for version 40 by daniel:
[C] Fix modulo bias, and also allow `b`

Version 39

2018-05-08, 01:28:15

Version 40

2019-09-26, 17:12:46

Idiom #15 Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

Idiom #15 Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

Extra Keywords
choose
Extra Keywords
choose
Imports
#include <stdlib.h>
Imports
#include <stdlib.h>
Code
int pick(int a, int b)
{
	return a + rand() % (b - a);
}
Code
int pick(int a, int b)
{
	int upper_bound = b - a + 1;
	int max = RAND_MAX - RAND_MAX % upper_bound;
	int r;

	do {
		r = rand();
	} while (r >= max);
	r = r % max;
	return a + r;
}
Doc URL
https://stackoverflow.com/a/10984975/4087179