用条件随机填充二维矩阵

randomly fill 2d matrix with conditions

这是我的情况,我只是把它扔在那里以了解如何处理它。

我有类别 categories = [0, 1, 3] 和一个 10 x 5 矩阵,A

我如何用类别中的随机选择填充矩阵 A,使得每一列必须有一次且仅出现一次“0”和一次且仅出现一次“1”?

我的思考过程是:

For each column, Cj, 
    create list L = selection of random integers between [0,9] ( no replacement) 
    Set Cj[k[0]] = 0 and Cj[k[1]] = 1 
    Set Cj[k[i]] , i=2, ..,9

有没有人有更好的方法来解决这个问题?

你的问题有点含糊。请提供更多关于您在其他职位上可以拥有什么的详细信息。如果一个位置是 0 和 1 位置是 1 和其他位置可以是任何东西,而不是使用这个。

制作一个数组[number_of_columns] = {0,1,2,2,....,2],随机播放它。然后对于第 (i) 列中的每个位置 if (array[i] = 0){array_you_are_making[i]=0};if(array[i] = 1){array_you_are_making[i]=1};if(array[i] = 2){array_you_are_making[i]="do something"};

听起来像是 Python shuffle() 方法的情况。

这是假设您已经拥有矩阵的一种方法。 (题目说的是fill a matrix,不是create a matrix)

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []

for row in matrix:
    tempRow = restrictedNumbers #first add the restricted numbers since they must appear once
    while len(tempRow) < len(row): #keep adding numbers from unrestricted till lengths are equal
        tempRow.append(random.choice(unrestrictedNumbers))
    random.shuffle(tempRow) 
    newMatrix.append(tempRow[:]) #finally add the shuffled row to newMatrix
pprint.pprint(newMatrix)

这给出了输出:(显然会因随机而异)

[[3, 1, 3, 0, 3],
 [3, 3, 0, 1, 3],
 [0, 3, 1, 3, 3],
 [0, 3, 1, 3, 3],
 [3, 3, 0, 3, 1],
 [0, 1, 3, 3, 3],
 [1, 0, 3, 3, 3],
 [1, 3, 0, 3, 3],
 [3, 3, 0, 3, 1],
 [3, 0, 1, 3, 3]]

你可以看到每一行都有一个0和一个1

这里有一个更短的方法:

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []
for row in matrix:
    row = restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row)-len(restrictedNumbers))]
    random.shuffle(row)
    newMatrix.append(row)
pprint.pprint(newMatrix)



甚至比那更短(如果 random.shuffle 返回列表而不是就地洗牌,这将是一行)

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
def returnShuffled(startList):
    random.shuffle(startList)
    return startList

newMatrix = [returnShuffled(restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row) - len(restrictedNumbers))]) for row in matrix]
pprint.pprint(newMatrix)