user000
user000

Reputation: 49

Numpy array filled with random numbers so that you only change the value by one along the x/y axis

I know how to create a numpy array filled with random numbers, for instance, this : np.random.randint(0, 100, (5, 5)).

But how do you create a numpy array filled with random numbers so that the difference between two adjacent cells is 1 or less ?

Thanks

Upvotes: 2

Views: 2791

Answers (1)

unutbu
unutbu

Reputation: 879421

Every row can differ by 1. So generate an array of differences:

In [83]: H, W = 5, 5

In [84]: np.random.randint(-1, 2, size=(H,1))
Out[84]: 
array([[ 1],
       [-1],
       [-1],
       [-1],
       [ 0]])

Now find the cumulative sums:

In [85]: np.add.accumulate([[ 1], [-1], [-1], [-1], [ 0]])
Out[85]: 
array([[ 1],
       [ 0],
       [-1],
       [-2],
       [-2]])

Similarly, every column can differ by 1. So again generate an array of differences, and find the cumulative sums:

In [86]: np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
Out[86]: array([[1, 1, 2, 1, 1]])

Now add these two cumulative sums together. Broadcasting creates a 2D array:

import numpy as np

H, W = 5, 5
x = np.add.accumulate(np.random.randint(-1, 2, size=(H,1)), axis=0)
y = np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
out = x + y
print(out)

prints a random array such as

[[ 1  0 -1  0 -1]
 [ 2  1  0  1  0]
 [ 3  2  1  2  1]
 [ 3  2  1  2  1]
 [ 2  1  0  1  0]]

You can add constants to this array to generate other random arrays with the same property.

Upvotes: 4

Related Questions