Reputation: 3
I am trying to recreate the game of life as an exercise but I don't know how to create the matrix and refer to the elements.
I tried this but it just create a array
for col in range(0,width):
for row in range(0,height):
at = np.append(at, 1 if rnd.random() < 0.2 else 0)
array = np.append(a, at)
array_temp = np.array([])
Upvotes: 0
Views: 34
Reputation: 1649
You can vectorize the randomization function and apply it to empty matrix:
import random
import numpy as np
def f(i):
return 1 if random.random() < 0.2 else 0
width = 5
height = 5
result = np.vectorize(f)(np.empty([width, height]))
print(result)
Upvotes: 0
Reputation: 1726
An alternate NumPy solution:
>>> import numpy as np
>>> seed = np.random.random((10,5))
>>> seed
array([[0.43419963, 0.12927612, 0.47783417, 0.6698047 , 0.43966626],
[0.56238954, 0.90856671, 0.84653548, 0.54566383, 0.98273554],
[0.13319855, 0.14511374, 0.44135731, 0.57732303, 0.63272811],
[0.67107476, 0.113417 , 0.25593979, 0.67509295, 0.35349618],
[0.86125898, 0.21895507, 0.46389417, 0.18839496, 0.90046474],
[0.03403771, 0.19303373, 0.02871153, 0.85036184, 0.95387585],
[0.3316397 , 0.84540023, 0.97718179, 0.95335886, 0.9703442 ],
[0.0221273 , 0.7636946 , 0.45536691, 0.64732677, 0.57123722],
[0.40939072, 0.49219486, 0.90310105, 0.12079284, 0.41212587],
[0.26332532, 0.52836011, 0.45873454, 0.69026349, 0.72141677]])
>>> board = np.where(seed < 0.2, 1, 0)
>>> board
array([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 0]])
Upvotes: 1
Reputation: 92450
You can avoid the loop and make a weighted Numpy matrix using numpy.random.choice
import numpy as np
width = 5
height = 4
np.random.choice(2, [height, width], p=[0.8, .2])
Gives you something like:
array([[1, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 1, 1],
[0, 0, 0, 0, 0]])
Upvotes: 0