2d array diamond shape of 1's of size x

Viewed 786

Hey I am trying to make a 2d array consisting of 1's and 0's where the 1's form a diamond shape. The diamond should be of size x:

A size x = 3 diamond shape would look like this:

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

A size x = 1 diamond shape would look this:

[[1]]

Does anyone have an idea how to implement this? I thought numpy.eye and concatenate might be useful. However, I could not find a solution

7 Answers

I would harness numpy.diagflat combined with numpy.flip following way:

import numpy as np
arr = np.diagflat([1,1,1],2)  # now we have 1s in upper-right part
arr = np.maximum(arr,np.flip(arr,1))  # now we have 1s in upper part
arr = np.maximum(arr,np.flip(arr,0))  # now we have 1s everywhere
print(arr)

output:

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

Here a solution with np.eye

import numpy as np

def diamond(n):
    a, b = np.eye(n, dtype=int), np.eye(n, dtype=int)[:,::-1]

    c, d = np.hstack((b,a[:,1:])), np.hstack((a,b[:,1:]))

    return np.vstack((c, d[1:,:]))

ouput:

>>> print(diamond(3))

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

My entry using np.pad(... mode = 'reflect'):

def diamond(n):
    return np.pad(np.eye(n), ((n-1, 0), (0, n-1)), mode = 'reflect')
    

diamond(3)
Out: 
array([[0., 0., 1., 0., 0.],
       [0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 1.],
       [0., 1., 0., 1., 0.],
       [0., 0., 1., 0., 0.]])

diamond(1)
Out: array([[1.]])

diamond(5)
Out: 
array([[0., 0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 1., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 1., 0.],
       [1., 0., 0., 0., 0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0., 0., 0., 1., 0.],
       [0., 0., 1., 0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0., 0.]])

In my timings this is about 40% faster than @Daweo's answer, and somewhat simpler code

def diamond_Daweo(n):
    arr = np.diagflat(np.ones(n), n-1)  # now we have 1s in upper-right part
    arr = np.maximum(arr,np.flip(arr,1))  # now we have 1s in upper part
    return np.maximum(arr,np.flip(arr,0))  # now we have 1s everywhere

%timeit diamond_Daweo(100)
120 µs ± 1.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit diamond(100)
75.8 µs ± 2.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

The below solution uses numpy.eye and numpy.flip to define arrays of the correct size filled with ones representing the lines required to draw a diamond (one diagonal left-upwards (lu) and one diagonal left-downwards(ld).

numpy.zeros is then used to create an array of the correct dimensions to store a diamond with size ones on each edge (d). Each dimension is size*2-1 to allow for full width of both lines along each axis with the -1 accounting for vertices/corners.

Then, numpy.where is used to effectively map both types of line generated above to correct positions on d to "draw" a diamond in ones. This is achieved by first slicing d so that each line starts at the correct index before lu/ld are used to generate a mask applied across the relevant selection to fill the ones.

import numpy as np

def diamond(size):
    lu = np.eye(size) # Define left-upward edge
    ld = np.flip(lu, axis=0) # Define left-downward edge
    d = np.zeros((lu.shape[0]*2-1, lu.shape[1]*2-1)) # Create empty array of correct size filled with zeros
    mid = size-1 # Store mid-point index of each axis
    d[np.where(ld==1)] = 1 # Write upper left-centre edge
    d[:,mid:][np.where(lu==1)] = 1 # Write upper centre-right edge
    d[mid:,mid:][np.where(ld==1)] = 1 # Write lower right-centre edge
    d[mid:,:][np.where(lu==1)] = 1 # Write lower left-centre edge
    return d.astype(int) # Return diamond shaped array with values int instead of float

print(diamond(1),'\n')
print(diamond(2),'\n')
print(diamond(3),'\n')
print(diamond(4),'\n')

Output

[[1]]

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

[[0 0 0 1 0 0 0]
 [0 0 1 0 1 0 0]
 [0 1 0 0 0 1 0]
 [1 0 0 0 0 0 1]
 [0 1 0 0 0 1 0]
 [0 0 1 0 1 0 0]
 [0 0 0 1 0 0 0]]

If you want to go with the numpy.eye, this works. Although it is a little bit complicated.

dim = 8
A = np.maximum(np.maximum(np.maximum(np.eye(dim, k=-(dim//2)), np.eye(dim, k=(dim//2))), np.fliplr(np.eye(dim, k=(dim//2)))), np.fliplr(np.eye(dim, k=-(dim//2))))

Generic code to make diamond matrix of any desired size. Using identity matrix and slicing techniques.

import numpy as np

x = 5  # assuming, this will always be odd

result_sz = 2*x-1
mid_pt = int(np.floor(result_sz/2.0))

result = np.zeros((result_sz, result_sz), dtype=np.int)
tile = np.eye(x)

# we have four regular graph quadrants
# first quadrant
result[0:x, mid_pt:] = tile    # direct identity
# second quadrant
result[mid_pt:, mid_pt:] = np.flip(tile, axis=1)     # identity flipped about y-axis
# third quadrant
result[mid_pt:, 0:x] = tile   # direct identity
# fourth quadrant
result[0:x, 0:x] = np.flip(tile, axis=0)     # identity flipped about x-axis

# The diamond matrix
print(result)
def diamond(m):
    n = 2 * m - 1
    res = [[0] * n for _ in range(n)]
    # make first m lines
    for x in range(m):
        res[x][m - x - 1] = 1
        res[x][n - (m - x)] = 1
    # copy other lines as they as symmetric with above line by line m - 1
    for x in range(m, n):
        res[x] = res[2 * (m - 1) - x][:]
    return res
Related