]> zdv2.bktei.com Git - BK-2023-05.git/blob - src/kr_exercises/ch1/s1.6/e1-13..histogram_word_length.c
86184150eb45829f8c9be79f2b05df7ea6d92fc6
[BK-2023-05.git] / src / kr_exercises / ch1 / s1.6 / e1-13..histogram_word_length.c
1 #include <stdio.h>
2
3 /* Exercise 1-13. Write a program to print a histogram of the length
4 of words in its input. It is easy to draw the histogram with the
5 bars horizontal; a vertical orientation is more challenging. */
6
7 #define MAX_LEN 4 /* Max acceptable word length */
8 #define MAX_DISP_LEN 70 /* Max length of horizontal bar */
9 #define IN 1 /* Inside a word */
10 #define OUT 0 /* Outside a word */
11
12 int main() {
13 int n, c, i, j, state, nwchar;
14 int wlen[ MAX_LEN + 1 ];
15
16 state = OUT;
17 nwchar = n = 0;
18 for (int i = 0; i <= MAX_LEN; ++i)
19 wlen[i] = 0;
20
21 /* Populate wlen[] */
22 while ( (c = getchar()) != EOF ) {
23 n++; /* Track loop number. */
24 /* Check if whitespace */
25 if ( c == ' ' || c == '\n' || c == '\t' ) {
26 /* printf("%d:DEBUG:In whitespace.\n", n); */
27 /* I'm in whitespace */
28 /* Check if I just departed a word */
29 if ( state == IN ) {
30 /* Increment appropriate element of wlen[] */
31 if ( nwchar <= MAX_LEN )
32 ++wlen[nwchar];
33 else
34 ++wlen[0]; /* Use zero-index for words longer than MAX_LEN */
35 };
36 /* Remember I'm not in a word */
37 state = OUT;
38 nwchar = 0;
39 } else {
40 /* printf("%d:DEBUG:In word.\n", n); */
41 /* I'm in a word. */
42 /* Check if I just departed whitespace*/
43 if ( state == OUT ) {
44 /* I just started a word. */
45 nwchar = 1;
46 } else {
47 /* I'm in a word. */
48 ++nwchar;
49 }
50
51 /* Remember I'm in a word. */
52 state = IN;
53 }
54
55 /* End of while loop stats */
56 /* printf("%d:DEBUG:nwchar:%d\n", n, nwchar); */
57 }
58
59
60 /* /\* DEBUG:display wlen[] *\/ */
61 /* printf("wlen[]:"); */
62 /* for (i = 0; i < MAX_LEN; ++i) */
63 /* printf(" %d", wlen[i]); */
64 /* printf("\n"); */
65
66 /* int tn = 0; */
67 /* ++tn; */
68 /* printf("wlen[%d]:%d\n", tn, wlen[tn]); */
69
70
71 /* Display wlen[] contents */
72 /* Iterate through elements of wlen[] (skipping zeroth element) */
73 for (i = 1; i <= MAX_LEN; ++i) {
74 /* Print bar for i'th entry in wlen[] */
75 printf("%d: ", i);
76 for (j = 0; j < wlen[i]; ++j ) {
77 if ( j < MAX_DISP_LEN )
78 printf("#");
79 }
80
81 printf("\n");
82 };
83
84 /* Print bar for 0'th entry in wlen[] (words exceeding MAX_LEN) */
85 printf("%d+: ", MAX_LEN + 1 );
86 for (j = 0; j < wlen[0]; ++j )
87 if ( j < MAX_DISP_LEN )
88 printf("#");
89 printf("\n");
90
91 return 0;
92 };
93
94 /* Author: Steven Baltakatei Sandoval
95 License: GPLv3+ */