mardi 24 avril 2018

function that should Generate random matrix with sums of rows/columns defined as input lists

I've a task to make fuction that generates random matrix from non negative integers in range (0-8)

  • Input of the function are 2 lists :
    • sumForEveryCol
    • sumForEveryRow
  • Each list contains sum of the values for every rows/columns
  • Example: sumForEveryRow should contain sums for every row by it's index ( sumForEveryRow[0] = sum of the first row ... etc.)
  • sumForEveryColumn[0] = sum of the first column .. sumForEveryColumn[1] - second column .. etc.)
  • Sum of every row or column is constant value of 40
  • Value of any cell should be in range 0, 8

I've strange ideas (code below) but there is no chance to work at all.. because of the algorithm... What is the algorithm in general to generate such matrix and what is the best way to implement it in python

Example:

sumsForEveryRow = [4,20,8,8] = constant 40
sumsForEveryCol = [8,8,8,8,8] = constant 40

gen_random_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_random_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




Aucun commentaire:

Enregistrer un commentaire