0

I'm looking to implement something similar to python's random.randint in C.

I would do something like:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
srand(time(NULL));

int randInt(int lBound, int uBound){
    return (rand()%(uBound-lBound+1))+lbound;
}

but if RAND_MAX is not a multiple of uBound, then distribution will be slight skewed.

Is there a quick and dirty way that's better?

John Gann
  • 595
  • 6
  • 13

1 Answers1

0

If avoiding skew is important then you need to do something like this.

int randInt(int lBound, int uBound){
    int rangesize = uBound-lBound+1; 
    if ((rangesize - 1 > RAND_MAX) || (rangesize < 0) || (lBound > uBound)) {
        // run in circles, scream and shout
    }
    int limit;
    if (rangesize < RAND_MAX) {
        limit = RAND_MAX - (((RAND_MAX % rangesize) + 1) % rangesize);
    } else {
        limit = RAND_MAX;
    ]
    int rv;
    do {
        rv = rand();
    } while (rv > limit);
    return rv % rangesize + lbound;
}
NovaDenizen
  • 5,089
  • 14
  • 28
  • 1
    That's a good way to approach the solution, but it has some issues: It doesn't work on platforms where `RAND_MAX == INT_MAX`, because `RAND_MAX+1` will overflow. It also doesn't work when `uBound-lBound > RAND_MAX`, or when `uBound-lBound+1` doesn't fit in an `int`. – interjay Oct 31 '13 at 15:09
  • Issues fixed, I think. – NovaDenizen Oct 31 '13 at 15:15