Advertisement
STANAANDREY

exam simu

Jan 14th, 2023 (edited)
764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. typedef long long int llint;
  5.  
  6. int **allocMat(int rows, int cols) {
  7.   int **mat = (int**)malloc(sizeof(int*) * rows);
  8.   for (int i = 0; i < rows; i++) {
  9.     mat[i] = (int*)malloc(sizeof(int) * cols);
  10.   }
  11.   return mat;
  12. }
  13.  
  14. void readMatElems(int **mat, int rows, int cols) {
  15.   for (int i = 0; i < rows; i++) {
  16.     for (int j = 0; j < cols; j++) {
  17.       scanf("%d", &mat[i][j]);
  18.     }
  19.   }
  20. }
  21.  
  22. int **readMat(int *rows, int *cols) {
  23.   scanf("%d %d", rows, cols);
  24.   int **mat = allocMat(*rows, *cols);
  25.   readMatElems(mat, *rows, *cols);
  26.   return mat;
  27. }
  28.  
  29. llint sumOnRow(int **mat, int targetRow, int cols) {
  30.   llint sum = 0;
  31.   for (int j = 0; j < cols; j++) {
  32.     sum += mat[targetRow][j];
  33.   }
  34.   return sum;
  35. }
  36.  
  37. void sortMatLines(int **mat, int rows, int cols) {
  38.   bool sorted;
  39.   do {
  40.     sorted = true;
  41.     for (int i = 1; i < rows; i++) {
  42.       if (sumOnRow(mat, i - 1, cols) > sumOnRow(mat, i, cols)) {
  43.         int *aux = mat[i - 1];
  44.         mat[i - 1] = mat[i];
  45.         mat[i] = aux;
  46.         sorted = false;
  47.       }
  48.     }
  49.   } while(!sorted);
  50. }
  51.  
  52. llint sumOnCol(int **mat, int targetCol, int rows) {
  53.   llint sum = 0;
  54.   for (int i = 0; i < rows; i++) {
  55.     sum += mat[i][targetCol];
  56.   }
  57.   return sum;
  58. }
  59.  
  60. bool colsSorted(int **mat, int rows, int cols) {
  61.   for (int j = 1; j < cols; j++) {
  62.     if (sumOnCol(mat, j - 1, rows) > sumOnCol(mat, j, rows)) {
  63.       return false;
  64.     }
  65.   }
  66.   return true;
  67. }
  68.  
  69. void displayMat(int **mat, int rows, int cols) {
  70.   for (int i = 0; i < rows; i++) {
  71.     for (int j = 0; j < cols; j++) {
  72.       printf("%d ", mat[i][j]);
  73.     }
  74.     printf("\n");
  75.   }
  76. }
  77.  
  78. void freeMat(int **mat, int rows, int cols) {
  79.   for (int i = 0; i < rows; i++) {
  80.     free(mat[i]);
  81.   }
  82.   free(mat);
  83. }
  84.  
  85. int main(void) {
  86.   int rows, cols, **mat = NULL;
  87.   mat = readMat(&rows, &cols);
  88.  
  89.   sortMatLines(mat, rows, cols);
  90.  
  91.   puts("");
  92.   displayMat(mat, rows, cols);
  93.  
  94.   printf("columns sorted: %s\n", (colsSorted(mat, rows, cols) ? "true" : "false"));
  95.  
  96.   freeMat(mat, rows, cols);
  97.   return 0;
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement