What is the best way to place numbers (1,2,3)
randomly in a matrix [10, 10]
in python?
I want to have an appearance of
1 = 20 times
2 = 30 times
3 = 50 times
What is the best way to place numbers (1,2,3)
randomly in a matrix [10, 10]
in python?
I want to have an appearance of
1 = 20 times
2 = 30 times
3 = 50 times
The principle here is to create a list/array with the values appearing a set number of times, shuffling that list/array and then reshaping it.
The starting point to generate the data:
a = [1 for x in range(20)]
b = [2 for x in range(30)]
c = [3 for x in range(50)]
full_array = a + b + c
A pure python approach might use this slightly adapted:
import random
def chunks(l, n):
n = max(1, n)
return [l[i:i+n] for i in range(0, len(l), n)]
random.shuffle(full_array)
matrix = chunks(full_array, 10)
If you use numpy
then things become easier:
import numpy as np
full_array = np.array(full_array)
np.random.shuffle(full_array)
matrix = full_array.reshape(10, 10)
I think a one-liner does exist for this. But until then this should work.
import numpy as np
temp=np.hstack((np.array([1]*20), np.array([2]*30), np.array([3]*50)))
np.random.shuffle(temp)
temp=temp.reshape(10, 10)
print(temp)
Maybe the best option is use numpy [1]
np.random.randint(5, size=(2, 4))
[1]https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html