/home/toolbox/public_html/solutions/100/10062/a.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <stdint.h>
7 #include <math.h>
8 #include <stdlib.h>
9
10 #define TRUE (1 == 1)
11 #define FALSE (1 != 1)
12
13 #define DEBUG if (FALSE)
14
15
16 /*
17 * Author: Isaac Traxler
18 * Date: 2017-09-27
19 * Purpose: fun
20 * Problem: 10062 - Tell me the frequencies!
21 */
22
23 /*
24 * This template reads lines of data at a time until end of file.
25 */
26
27 #define MAX_LINE 1024
28 #define ASCII_MAX 128
29
30 typedef struct FREQ_STRUCT
31 {
32 /* struct FREQ_STRUCT */
33 int ascii;
34 int count;
35 } /* struct FREQ_STRUCT */
36 FREQ_STRUCT;
37
38 FREQ_STRUCT cnt[ASCII_MAX];
39 char line[MAX_LINE];
40
41 int compare(const void * a, const void * b)
42 {
43 /* FUNCTION compare */
44 int toReturn;
45
46 FREQ_STRUCT *A = (FREQ_STRUCT *)a;
47 FREQ_STRUCT *B = (FREQ_STRUCT *)b;
48 if (A->count == B->count)
49 {
50 toReturn = B->ascii - A->ascii;
51 }
52 else
53 {
54 toReturn = A->count - B->count;
55 }
56 return ( toReturn );
57 } /* FUNCTION compare */
58
59
60
61 void init()
62 {
63 /* FUNCTION init */
64 int i;
65
66 for (i=0; 128>i; i++)
67 {
68 cnt[i].count = 0;
69 cnt[i].ascii = i;
70 }
71 } /* FUNCTION init */
72
73 void dump()
74 {
75 /* FUNCTION dump */
76 int i;
77
78 for (i=28; 128>i; i++)
79 {
80 /* for each counter */
81 if (0 < cnt[i].count)
82 {
83 printf("%d %d\n", cnt[i].ascii, cnt[i].count);
84 }
85 DEBUG printf("%d %d\n", cnt[i].ascii, cnt[i].count);
86 } /* for each counter */
87 } /* FUNCTION dump */
88
89 int getInput()
90 {
91 /* FUNCTION getInput */
92 int dataReadFlag;
93
94 fgets(line, MAX_LINE, stdin);
95 if (feof(stdin))
96 dataReadFlag = FALSE;
97 else
98 {
99 /* something to read */
100 dataReadFlag = TRUE;
101 line[strlen(line)-1] = 0;
102 } /* something to read */
103 return (dataReadFlag);
104 } /* FUNCTION getInput */
105
106 void process()
107 {
108 /* FUNCTION process */
109 int i;
110
111 init(); /* reset counts */
112 DEBUG printf("%s\n", line);
113 /* process seach char -- incrementing counter in array */
114 for (i=0; strlen(line)>i; i++)
115 {
116 /* for each character in the line */
117 cnt[line[i]].count++;
118 } /* for each character in the line */
119 DEBUG dump();
120 /* sort based on frequency and then ascii value */
121 qsort(cnt, ASCII_MAX, sizeof(FREQ_STRUCT), compare);
122 /* process each count and dump out non-zero ones */
123 dump();
124 } /* FUNCTION process */
125
126 int main()
127 {
128 /* main */
129 int moreToDo;
130
131 moreToDo = getInput();
132 while (moreToDo)
133 {
134 /* while */
135 process();
136 moreToDo = getInput();
137 if (moreToDo)
138 {
139 printf("\n");
140 }
141 } /* while */
142
143 return EXIT_SUCCESS;
144 } /* main */
145