开发者

How to choose 10 different integers from range (0, 99)

开发者 https://www.devze.com 2023-01-21 11:45 出处:网络
I want to choose 10 random integers from 0 开发者_如何学Pythonto 99. I know I can use: random.randint(a, b)

I want to choose 10 random integers from 0 开发者_如何学Pythonto 99. I know I can use:

random.randint(a, b)

But how to tell the randint() that I only want different integers.

Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like an optimal solution.


from random import sample

sample(range(0, 100), 10)


Here's general strategy that is language independent. Generate an array of 100 entries from 0 to 99. Choose a random number from 0 to 99 and swap the entry at that position with the element at position 0. Then successively choose a random number from i to 99, where i = 1 to 9 and swap the element at that position with the one at element i. Your 10 random numbers are in the first 10 positions of the array.


This may not be a solution depending on what you will need to use this for... but have you thought of splitting it off into 10 different random number generators? Ex. 0-9, 10-19, 20-29, etc. I guess that's not really as "random" as you are specifying different ranges and are guaranteed 1 number from each range. The only other solution I can think of would be to have a list of the random integers, iterate through and check to see if the random number has been generated yet and if so run the random.randint() again.


Here is a language independent solution:

integer numbers[10];
for(integer i = 0; i < 10; i += 1) {
    integer num = randomInteger(min = 0, max = (99 - i));
    boolean hasFoundDuplicate = false;
    for(integer j = 0; j < i && hasFoundDuplicate == false; j += 1) {
        if(numbers[j] == num) {
            num = 99 + 1 - i + j;
            hasFoundDuplicate = true;
        }
    }
    numbers[i] = num;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号