user14263018
user14263018

Reputation:

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

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)

Upvotes: 3

Views: 1279

Answers (4)

Christian Sloper
Christian Sloper

Reputation: 7510

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.

Upvotes: 4

Ethan
Ethan

Reputation: 1373

Generate two ints and sort:

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

Upvotes: 0

Wagner
Wagner

Reputation: 1

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]

Upvotes: 0

mazore
mazore

Reputation: 1024

One approach world be to sort the random numbers after generation

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

Upvotes: 2

Related Questions