小编KHC*_*KHC的帖子

生成拉丁方块的有效方法(或在两个轴上唯一地在矩阵中随机置换数字 - 使用NumPy)

例如,如果有5个数字1,2,3,4,5

我想要一个随机的结果

[[ 2, 3, 1, 4, 5]
 [ 5, 1, 2, 3, 4]
 [ 3, 2, 4, 5, 1]
 [ 1, 4, 5, 2, 3]
 [ 4, 5, 3, 1, 2]]
Run Code Online (Sandbox Code Playgroud)

确保其行和列中的每个数字都是唯一的.

有没有一种有效的方法来做到这一点?

我尝试使用while循环为每次迭代生成一行,但似乎效率不高.

import numpy as np

numbers = list(range(1,6))
result = np.zeros((5,5), dtype='int32')
row_index = 0
while row_index < 5:
    np.random.shuffle(numbers)
    for column_index, number in enumerate(numbers):
       if number in result[:, column_index]:
           break
       else:
           result[row_index, :] = numbers
           row_index += 1
Run Code Online (Sandbox Code Playgroud)

python numpy scipy

7
推荐指数
2
解决办法
599
查看次数

标签 统计

numpy ×1

python ×1

scipy ×1