Reputation: 29
This line of code already create a 3x3 matrix populated with random numbers between 0 and 8, but some of them are duplicated. How to stop this?
initStateRandom = np.random.randint(9, size=(3,3))
Upvotes: 0
Views: 665
Reputation: 13
You can also use 'np.random.shuffle'. It works in-place, and only along one dimension for multi-dimensional arrays, so you'd need to shuffle a temporary 1-d array like this:
import numpy as np
tmp=np.arange(9)
np.random.shuffle(tmp)
mat=np.reshape(tmp,[3,3])
Upvotes: 0
Reputation: 3031
You can use choice
function from np.random
, see the documentation.
You can either pass in an int for the range or any ndarray.
import numpy as np
r_array = np.random.choice(9, size=(3, 3), replace=False) # int
r_array = np.random.choice(np.arange(10, 100), size=(3, 3), replace=False) # ndarray
Upvotes: 2