如何创建一个 1 的二维二进制数组,形成一个“菱形"形状 [英] How to create a 2D binary array with 1's forming a "diamond" shape

查看:57
本文介绍了如何创建一个 1 的二维二进制数组,形成一个“菱形"形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个函数,当给定边长时产生菱形.菱形数组应由 0 和 1 的值组成.

I need to create a function that results in a diamond shape when given a side length. The diamond array should consist of values of 0 and 1.

到目前为止我已经知道如何制作钻石,我不知道如何为不同边长编写函数

So far I figured out how to make the diamond, I don't know how to program a function for different side lengths

到目前为止,我有一个边长为 3 的解决方案:

So far I have this solution for a side length of 3:

import numpy as np

#line1
a=np.zeros(3+2)
a[3-1]=1

#line2
b=np.zeros(3+2)
b[3-2]=1
b[3]=1

#line3
c=np.zeros(3+2)
c[3-3]=1
c[3+1]=1

print(np.concatenate((a,b,c,b,a),axis=1).reshape(5,5))

如何编写不同长度的函数?
此外,如果给定长度为 1,则应返回 [[1]]

How could I write a function for different lengths?
Also, if given a length of 1 it should return [[1]]

推荐答案

您可以使用水平和垂直模式的交集来做到这一点:

You can do this using an intersection of horizontal and vertical patterns:

import numpy as np

N       = 5
H       = abs(np.arange(1-N,N+1,2))//2
V       = H[0] - H[:,None]
diamond = (H==V)*1

print(diamond)

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

在视觉上,这对应于行和列之间的相交数相等:

Visually, this corresponds to intersecting number equalities between rows and columns:

对于 N=7:

     [3, 2, 1, 0, 1, 2, 3]
   0  .  .  .  x  .  .  .         
   1  .  .  x  .  x  .  .
   2  .  x  .  .  .  x  .     
   3  x  .  .  .  .  .  x
   2  .  x  .  .  .  x  .
   1  .  .  x  .  x  .  .
   0  .  .  .  x  .  .  .

对于 N=8:

     [3, 2, 1, 0, 0, 1, 2, 3]
   0  .  .  .  x  x  .  .  .         
   1  .  .  x  .  .  x  .  .         
   2  .  x  .  .  .  .  x  .         
   3  x  .  .  .  .  .  .  x         
   3  x  .  .  .  .  .  .  x         
   2  .  x  .  .  .  .  x  .         
   1  .  .  x  .  .  x  .  .         
   0  .  .  .  x  x  .  .  .         

如果要填充菱形,使用diamond = (H<=V)*1

这篇关于如何创建一个 1 的二维二进制数组,形成一个“菱形"形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆