Advertisement
Guest User

Words-Numbers

a guest
Jun 19th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include <string.h>
  5. #define MAX 50
  6.  
  7. // Перевод строки в нижний регистр
  8. char* str_tolower(char* str)
  9. {
  10. int count = 0;
  11. char* result = (char*)malloc(MAX * sizeof(char));
  12. while (str[count] != 0)
  13. {
  14. result[count] = (char) tolower(str[count]);
  15. count++;
  16. }
  17.  
  18. result[count] = 0;
  19.  
  20. return result;
  21. }
  22.  
  23. // Поиск индекса в массиве строк
  24. int find_index(char** arr, char* key)
  25. {
  26. int i;
  27. for (i = 0; i < MAX; i++)
  28. {
  29. if (arr[i] == NULL || strcmp(arr[i], str_tolower(key)) == 0)
  30. return i;
  31. }
  32.  
  33. return 0;
  34. }
  35.  
  36. // Сортировка 2 массивов
  37. void sort(char** keys, int* values)
  38. {
  39. int i, j, n = 0;
  40. while (keys[n] != NULL)
  41. n++;
  42.  
  43. for (i = 0; i < n - 1; i++) {
  44. // сравниваем два соседних элемента.
  45. for (j = 0; j < n - i - 1; j++) {
  46. if (strcmp(keys[j], keys[j+1]) > 0) {
  47. // если они идут в неправильном порядке, то
  48. // меняем их местами.
  49. char* tmp_key = keys[j];
  50. int tmp_val = values[j];
  51. keys[j] = keys[j + 1];
  52. values[j] = values[j + 1];
  53. keys[j + 1] = tmp_key;
  54. values[j + 1] = tmp_val;
  55. }
  56. }
  57. }
  58. }
  59.  
  60. int main()
  61. {
  62. char** keys = (char**) malloc(MAX * sizeof(char*));
  63. int* values = (int*) malloc(MAX * sizeof(int));
  64. // Заполняем массив нулями
  65. int i;
  66. for (i = 0; i < MAX; i++)
  67. {
  68. keys[i] = NULL;
  69. values[i] = 0;
  70. }
  71.  
  72. char* word = (char*)malloc(MAX * sizeof(char));
  73. int count = 0, value = 0;
  74.  
  75. while (1)
  76. {
  77. scanf("%s", word);
  78. if (strcmp(word, "Total") == 0)
  79. break;
  80.  
  81. scanf("%d", &value);
  82.  
  83. int ind = find_index(keys, word);
  84. keys[ind] = str_tolower(word);
  85. values[ind] += value;
  86. count++;
  87. }
  88.  
  89. sort(keys, values);
  90. count = 0;
  91. while (keys[count] != NULL)
  92. {
  93. printf("%s %d\n", keys[count], values[count]);
  94. count++;
  95. }
  96.  
  97. free(word);
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement