Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- //#define NEWLINE 13
- #define NEWLINE 10
- static char** groups; // Array with the groups of letters.
- static int n_groups; // Current amount of groups (used for realloc())
- static int* weights; // Array with the precalculated # of 'a' in each group
- static char* group; // String representing the current group
- static int n_group; // Current amount of letters in the group
- int add_to_group(char c)
- {
- // Allocate memory:
- if (n_group == 0)
- {
- n_group++;
- group = (char*) malloc(sizeof(char) * 1);
- }
- else
- {
- n_group++;
- group = (char*) realloc(group, sizeof(char) * n_group);
- }
- // Store the new symbol:
- group[n_group - 1] = c;
- return 0;
- }
- int store_group(void)
- {
- int a, i;
- // Allocate memory:
- if (n_groups == 0)
- {
- n_groups++;
- weights = (int* ) malloc(sizeof(int ) * 1);
- groups = (char**) malloc(sizeof(char*) * 1);
- }
- else
- {
- n_groups++;
- weights = (int* ) realloc(weights, sizeof(int ) * n_groups);
- groups = (char**) realloc(groups , sizeof(char*) * n_groups);
- }
- // Finish the group with the \0 symbol
- add_to_group(0);
- // Count the 'a' symbols and store the data:
- for (i = 0; ; ++i)
- {
- if (group[i] == 0)
- break;
- if (group[i] == 'a')
- a++;
- }
- groups [n_groups - 1] = group;
- weights[n_groups - 1] = a;
- // Set n_group to 0 to indicate the start of the new group
- n_group = 0;
- return 0;
- }
- int sort_groups(void)
- {
- int flag;
- int i;
- int int_temp;
- char* char_p_temp;
- flag = 0;
- for (; flag != 1;)
- {
- flag = 1;
- for (i = 1; i < n_groups; ++i)
- if (weights [i - 1] < weights [i])
- {
- int_temp = weights [i - 1];
- weights [i - 1] = weights [i ];
- weights [i ] = int_temp;
- char_p_temp = groups [i - 1];
- groups [i - 1] = groups [i ];
- groups [i ] = char_p_temp;
- flag = 0;
- }
- }
- return 0;
- }
- int free_groups(void)
- {
- int i;
- for (i = 0; i < n_groups; ++i)
- free(groups[i]);
- free(groups);
- return 0;
- }
- int main(void)
- {
- int true_int, flag;
- char c;
- int i, j;
- flag = 0;
- true_int = 1;
- groups = NULL;
- n_groups = 0;
- weights = NULL;
- group = NULL;
- n_group = 0;
- while (true_int)
- {
- scanf("%c", &c);
- if (c == 0) break;
- if (c == NEWLINE) break;
- if (isalpha(c))
- {
- flag = 1;
- add_to_group(c);
- }
- else
- {
- if (flag)
- {
- flag = 0;
- store_group();
- }
- }
- }
- sort_groups();
- for (i = 0; i < n_groups; ++i)
- {
- for (j = 0; ; ++j)
- {
- if (groups[i][j] == 0)
- break;
- printf("%c", groups[i][j]);
- }
- printf(" ");
- }
- free_groups();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement