Search code examples
c++matrixmirrorinverse

How to create the horizontally mirror inverse of a 2d matrix c++?


For example if the input is :

21 26 31 36
22 27 32 37
23 28 33 38
24 29 34 39
25 30 35 40

the output should be :

25 30 35 40
24 29 34 39
23 28 33 38
22 27 32 37
21 26 31 36

Al the rows are swapped until the middle row.

The first row should be swapped with the last one, the second with the before last one row, etc...

This is my code yet:

int A[100][100] = { 0 };
int n, m;
std::cin >> n >> m;


for (int k = 0, j = n - 1; k < j; k++, --j)
     std::swap(A[k], A[j]);

number of rows(n), columns(m), for n, m < 100 It shows me the same matrix as before.


Solution

  • You can swap the two dimensional array using std::reverse:

    #include <algorithm>
    #include <iostream>
    
    int main()
    {
        int A[100][100] = { {21, 26, 31, 36},
                            {22, 27, 32, 37},
                            {23, 28, 33, 38},
                            {24, 29, 34, 39},
                            {25, 30, 35, 40} };
    
        std::reverse(&A[0], &A[5]);  // Starting and ending ranges are &A[0] and &A[5]
    
        // Output results
        for (int i = 0; i < 5; ++i)
        {
            for (int j = 0; j < 4; ++j)
                std::cout << A[i][j] << " ";
            std::cout << "\n";
        }
    }
    

    Output:

    25 30 35 40 
    24 29 34 39 
    23 28 33 38 
    22 27 32 37 
    21 26 31 36