Generating random integer from a range

前端 未结 13 1523
失恋的感觉
失恋的感觉 2020-11-22 03:12

I need a function which would generate a random integer in given range (including border values). I don\'t unreasonable quality/randomness requirements, I have four requirem

13条回答
  •  青春惊慌失措
    2020-11-22 03:37

    Notice that in most suggestions the initial random value that you have got from rand() function, which is typically from 0 to RAND_MAX, is simply wasted. You are creating only one random number out of it, while there is a sound procedure that can give you more.

    Assume that you want [min,max] region of integer random numbers. We start from [0, max-min]

    Take base b=max-min+1

    Start from representing a number you got from rand() in base b.

    That way you have got floor(log(b,RAND_MAX)) because each digit in base b, except possibly the last one, represents a random number in the range [0, max-min].

    Of course the final shift to [min,max] is simple for each random number r+min.

    int n = NUM_DIGIT-1;
    while(n >= 0)
    {
        r[n] = res % b;
        res -= r[n];
        res /= b;
        n--;
    }
    

    If NUM_DIGIT is the number of digit in base b that you can extract and that is

    NUM_DIGIT = floor(log(b,RAND_MAX))
    

    then the above is as a simple implementation of extracting NUM_DIGIT random numbers from 0 to b-1 out of one RAND_MAX random number providing b < RAND_MAX.

提交回复
热议问题