在正方形的特定区域中创建随机数

时间:2017-06-09 09:56:35

标签: python algorithm

我正在尝试创建这样一个在每个区域中具有不同密度元素的对称矩阵。

enter image description here

矩阵为256x256等级1 我有16个正方形,长度为16,每个有10个元素:

#LEVEL I
C = np.zeros((256,256))
s = 0
for k in range(16):
    if k > 0:
        s += 16
    while m < 10: #number of elements in most inner square
        i,j = np.random.randint(s,s+16,size=2) # randint(low,high,size)
        C[i,j] = C[j,i] = 1
        m = 0.5 * np.sum(C[s:s+16,s:s+16])  # count the number of elements

2级我有4个正方形,长度为64个,每个都有4个元素,除了小方块内的元素(4个方块,每个10个元素+ 4个元素,大方块)。

对于2级,我需要创建与小方块不重叠的整数随机数。

#LEVEL II
s = 0
for k in range(4):
    if k>0:
        s += 64
    while m < (40+4):
        # create i,j with no overlapping with small squares
        C[i,j]=C[j,i] = 1
        m = 0.5 * np.sum(C[s:s+64,s:s+64])

我感谢任何想法或评论。

#Edit 我认为一个解决方案可以定义另一个方形矩阵,其子方格都是aij = 1,并比较每个while循环中元素的数量。

1 个答案:

答案 0 :(得分:0)

import numpy as np

# Matrix size and inner squares length
s = 256
L2 = 64
L1 = 16

# Create matrix and masks along MAIN diagonal
C = 1 - np.random.random((s, s))
L2_mask = np.array([range(s)]*s)//L2 + np.array([range(s-1, -1, -1)]*s).T//L2
L1_mask = np.array([range(s)]*s)//L1 + np.array([range(s-1, -1, -1)]*s).T//L1

# Fill in inner squares
C[np.where(L2_mask == 3)] = np.random.randint(2, 10, 16384)
C[np.where(L1_mask == 15)] = np.random.randint(100, 200, 4096)

为了生成对称矩阵,我可以建议两种方法:

# Turn matrix into symmetric
C_symm = (C + C.T)//2

# Turn matrix into symmetric
C_symm = np.tril(C) + np.tril(C, -1).T

现在只需翻转它:

# Flip it
C_final = np.fliplr(C_symm)