0

I'm working on a function that takes a square matrix (2D array), rotates it in steps of 90 degrees, then prints all 4 rotations. What I've been working on is printing these rotations side by side, rather than directly underneath each other. This is what I'm able to produce, given the first matrix shown below:

123
123
123

111
222
333

321
321
321

333
222
111

What I'm looking to achieve:

123  111  321  333
123  222  321  222
123  333  321  111

Any help on how to approach it is really appreciated as I've hit a dead and can't get anything to work.

code:

//get transformation of matrix
for(num_rotations = 0;num_rotations < 3;num_rotations++){
    for(row=0;row<num_rows;row++){
        for(col=0;col<3;col++){
            temp_arr[row][col] = working_arr[col][row];
        }
    }
}

Whilst inside the 1st 'for' loop, the 2nd and 3rd 'for' loops are then repeated, and the final line is replaced with:

working_arr[row][col] = temp_arr[row][3-col-1];//reverse columns for a single rotation

A print statement is placed at the end of the very first 'for' loop.

  • Where is your example code ? – Simion Aug 13 '18 at 11:36
  • I'm thinking its as simple as adding another loop or two somewhere...but I genuinely have no idea where to start. – R. Johnston Aug 13 '18 at 12:17
  • Calculate first, then print. – Lundin Aug 13 '18 at 14:17
  • 1
    Unless you want to be continually recalculating the rotated matrices, you'll need to collect the complete set of 4. Then you can step through the 4 matrices, printing the first row of each on one line, the second row of each on the next, and so on. You could recalculate each rotation on demand, as it were, but … well, there's a time-space trade-off. For small matrices, it might not matter much recomputing; for medium matrices, computing once becomes a benefit, until the matrices are so big that storing all 4 is problematic. – Jonathan Leffler Aug 13 '18 at 14:35

2 Answers2

2

If you just need to print it, you could do something like

for(int i=0; i<n; ++i)
{
    for(int j=0; j<n; ++j)
    {
        printf("%3d", arr[i][j]);
    }
    printf("\t");

    for(int j=0; j<n; ++j)
    {
        printf("%3d", arr[n-1-j][i]);
    }
    printf("\t");

    for(int j=n-1; j>=0; --j)
    {
        printf("%3d", arr[n-1-i][j]);
    }
    printf("\t");

    for(int j=0; j<n; ++j)
    {
        printf("%3d", arr[j][n-1-i]);
    }
    printf("\n");
}

where arr has the matrix of size n.

Here, the appropriate range of indices are used to print the rotated versions, one row at a time, from the original matrix without modifying the original.

J...S
  • 5,079
  • 1
  • 20
  • 35
0

Unless you store all 4 2D arrays and print them at the end all at once, it's pretty tough.

One other (messy) idea is to use gotoxy() to place the cursor where you want on the screen and print the elements of the 2D arrays as you rotate. How to position the input text cursor in C?

LIH
  • 36
  • 5