Created
October 17, 2014 08:50
-
-
Save koturn/9fd20583bac464beb242 to your computer and use it in GitHub Desktop.
後輩の課題
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <ctype.h> | |
| #include <stdio.h> | |
| #define BUF_SIZE 1024 | |
| #define N_ALPHA 26 | |
| #define LALPHA_TO_NR(c) (c - 'a') | |
| #define NR_TO_LALPHA(n) (n + 'a') | |
| #define LENGTH(array) (sizeof(array) / sizeof((array)[0])) | |
| #define SWAP(type, a, b) \ | |
| do { \ | |
| type __tmp_swap_var__ = *(a); \ | |
| *(a) = *(b); \ | |
| *(b) = __tmp_swap_var__; \ | |
| } while (0) | |
| typedef struct { | |
| char ch; | |
| int cnt; | |
| } Pair; | |
| void init_pairs(Pair *restrict pairs, int n); | |
| void bsort(Pair *restrict pairs, int n); | |
| void show(const Pair *restrict pairs, int n); | |
| int main(void) { | |
| static char str[BUF_SIZE]; | |
| static Pair pairs[N_ALPHA]; | |
| fgets(str, sizeof(str), stdin); | |
| init_pairs(pairs, LENGTH(pairs)); | |
| for (const char *restrict ptr = str; *ptr != '\0'; ptr++) { | |
| if (isalpha(*ptr)) { | |
| pairs[LALPHA_TO_NR(tolower(*ptr))].cnt++; | |
| } | |
| } | |
| bsort(pairs, LENGTH(pairs)); | |
| show(pairs, LENGTH(pairs)); | |
| return 0; | |
| } | |
| void init_pairs(Pair *restrict pairs, int n) { | |
| for (int i = 0; i < n; i++) { | |
| pairs[i].ch = NR_TO_LALPHA(i); | |
| } | |
| } | |
| void bsort(Pair *restrict pairs, int n) { | |
| for (int i = 0; i < n - 1; i++) { | |
| for (int j = n - 1; j > i; j--) { | |
| if (pairs[j - 1].cnt < pairs[j].cnt) { | |
| SWAP(Pair, &pairs[j - 1], &pairs[j]); | |
| } | |
| } | |
| } | |
| } | |
| void show(const Pair *restrict pairs, int n) { | |
| for (int i = 0; i < N_ALPHA; i++) { | |
| printf("%c(%c): %d\n", pairs[i].ch, toupper(pairs[i].ch), pairs[i].cnt); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment