Teemo
Teemo

Reputation: 459

Generate matrix NxN where average of row is in row and avrage of column is in column

I am solving some python problems and been bashing my head to solve this task. I need to generate matrix N x N filled with natural numbers where:

So far I have generated matrix and tried with random.choice but I don't see a way to handle it so that both row and columns have average present in that row/column.

Here is my code:

import random
used_numbers = []
matrix = []
matrix_done = False
rows_generated = 0

n = int(input("please enter number for nxn matrix: "))
start = 1
max_n = n

while(matrix_done is False):
    row = random.sample(range(start, max_n + 1), n)
    average = sum(row) / len(row)
    print("row", row, average)
    start = max_n + 1
    max_n = max_n + n

    print("start***", start, max_n)

    matrix.append(row)

    if(average > 0 and average.is_integer()):
        print("is integer true")
        rows_generated += 1

    if(rows_generated == n):
        matrix_done = True

for row in matrix:
    print(row)

Upvotes: 0

Views: 319

Answers (1)

I created the code below using the following principle:

  • If n is even: it is just an arithmetic progression
  • If n is odd: we have to compensate the last element of each line, column and the very last of them to ensure the average is inside the matrix

I defined a the start at 10 so it makes easy to check results. But you can make it start in any given random number if you wish.

import random
import numpy as np

# Get user inputs
n = int(input("please enter number for nxn matrix: "))
s =  10 # First element in the matrix. Can use random.randint(1, 100)
r = 2 # Arithmetic progression ratio
c = n*(r + 1) # How much change from one line to another. Use it to avoid having the same numbers

# Now we have to scenarios: the calculation is done differently if n is iven or odd
if (n % 2 == 0):
    elements = []
    for i in range(n):
        for j in range(n):
            e = s + r*j + c*i
            
            if j == n - 1 and i == n - 1: # Last element of the matrix
                e += c*n/2 + n
            elif j == n - 1: # last element of the line
                e += r*n/2
            elif i == n - 1: # last element of the column
                e += c*n/2
            else:
                pass
            elements.append(e)

else:
    # If the number is even, we just need to create an arithmetic progression and reshape it into a matrix
    elements = [s + r*i for i in range(n*n)]

matrix = np.reshape(elements, (n, n))
print(matrix)

Upvotes: 1

Related Questions