Advertisement
xathrya

Nom nom

May 2nd, 2015
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5. N = 5
  6.     5       6       7       8       9
  7.     4       19      18      17      10
  8.     3       20      25      16      11
  9.     2       21      24      15      12
  10.     1       22      23      14      13
  11.    
  12. N = 7
  13.     7       8       9       10      11      12      13
  14.     6       29      28      27      26      25      14
  15.     5       30      39      40      41      24      15
  16.     4       31      38      49      42      23      16
  17.     3       32      37      48      43      22      17
  18.     2       33      36      47      44      21      18
  19.     1       34      35      46      45      20      19
  20. */
  21.  
  22. void printm(int *matriks, int n)
  23. {
  24.     int i, j;
  25.    
  26.     for (i=0; i<n; i++)
  27.     {
  28.         for (j=0; j<n; j++)
  29.         {
  30.             printf("%d\t", matriks[i*n + j]);
  31.         }
  32.         printf("\n");
  33.     }
  34.    
  35.     printf("\n\n");
  36. }
  37.  
  38. int main()
  39. {
  40.     int n, i, j, k, dim, count, geser, batas;
  41.     int *matriks;
  42.    
  43.     printf("Input: ");
  44.     scanf("%d", &n);
  45.    
  46.     matriks = malloc(n*n*sizeof(int));
  47.    
  48.     for (i=0; i<n; i++)
  49.     {
  50.         for (j=0; j<n; j++)
  51.         {
  52.             matriks[i*n + j] = 0;
  53.         }
  54.     }    
  55.    
  56.     i     = n-1;    
  57.     j     = 0;
  58.     dim   = n/2;
  59.     geser = 1;
  60.     batas = n;
  61.     count = 0;
  62.    
  63.     printf("Output:\n");
  64.    
  65.     for (k=0; k<dim; k++)
  66.     {
  67.         for (; i >= k; i--) {
  68.             matriks[i*n + j] = ++count;
  69.         }
  70.         i++;
  71.         for (j += geser; j != batas; j += geser) {
  72.             matriks[i*n + j] = ++count;
  73.         }
  74.         j -= geser;
  75.         for (i++; i < n; i++) {
  76.             matriks[i*n + j] = ++count;
  77.         }
  78.         i--;
  79.                
  80.         if (k%2==0) {
  81.             geser = -1;
  82.             batas = k;
  83.             j--;
  84.         } else {
  85.             geser = 1;
  86.             batas = n-k-1;
  87.             j++;
  88.         }
  89.     }
  90.    
  91.     // If we still have leftover
  92.     if (n % 2 == 1)
  93.     {
  94.         for (; i >= dim; i--)
  95.             matriks[i*n + j] = ++count;
  96.     }
  97.    
  98.     printm(matriks, n);
  99.     free(matriks);
  100.    
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement