Advertisement
VSZM

2d arrays

May 15th, 2014
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. /*
  5. 1 2 3
  6. 4 5 6
  7. 7 8 9
  8. ==>
  9. 9 6 3
  10. 8 5 2
  11. 7 4 1
  12.  
  13.  
  14. n = 3
  15.  
  16. i j      x y
  17. 0 0  <-> 2 2
  18. 0 1  <-> 1 2
  19. 1 0  <-> 2 1
  20.  
  21. x = n - j -1
  22. y = n - i -1
  23. */
  24.  
  25. void mirror_flattened(int *t, int n)
  26. {
  27.     int i, j;
  28.  
  29.     for(i = 0; i < n - 1; ++i)
  30.     {
  31.         for(j = 0; j < n - i; ++j)
  32.         {
  33.             int x = n - j - 1, y = n - i - 1, tmp;
  34.             tmp = t[i * n +  j];
  35.             t[i * n + j] = t[x * n + y];
  36.             t[x * n + y] = tmp;
  37.         }
  38.     }
  39. }
  40.  
  41.  
  42.  
  43. void mirror_jagged(int **t, int n)
  44. {
  45.     int i, j;
  46.  
  47.     for(i = 0; i < n - 1; ++i)
  48.     {
  49.         for(j = 0; j < n - i; ++j)
  50.         {
  51.             int x = n - j - 1, y = n - i - 1, tmp;
  52.             tmp = t[i][j];
  53.             t[i][j] = t[x][y];
  54.             t[x][y] = tmp;
  55.         }
  56.     }
  57. }
  58.  
  59.  
  60. int main()
  61. {
  62.     int M[3][3] = { {1,2,3},
  63.                     {4,5,6},
  64.                     {7,8,9}};
  65.     int **t, i, j, x;
  66.     t = (int**) malloc(3*sizeof(int*));
  67.  
  68.     x = 1; 
  69.     for(i = 0; i < 3; ++i) 
  70.     {
  71.         t[i] = (int*) malloc(3*sizeof(int));
  72.         for(j = 0; j < 3; ++j)
  73.             t[i][j] = x++;
  74.     }
  75.  
  76.     mirror_flattened((int*)M,3);
  77.  
  78.     for(i = 0; i < 3; ++i) 
  79.     {
  80.         for(j = 0; j < 3; ++j)
  81.             printf("%d ", M[i][j]);
  82.         printf("\n");
  83.     }
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement