Uploaded by amrag201

algo assignment

advertisement
Lab Assignment 1
Name: Ahmed Mohamed Ahmed Amin
ID: 20P2629
Group 3 Sec on 5
Problem:
Fill the 3 × 3 table with nine distinct integers from 1 to 9 so
that the sum of the numbers in
each row, column, and corner-to-corner diagonal is the same.
How many ways are there to fill such a table?
Pseudocode:
Generate a list of 9 different numbers from 1 to 9.
Calculate the target sum = total numbers sum / 3
While table not found:
Generate a random permutation of the numbers.
Reshape the permutation into a 3x3 matrix.
Check if all rows, columns, and diagonals have equal sum
to the target sum .
If the table found exit the loop.
Print the table.
Implementation In Python:
import random
numbers = random.sample(range(1, 10), 9)
target_sum = sum(numbers) // 3
while True:
perm = random.sample(numbers, len(numbers))
matrix = [[perm[i], perm[i+1], perm[i+2]] for i in range(0, 9, 3)]
if all(sum(row) == target_sum for row in matrix) and \
all(sum(col) == target_sum for col in zip(*matrix)) and \
sum(matrix[i][i] for i in range(3)) == target_sum and \
sum(matrix[i][2-i] for i in range(3)) == target_sum:
break
for row in matrix:
print(row)
The Time Complexity is O(1) since it does not depend on the size of
the input or the number of times it is run
The number of valid tables is 9! = 362880
Download