How to generate a random integer number from within a range

后端 未结 11 1223
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 23:57

This is a follow on from a previously posted question:

How to generate a random number in C?

I wish to be able to generate a random number from within a part

11条回答
  •  终归单人心
    2020-11-22 00:56

    Following on from @Ryan Reich's answer, I thought I'd offer my cleaned up version. The first bounds check isn't required given the second bounds check, and I've made it iterative rather than recursive. It returns values in the range [min, max], where max >= min and 1+max-min < RAND_MAX.

    unsigned int rand_interval(unsigned int min, unsigned int max)
    {
        int r;
        const unsigned int range = 1 + max - min;
        const unsigned int buckets = RAND_MAX / range;
        const unsigned int limit = buckets * range;
    
        /* Create equal size buckets all in a row, then fire randomly towards
         * the buckets until you land in one of them. All buckets are equally
         * likely. If you land off the end of the line of buckets, try again. */
        do
        {
            r = rand();
        } while (r >= limit);
    
        return min + (r / buckets);
    }
    

提交回复
热议问题