I am trying to print the right hemisphere of a matrix. If we draw the main and the secondary diagonals in a matrix we see that we got 4 equal parts, the right part is called (in my algorithms textbook) the right hemisphere of a square matrix.
For example, in the following 5 x 5
matrix, the right hemisphere is made of the elements: -1, -3, -2, 0
.
The way I have tried to solve this problem is by starting and composing half of the secondary diagonal and then print each element on the right of the element on the left diagonal. After I reach the middle of the secondary diagonal I repeat this process on the lower part of the main diagonal.
Something like that (at least, this is how I see it in my head):
Here is some working code that prints the right hemisphere of a 5 x 5
matrix. It works, but it is ugly and it doesn't work properly of matrices that have even number of lines and columns, for example a 4 x 4
matrix.
#include <iostream>
#define N 5
#define M 5
void printHemisphere(int matrix[N][M], int n, int m)
{
int i = 1;
for(int j = n - 1; j > n / 2; i++, j--)
{
for (int k = j + 1; k < m; ++k)
{
std::cout << matrix[i][k] << " ";
}
std::cout << std::endl;
}
for(int j = n / 2; j < n; i++, j++)
{
for (int k = j + 1; k < m; ++k)
{
std::cout << matrix[i][k] << " ";
}
std::cout << std::endl;
}
}
int main(int argc, char const *argv[])
{
int matrix5[N][M] =
{
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
printHemisphere(matrix5, N, M);
return 0;
}
How would you approach this problem?