fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void init(FILE* f, int** avrs, int*** lines, int n) {
  5. const int m = 5;
  6. int i;
  7. int j;
  8. int s;
  9. int* as;
  10. int** ls;
  11. int* l;
  12.  
  13. /* read data */
  14. ls = malloc(sizeof(int*) * n);
  15. for (i = 0; i < n; i++) {
  16. l = malloc(sizeof(int) * m);
  17. fscanf(f, "%d %d %d %d %d%*c", &l[0], &l[1], &l[2], &l[3], &l[4]);
  18. ls[i] = l;
  19. }
  20.  
  21. /* compute average */
  22. as = malloc(sizeof(int) * n);
  23. for (i = 0; i < n; i++) {
  24. l = ls[i];
  25. s = 0;
  26. for (j = 1; j < m; j++) {
  27. s += l[j];
  28. }
  29. as[i] = s / (m - 1);
  30. }
  31.  
  32. *avrs = as;
  33. *lines = ls;
  34. }
  35.  
  36. void sort(int* avrs, int** lines, int n) {
  37. int i;
  38. int j;
  39. int t1;
  40. int* t2;
  41.  
  42. for (i = 0; i < n - 1; i++) {
  43. for (j = 0; j < n - 1; j++) {
  44. if (avrs[j] < avrs[j + 1]) {
  45. t1 = avrs[j];
  46. avrs[j] = avrs[j + 1];
  47. avrs[j + 1] = t1;
  48.  
  49. t2 = lines[j];
  50. lines[j] = lines[j + 1];
  51. lines[j + 1] = t2;
  52. }
  53. }
  54. }
  55. }
  56.  
  57. void print(int* avrs, int** lines, int n) {
  58. int i;
  59. int* line;
  60. for (i = 0; i < n; i++) {
  61. line = lines[i];
  62. printf("avr:%d %d %d %d %d %d\n", avrs[i], line[0], line[1], line[2], line[3], line[4]);
  63. }
  64. }
  65.  
  66. void term(int* avrs, int** lines, int n) {
  67. int i;
  68. free(avrs);
  69. for (i = 0; i < n; i++) {
  70. free(lines[i]);
  71. }
  72. free(lines);
  73. }
  74.  
  75. int main(void) {
  76. int n;
  77. int* avrs;
  78. int** lines;
  79. FILE* f;
  80.  
  81. f = fopen("test.dat", "r");
  82. fscanf(f, "%d%*c", &n);
  83. init(f, &avrs, &lines, n);
  84. fclose(f);
  85. sort(avrs, lines, n);
  86. print(avrs, lines, n);
  87. term(avrs, lines, n);
  88.  
  89. return EXIT_SUCCESS;
  90. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty