Reputation: 461
I have piece of code :
V = numpy.floor(3*np.random.rand(5,5))
print V
It create random result of array in 5x5 table, how to add condition "1" only generate x times, "2" only generate y times, else are "0". Thanks
Upvotes: 0
Views: 60
Reputation: 206
How about the following?
import numpy as np
shape = (5, 5)
area = shape[0] * shape[1]
np.random.permutation([1]*x + [2]*y + [0]*(area-x-y)).reshape(shape)
Seems pretty simple. You take a random permutation of [1, ... 1, 2, ... 2, 0, ... 0]
and then you just turn it into a square. I'm not too sure but it also seems less computationally expensive and is also extensible to n
numbers or dimensions quite easily.
Upvotes: 1
Reputation: 574
Try this:
import numpy as np
def newArray( x, y, n):
if x + y > n ** 2:
print "Values error!"
return
res = [[0 for col in range(n)] for row in range(n)]
# Create roulette
roulette = range(0, n ** 2)
printkxtimes(res, roulette, 1, x, n)
printkxtimes(res, roulette, 2, y, n)
print res
# This function draws random element from roulette,
# gets the position in array and sets value of this position to k.
# Then removes this element from roulette to prevent drawing it again
def printkxtimes(array, roulette, k, x, n):
for i in xrange(0, x):
r = int(np.floor(roulette.__len__()*np.random.rand(1))[0])
array[roulette[r] / n][roulette[r] % n] = k
roulette.pop(r)
newArray(10,2,5)
A little explanation of roulette
:
Every element of table res
can be represented equivalently with a number from range(0, n^2)
:
z = row*n + column <=> row = int(z/n) , column= z%n
We can then represent the list of positions in table res
as the table [0,1,...,n^2-1]
Upvotes: 1