user3414321
user3414321

Reputation: 421

2D rotation of rectangular array in C

I was experimenting around with 2d array manipulation in c. in-place rotation of a 2d shape in particular, so i did my research and came up with :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAD(x) ((x) * 3.14 / 180)

char shape[3][3] = {{1, 1, 1},
                    {1, 0, 1},
                    {1, 1, 1}};

char nf[5][5]= {{0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0}};

char expa[5][5]= {{0, 0, 1, 0, 0},
                  {0, 1, 0, 1, 0},
                  {1, 0, 0, 0, 1},
                  {0, 1, 0, 1, 0},
                  {0, 0, 1, 0, 0}};

void print(int row, int col, char shapein[][col]) {
  for (int i = 0; i < row; ++i) {
    for (int j = 0; j < col; ++j) {
      printf("%c", ((shapein[i][j]) == 1) ? '#' : ' ');
    }
    printf("\n");
  }
}

void main() {
  int nw = 5;
  int nh = 5;

  int xf = nw / 2;
  int yf = nh / 2;
  float angle = RAD(90);


  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      int nx = ((i - xf) * cos(angle) - (j - yf) * sin(angle)) + xf;
      int ny = ((i - xf) * sin(angle) + (j - yf) * cos(angle)) + yf;

      nf[nx][ny] = shape[i][j];
    }
  }

  print(5, 5, nf);
}

i was expecting to get output like this :

OK output

however what i get is :

Wrong output

i did what i understood from my research: - rotations do happen at origin (assuming top left corner) - moved coords so that it is in origin scale. - used output array's dimension as space when rotating.

I am stumped, i need a little help. while at it, as you can see from my code, i hard coded the new rotated dimensions, however, it would be nice if somebody could guide me how to calculate new rotated dimensions dynamically,without using the "maximum of corners" method.

Upvotes: 0

Views: 113

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224546

  1. The expected result you show looks like shape rotated by 45º, but you set the angle to 90º.

  2. You are working with integer coordinates but using floating-point functions. The sin and cos routines necessarily return approximations, and, when floating-point values are converted to integers, they are truncated. You may prefer rounding, perhaps using the round function.

  3. xf and yf appear to be set to the center of the image using nw / 2 and nh / 2, but they are integers, so the result, 2 in each case, is a considerable distance from the actual center, 2.5.

There are likely additional errors, but you should fix those and continue working. Also, take steps to debug your code. Inside the loop, print each value of xf, yf, nx, and ny so you can see the inputs and outputs of the calculations. Check them manually to see if they are right or not. If they are not right, examine the individual calculations to see what they are doing.

Upvotes: 1

Related Questions