티스토리 뷰

Hobby/Code

[C] n squared matrix 덧셈

생각많은 소심남 2014. 5. 14. 02:55
  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <math.h>
  4 #include <time.h>
  5 
  6 #define SWAP(x, y, t)   ((t) = (x), (x) = (y), (y) = (t))
  7 
  8 #define MALLOC(ptr, size)  \
  9   if(!((ptr) = malloc(size))) { \
 10     fprintf(stderr, "Insufficient memory"); \
 11     exit(EXIT_FAILURE);\
 12   }
 13 
 14 #define CALLOC(ptr, n, size) \
 15   if(!((ptr) = calloc(n, size))){\
 16     fprintf(stderr, "Insufficient memory"); \
 17     exit(EXIT_FAILURE);\
 18   }
 19 
 20 #define REALLOC(ptr, size) \
 21   if(!((ptr) = realloc(ptr, size))){\
 22     fprintf(stderr, "Insufficient memory"); \
 23   }
 24 
 25 int** make2dArray(int rows, int cols);
 26 void add(int **a, int **b, int **c, int rows, int cols);
 27 
 28 void main(int argc, char* argv[])
 29 {
 30   int i, j;
 31   int n;
 32   int **A, **B, **C;
 33 
 34   n = atoi(argv[1]);
 35 
 36   A = make2dArray(n, n);
 37   B = make2dArray(n, n);
 38   C = make2dArray(n, n); 
 39 
 40   srand((unsigned)time(NULL));
 41   for(i = 0; i < n; ++i){
 42     for(j = 0; j < n; ++j){
 43       A[i][j] =rand() % 10;
 44       B[i][j] =rand() % 10;
 45     }
 46   }
 47 
 48   add(A, B, C, n, n);
 49 
 50   for(i = 0; i < n; ++i){
 51     printf("[ ");
 52     for(j = 0; j < n; ++j){
 53       printf("%d ", A[i][j]);
 54     }
 55     printf("] ");
 56 
 57     if(i == ((int)n/2)) printf("   +   ");
 58     else printf("       ");
 59 
 60     printf("[ ");
 61     for(j = 0; j < n; ++j){
 62       printf("%d ", B[i][j]);
 63     }
 64     printf("]");
 65 
 66     if(i == ((int)n/2)) printf("   =   ");
 67     else printf("       ");
 68 
 69     printf("[ ");
 70     for(j = 0; j < n; ++j){
 71       if(C[i][j] < 10) printf(" %d ", C[i][j]);
 72       else printf("%d ", C[i][j]);
 73     }
 74     printf("]\n");
 75   }
 76 }
 77 
 78 int** make2dArray(int rows, int cols)
 79 {
 80   int **x, i;
 81 
 82   CALLOC(x, rows, rows * sizeof(*x));
 83 
 84   for(i = 0; i < rows; ++i)
 85     CALLOC(x[i], cols, cols * sizeof(**x));
 86   return x;
 87 }
 88 
 89 void add(int **a, int **b, int **c, int rows, int cols)
 90 {
 91   int i, j;
 92 
 93   for(i = 0; i < rows; ++i){
 94     for(j = 0; j < cols; ++j){
 95       c[i][j] = a[i][j] + b[i][j];
 96     }
 97   }
 98 }
 99 


C로 쓴 자료구조론 연습문제 2.2.3 풀다가...

'Hobby > Code' 카테고리의 다른 글

[C] fifteen game  (0) 2014.05.26
[C] vigenere cipher  (1) 2014.05.25
[C] Caesar Cipher  (1) 2014.05.25
[ruby] Rock-Paper-Scissors class  (0) 2014.05.19
[ruby] Very simple class for dessert  (0) 2014.05.19
[Ruby] Palindrome, dictionary, anagram  (0) 2014.05.18
[python] count inversion with mergesort  (0) 2014.05.18
댓글