TCPL——练习1.13
坚持每天写一两道小练习:-)
TCPL练习1.13: 编写一个程序,打印输入中单词长度的水平和垂直直方图。很简单,就是垂直的时候,我用了二维数组,真是浪费空间啊。当然有局限性,只能规定单词长度在什么范围内。TCAB里面通过一条数学运算,没借助二维数组来实现,我没有验证,也没有看懂那运算是怎么得出结果的。
代码
#include <stdio.h>
#include <string.h>
#define MAXLEN 11
#define OUT 0
#define IN 1
static void WordsLenCount(int *histogram)
{
int c;
int wordLen = 0;
int state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (wordLen != 0) {
histogram[wordLen]++;
wordLen = 0;
state = OUT;
}
} else if (state == OUT) {
++wordLen;
state = IN;
} else {
++wordLen;
}
}
}
static void DrawHorizontalHistogram(int *histogram)
{
int i, j;
printf("===== DRAWING THE HOIZONTAL HISTOGRAM ====\n");
for (i = 1; i < MAXLEN; ++i) {
printf("%3d ", i);
for (j = 0; j < histogram[i]; ++j) {
printf("*");
}
printf("\n");
}
}
static void DrawVerticalHistogram(int *histogram)
{
int i, j;
int verHistogram[MAXLEN][MAXLEN];
memset(verHistogram, ' ', sizeof(verHistogram));
printf("===== DRAWING THE VERTICAL HISTOGRAM ====\n");
for (i = 1; i < MAXLEN; ++i) {
for (j = histogram[i]; j >= 1; --j) {
verHistogram[j][i] = '*';
}
}
for (i = MAXLEN - 1; i >= 1; --i) {
for (j = 1; j < MAXLEN; ++j) {
printf("%c ", verHistogram[i][j]);
}
printf("\n");
}
for (i = 1; i < MAXLEN; ++i) {
printf("%d ", i);
}
printf("\n");
}
int main(void)
{
int histogram[MAXLEN] = {0};
WordsLenCount(histogram);
DrawHorizontalHistogram(histogram);
DrawVerticalHistogram(histogram);
return 0;
}