Rikudo Pain - 1 year ago 77

Python Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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]`

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**