Home > Software engineering >  shift matrix columns in c
shift matrix columns in c

Time:05-11

how can i shift each column of a matrix to the left by the row number ? for example

 0, 1, 2, 3
 4, 5, 6, 7
 8, 9,10,11
12,13,14,15 

this is a 4*4 matrix, the index of the first row is 0, therefore the columns will not move, the second row's index is 1, therefore each column will move 1 spot to the left (cyclically). the output for the given matrix is example

my function code is:

void ShiftRows(int message[M][M])
{
    int temp = 0;
    for (int i = 1; i < M ; i  ) 
    {
        for (int j = 0; j < M; j  )
        {
            temp = message[i][(j-i)%M];
            message[i][(j-i)%M] = message[i][j];
            message[i][j] = temp;
        } 
        temp = 0;
    }
}

CodePudding user response:

You only swap 2 values. That does not work for cyclically shift a whole row.

void ShiftRows(int message[M][M])
{
    for (int i = 1; i < M ; i  ) 
    {
        int temp[M];
        // First shift using a copy
        for (int j = 0; j < M; j  )
        {
            temp[j] = message[i][(j i)%M];
        }

        // After whole row is shifted, copy back
        for (int j = 0; j < M; j  )
        {
            message[i][j] = temp[j];
        } 
    }
}
  • Related