9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex47.c (2016B)
   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 #include <stdbool.h>
   4 #include <time.h>
   5 
   6 #define N 3
   7 #define M 3
   8 
   9 void m_load(size_t r, size_t c, double matrix[r][c]);
  10 void m_initrand(size_t r, size_t c, double matrix[r][c]);
  11 void m_print(size_t r, size_t c, double matrix[r][c]);
  12 void m_transpose(size_t r, size_t c, double matrix[r][c], double matrix_t[c][r]);
  13 
  14 bool m_isSimetric(size_t r, size_t c, double matrix[r][c]);
  15 
  16 
  17 int main (void)
  18 {
  19     double matrix[N][M];
  20     double matrix_transpose[M][N];
  21 
  22     m_load(N, M, matrix);
  23     m_print(N, M, matrix);
  24     putchar('\n');
  25     
  26     m_transpose(N, M, matrix, matrix_transpose);
  27     m_print(M, N, matrix_transpose);
  28 
  29     printf("\nThe matrix is %s SIMETRIC.", m_isSimetric(N, M, matrix) ? "" : "NOT");
  30 
  31     return 0;
  32 }
  33 
  34 void m_load(size_t r, size_t c, double matrix[r][c])
  35 {
  36     char buf[20];
  37     for(size_t i = 0; i < r; i++) {
  38         for(size_t j = 0; j < c; j++) {
  39             fgets(buf, 20, stdin);
  40             matrix[i][j] = strtod(buf, NULL);    /*    value from stdin    */ 
  41         }
  42     }
  43 }
  44 
  45 void m_initrand(size_t r, size_t c, double matrix[r][c])
  46 {
  47     srand((unsigned int)time(NULL));
  48 
  49     for(size_t i = 0; i < N; i++) {
  50         for(size_t j = 0; j < M; j++) {
  51             matrix[i][j] = ((double)rand()/(double)(RAND_MAX)) * 20;
  52         }
  53     }
  54 }
  55 
  56 void m_print(size_t r, size_t c, double matrix[r][c])
  57 {
  58     for(size_t i = 0; i < r; i++) {
  59         putchar('(');
  60         putchar(' ');
  61         for(size_t j = 0; j < c; j++) {
  62             printf("%6.2f ", matrix[i][j]);
  63         }
  64         putchar(')');
  65         putchar('\n');
  66     }
  67 }
  68 
  69 void m_transpose(size_t r, size_t c, double matrix[r][c], double matrix_t[c][r])
  70 {
  71     for(size_t i = 0; i < r; i++) {
  72         for(size_t j = 0; j < c; j++)
  73             matrix_t[j][i] = matrix[i][j];
  74 
  75     }
  76 }
  77 
  78 bool m_isSimetric(size_t r, size_t c, double matrix[r][c])
  79 {
  80     double matrix_transpose[r][c];
  81     m_transpose(r, c, matrix, matrix_transpose);
  82 
  83     size_t aux = 0;
  84     for(size_t i = 0; i < r; i++)
  85         for(size_t j = 0; j < c; j++)
  86             if(matrix[i][j] == matrix_transpose[i][j])
  87                 aux++;
  88 
  89     //if(aux == (r * c))
  90     //    return true;
  91 
  92     //return false;
  93     return true * (aux == (r * c)) + false * (aux != (r * c));
  94 }