kandr

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 44f176cdff8e1f076218542db9c9abb19e2b8097
parent 58908e6c604814e325d749228ad834e9fdc20a7f
Author: aabacchus <ben@bvnf.space>
Date:   Wed, 19 May 2021 02:50:58 +0100

1-14: character freq histogram

Diffstat:
M1.6.c | 51+++++++++++++++++++++------------------------------
1 file changed, 21 insertions(+), 30 deletions(-)

diff --git a/1.6.c b/1.6.c @@ -1,12 +1,9 @@ #include <stdio.h> -#define OUTWORD 0 -#define INWORD 1 -#define MAXWORDLEN 30 +#define NASCII ('~' - '!') -int longest(const int *list) { +int longest(const int *list, const int length) { int max = 0; - int length = sizeof list / sizeof *list; for (int i = 0; i < length; i++){ if (list[i] > max) max = list[i]; } @@ -14,47 +11,41 @@ int longest(const int *list) { } void usage() { - printf("print a histogram of the lengths of words in stdin (K&R ex 1-13)\n"); - printf(" vertical axis is frequency\n"); - printf(" horizontal axis is word length\n"); + fprintf(stderr, "print a histogram of the frequencies of \ +ascii characters in stdin (K&R ex 1-14)\n"); + fprintf(stderr, " vertical axis is frequency\n"); + fprintf(stderr, " horizontal axis is character\n"); } int main (int argc, char *argv[]) { if (argc > 1) { usage(); return 0;} - int c, i, j, wordlen; - int ndigit[MAXWORDLEN] = {0}; - wordlen = 0; - char state = OUTWORD; + int c, i, j; + int ascii[NASCII] = {0}; while ((c = getchar()) != EOF) { - if (c == ' ' || c == '\n' || c == '\t') { - if (state == INWORD) ++ndigit[wordlen]; - wordlen = 0; - state = OUTWORD; - } - else { - state = INWORD; - ++wordlen; + if (c >= '!' && c <= '~') { + ++ascii[c - '!']; } } - int max = longest(&ndigit); + int max = longest(ascii, NASCII); // i counts down from the top to the bottom // (actually from a couple above the top, for padding) // we start printing each bar as i gets to be within the bar's value for (i = max + 2; i > 0; i--) { // side axis - printf("%2d |", i); - for (int j = 0; j < MAXWORDLEN; ++j) - printf(" %s ", i <= ndigit[j] ? "=" : " "); + printf("%3d |", i); + for (int j = 0; j < NASCII; ++j) + printf("%s", i <= ascii[j] ? "*" : " "); printf("\n"); } // bottom axis - printf(" +"); - for (j = 0; j < MAXWORDLEN; ++j) - printf("-|-"); - printf("\n |"); - for (j = 0; j < MAXWORDLEN; ++j) - printf("%3d", j); + printf(" +"); + for (j = '!'; j <= '~'; ++j) + printf("-"); + // bottom labels + printf("\n |"); + for (j = '!'; j <= '~'; ++j) + printf("%c", j); printf("\n"); return 0; }