K&Rを読もう(7) 演習 1-14 またまたヒストグラム表示

さて、問題を解こう。またまたヒストグラム

演習 1-14

今度は文字の頻度。

#include <stdio.h>
#include <stdlib.h>

void hist_iter(int count[], int start, int end) {
    int i, j;
    for(i = start; i <= end; i++) {
        printf("%c(%2x) : %2d ", i , i, count[i]);
        for (j = 0; j < count[i]; j++)
            putchar('*');
        puts("");
    }
}

#define TABLE_SIZE 0x100

int main(void)
{
    int c, i;
    int count[TABLE_SIZE];

    for (i = 0; i < TABLE_SIZE; i++)
        count[i] = 0;
    while ((c = getchar()) != EOF)
        ++count[c];

    hist_iter(count, '0', '9');
    hist_iter(count, 'A', 'Z');
    hist_iter(count, 'a', 'z');

    exit(EXIT_SUCCESS);
}

パターンを見抜くことが出来ました。

以前の僕ならもっと長くなっていたはず。SICP読んでて良かったと思う瞬間。

さて、実行結果。

% ./ex-1-14 < ex-1-14.c
0(30) :  7 *******
1(31) :  1 *
2(32) :  2 **

...(略

x(78) :  3 ***
y(79) :  0
z(7a) :  1 *

文字コードも付けてみた。文字コード表を作っておくと便利かも知れない。

まとめ

って言われたら僕死んじゃいそう〜。そんな問題が無くてホッっとした。