9p / who / tweedy / 9C / 1


Exercise 1.14: Histogram of Character Frequencies

Code

#include <u.h>
#include <libc.h>
#include <bio.h>

#define STDIN       0
#define MIN     32  /* lowest ASCII value of character range to be counted [32: ' '] */
#define MAX     126 /* highest value [126: '~'] */
#define PRINTEMPTY  0   /* whether to print characters with no instances */

/* histogram of character frequencies */

void
main()
{
    Biobuf *bstdin;
    bstdin = Bfdopen(STDIN, OREAD);
    char c, i, j;
    int hist[MAX];  /* a slight waste of array values < MIN, but much more readable */

    c = j = 0;
    for(i = 0; i <= MAX; ++i)
        hist[i] = 0;

    while((c = Bgetc(bstdin)) >= 0){
        if(c >=MIN && c <= MAX)
            ++hist[c];
    }

    for(i = MIN; i <= MAX; ++i){
        if(PRINTEMPTY == 0){
            if(hist[i] > 0){
                print("'%c'\t| ", i);
                for(j = 1; j <= hist[i]; ++j)
                    print("*");
                print("\n");
            }
        }
        else{
            print("'%c'\t| ", i);
            for(j = 1; j <= hist[i]; ++j)
                print("*");
            print("\n");
        }
    }

    exits(0);
}

Output

$ 9c chist.c; 9l chist.o -o chist
chist.c:22:7: warning: array subscript is of type 'char' [-Wchar-subscripts]
chist.c:26:10: warning: array subscript is of type 'char' [-Wchar-subscripts]
chist.c:30:10: warning: array subscript is of type 'char' [-Wchar-subscripts]
chist.c:32:24: warning: array subscript is of type 'char' [-Wchar-subscripts]
$ ./chist < chist.c
' ' | *******************************************************************************************
'"' | ******
'#' | *******
'%' | *
'&' | **
''' | ******
'(' | **************
')' | **************
'*' | ************
'+' | ********
',' | *****
'.' | ***
'/' | **********
'0' | ********
'1' | ***
'2' | ****
'3' | **
'6' | **
':' | **
';' | *****************
'<' | ********
'=' | **************
'>' | ******
'A' | *******
'B' | ***
'C' | *
'D' | ***
'E' | **
'I' | ********
'M' | **********
'N' | ******
'O' | *
'P' | *
'R' | *
'S' | ***
'T' | ***
'X' | *****
'Y' | *
'[' | *******
'\' | **
']' | *******
'a' | ********************
'b' | *********
'c' | **********************
'd' | **************
'e' | *********************************
'f' | **************
'g' | *****
'h' | *********************
'i' | **********************************************
'j' | *****
'l' | ***********
'm' | ****
'n' | ************************
'o' | *****************
'p' | ******
'r' | **********************
's' | *******************
't' | ********************************
'u' | ***********
'v' | ****
'w' | *****
'x' | *
'y' | *
'{' | ****
'|' | *
'}' | ****
'~' | *



tweedy