2

I need to create a N x M numpy array of randomly shuffled numbers 0 to N. That is to say that each row of the matrix has exactly one of each numbers 0 to N in a random order with no repeating elements and every number is represented.

The best I've been able to come up with so far is (for N = 10 and M = 5)

import random
import numpy as np

a = np.array([random.sample(range(10), 10) for x in range(5)])

which gives me

[[5 9 1 3 8 2 6 4 0 7]
 [4 8 5 2 9 3 7 6 0 1]
 [8 4 6 7 9 2 0 5 1 3]
 [3 5 4 9 2 0 6 7 1 8]
 [6 0 4 7 3 2 1 8 5 9]]

My current solution does work, but I'd like to only have one random library if possible (I'm using numpy elsewhere so a numpy only solution would be ideal). I'm assuming numpy has an easier way to do this, but I'm currently missing it.

Grant Williams
  • 1,469
  • 1
  • 12
  • 24

1 Answers1

3

If the issue is simply to only use one random library (as you said in your comments), you could just use numpy.random.choice with the argument replace=False, which ensures each element is not repeated:

import numpy as np

a = np.stack([np.random.choice(range(10), 10, replace=False) for _ in range(5)])

>>> a
array([[0, 9, 3, 5, 8, 7, 1, 4, 6, 2],
       [5, 6, 8, 3, 0, 4, 7, 9, 2, 1],
       [7, 4, 9, 5, 0, 1, 6, 8, 3, 2],
       [9, 0, 3, 8, 5, 7, 6, 1, 4, 2],
       [5, 6, 0, 1, 3, 4, 9, 8, 7, 2]])
sacuL
  • 49,704
  • 8
  • 81
  • 106