Home > Blockchain >  swap all elements from opposite lines in a C matrix
swap all elements from opposite lines in a C matrix

Time:02-02

I would like to change each element of the matrix with its "opposite" (element 0,0 becomes element n, n element 0,1 becomes n, n-1 and etc ..).

below an example:

1 2 3      9 8 7
4 5 6  --> 6 5 4
7 8 9      3 2 1

or:

4 5 4 7            22 14 12 2
5 2 6 8       ---> 2 4 6 2
2 6 4 2            8 6 2 5
2 12 14 22         7 4 5 4

anyone have any ideas on how to do it?

CodePudding user response:

It is enough to use the standard algorithm std::reverse to perform the task.

Here is a demonstration program.

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    const size_t N1 = 3;
    int a[N1][N1] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    std::reverse( std::begin( a ), std::end( a ) );

    for ( auto &row : a )
    {
        std::reverse( std::begin( row ), std::end( row ) );
    }

    for (const auto &row : a)
    {
        for (const auto &item : row)
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';

    const size_t N2 = 4;
    int b[N2][N2] =
    {
        { 4,  5,  4,  7 },
        { 5,  2,  6,  8,},
        { 2,  6,  4,  2 },
        { 2, 12, 14, 22 }
    };

    std::reverse( std::begin( b ), std::end( b ) );

    for (auto &row : b)
    {
        std::reverse( std::begin( row ), std::end( row ) );
    }

    for (const auto &row : b)
    {
        for (const auto &item : row)
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';
}

The program output is

9 8 7
6 5 4
3 2 1

22 14 12 2
2 4 6 2
8 6 2 5
7 4 5 4

You could write a separate function to perform such an operation like

template <typename T, size_t N>
void reverse_matrix( T ( &a )[N][N] )
{
    std::reverse( std::begin( a ), std::end( a ) );

    for (auto &row : a)
    {
        std::reverse( std::begin( row ), std::end( row ) );
    }
}

Without using the standard algorithm std::reverse you will need to use loops as for example

for ( size_t i = 0; i < N1 / 2; i   )
{
    std::swap( a[i], a[N1-i-1] );
}

for ( size_t i = 0; i < N1; i   )
{
    for ( size_t j = 0; j < N1 / 2; j   )
    {
        std::swap( a[i][j], a[i][N1-j-1] );
    }
} 

CodePudding user response:

You can do it simply with for loop. This is code:

#include <iostream>
using namespace std;
 
int main(){
 int n;
 cin>>n;
 int arr[n][n], arr1[n][n];
 for(int i = 0; i < n; i  ){
   for(int j = 0; j < n; j  )
     cin>>arr[i][j];
 }
 for(int i = 0; i < n; i  ){
   for(int j = 0; j < n; j  )
      arr1[i][j] = arr[n-1-i][n-1-j];
 }

 for(int i = 0; i < n; i  ){
   for(int j = 0; j < n; j  ){
     cout<<arr1[i][j]<<" ";
   }
   cout<<endl;
 }
}
  •  Tags:  
  • Related