How to generate pairs of random numbers that first number is smaller than second one

Viewed 576

I want to generate pairs of random numbers that the first number is smaller than the second one like [[3 8] [2 5] [8 9] [8 10] [5 9] [3 7]]. I tried with the following code but since all the values generated randomly some of the first elements are greater than the second ones and some of them are equal.

a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
print(b)
4 Answers

Seems most solution so far don't take into account that two independently generated random numbers could be equal. (Which OP states he doesn't want).

I think sample is better.

from random import sample
sorted(sample(range(1,10),2))

This guarantees 2 unique numbers in increasing order.

One approach world be to sort the random numbers after generation

sorted([randint(1, 10), randint(1, 10)])  # [3, 7], [4, 6], [1, 10]

Well, since the number are just random, you can simply add the following to you code:

Same as you did:

a = random.randint(1, 10)    
b = np.random.randint(1, 10, (a, 2))     

Then:

b = [sorted(pair) for pair in b]

Generate two ints and sort:

sorted(np.random.randint(0,100,2))
[28, 94]
Related