Generate a set amount of a value to appear in an array

Viewed 38

I am trying to generate a 2D list with NumPy that has 10 of one value, 5 of the other, and then leave all the rest blank.

This is my code:

arrOps = ["B", "T", " "]
board = np.random.choice(arrOps, size=(8,8), p=[0.078125,0.15625,0.765625])
print(board)

The probabilities should theoretically work, however they consistantly generate 11 or 12 of T, and only 3 or 4 of B. Is there anyway to make it so that the probabilities are set amounts?

1 Answers

As described in the comments:

(n, m) = (8, 8)
Ts = 10
Ns = 5

# create a array of 10T, 5B and the rest of blank
a = np.repeat(['T', 'B', ' '], (Ts, Ns, n*m-Ts-Ns))
# shuffle
np.random.shuffle(a)
# reshape
a = a.reshape(n, m)

Example output:

array([[' ', 'T', ' ', ' ', 'T', ' ', ' ', 'B'],
       [' ', ' ', ' ', 'T', ' ', ' ', ' ', 'B'],
       [' ', 'B', ' ', ' ', ' ', ' ', ' ', ' '],
       [' ', 'B', ' ', ' ', ' ', ' ', ' ', ' '],
       [' ', ' ', ' ', 'T', 'T', ' ', ' ', ' '],
       [' ', ' ', ' ', 'T', ' ', 'T', 'T', ' '],
       [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T'],
       [' ', ' ', 'T', ' ', ' ', ' ', 'B', ' ']], dtype='<U1')
Related