我有一个任务来创建从范围(0-8)中的非负整数生成矩阵的函数
我有一些奇怪的想法(下面的代码),但根本没有机会工作..因为算法...一般来说生成这样的矩阵的算法是什么?实现它的最佳方法是什么蟒
示例:
sumsForEveryRow = [4,20,8,8] = constant 40
sumsForEveryCol = [8,8,8,8,8] = constant 40
gen_matrix(sumForEveryRow, sumForEveryCol) should produce random matrix like:
[ 0 , 2 , 0 , 0 , 2 ], - sum of row 1 should be 4
[ 1 , 2 , 8 , 5 , 4 ], - sum of row 2 should be 20
[ 3 , 2 , 0 , 3 , 0 ], - sum of row 3 should be 8
[ 4 , 2 , 0 , 0 , 2 ], - sum of row 4 should be 8
sum for every column should be
8 8 8 8 8
import random
import numpy
sumsForEveryCol = [8,8,8,8,8]
sumsForEveryRow = [4,20,8,8]
def gen_matrix(sumForEveryCol, sumForEveryRow):
sum = 40
max_value_cell = 8
num_of_rows = len(sumsForEveryRow)
num_of_cols = len(sumsForEveryCol)
matrix = numpy.zeros((num_of_rows, num_of_cols), dtype=numpy.int)
for i in range(0, num_of_rows - 1):
cur_row_sum = sumsForEveryRow[i]
for j in range(0, num_of_cols - 1):
if max_value_cell >= cur_row_sum:
if cur_row_sum == 0:
matrix[i][j] = 0
else:
# Dont generate 0 values ????
rand_digit = random.randint(1, cur_row_sum)
cur_row_sum = cur_row_sum - rand_digit
matrix[i][j] = rand_digit
else:
rand_digit = random.randint(0, max_value_cell)
matrix[i][j] = rand_digit
cur_row_sum = cur_row_sum - rand_digit
return matrix