about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authoraabacchus <ben@bvnf.space>2021-05-19 02:50:58 +0100
committeraabacchus <ben@bvnf.space>2021-05-19 03:02:08 +0100
commit44f176cdff8e1f076218542db9c9abb19e2b8097 (patch)
tree77ae07bd8821b39fa8564b058d21b1a12496b4e9
parent58908e6c604814e325d749228ad834e9fdc20a7f (diff)
downloadkandr-44f176cdff8e1f076218542db9c9abb19e2b8097.tar.gz
1-14: character freq histogram
-rw-r--r--1.6.c51
1 files changed, 21 insertions, 30 deletions
diff --git a/1.6.c b/1.6.c
index 41004ad..bb9e778 100644
--- 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;
 }