Skip to content
Advertisement

Divide matrix into submatrix python

The program must accept an integer matrix of size R*C and four integers X, Y, P, Q as the input. The program must divide the matrix into nine submatrices based on the following condition. The program must divide the matrix horizontally after the Xth row and Yth row. Then the program must divide the matrix vertically after the Pth column and Qth column. Finally, the program must print the sum of integers in each submatrix as the output.

JavaScript

My program:

JavaScript

How to iterate from the given row and column and find the submatrix and print the sum?

Advertisement

Answer

Here are five solutions…

After reading all input like you did, you could go through the three boundary pairs for columns and the three boundary pairs for columns:

JavaScript

Same idea, slicing earlier / less often:

JavaScript

Or without slicing:

JavaScript

Or go through the matrix and update the right one of the nine sums:

JavaScript

Again a variation:

JavaScript

Try it online!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement