From a4eda78b73cea22f36435f62ed52d071395bfc4f Mon Sep 17 00:00:00 2001 From: "martin@ashbysoft.com" Date: Sun, 12 Jun 2022 21:38:17 +0000 Subject: added tests for ex1-13.c --- ex1-13.c | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 96 insertions(+), 21 deletions(-) (limited to 'ex1-13.c') diff --git a/ex1-13.c b/ex1-13.c index 87fe0b0..ff2d53d 100644 --- a/ex1-13.c +++ b/ex1-13.c @@ -1,8 +1,10 @@ #include #include #include +#include #define max_word 100 +#define max(a, b) ((a) > (b) ? (a) : (b)) typedef enum _state {in,out} state; bool is_word(char c) { @@ -10,43 +12,51 @@ bool is_word(char c) { && c != '\t' && c != '\n'; } + /* print a histogram of word lengths read from input print histo to output print errors warnings to output_err */ int whisto(FILE* input, FILE* output, FILE* output_err) { - uint32_t lens[max_word]={0}; - int c = fgetc(input); - if (c == EOF) { - fprintf(output_err, "warning: no input!\n"); - goto spout; - } - state s = is_word(c) ? in : out; - uint32_t cl = s == in ? 1 : 0; - while ((c = fgetc(stdin))!= EOF){ + uint32_t lens[max_word+1]={0}; + state s = out; + uint32_t cl = 0; + while(true) { + int c = fgetc(input); if (is_word(c)){ - if (s == in) { - cl++; - } else { + if (s == out) { s = in; cl=1; + } else { + cl++; } } else { if (s == in) { s = out; + if (cl > max_word) { + printf("cl=%d\n", cl); + fprintf(output_err, "word too long\n"); + fflush(output_err); + return 1; + } lens[cl]++; } else { // do nothing I guess - } + } + } + + if (c == EOF) { + break; } } - // need to count final word - if (s == in) { - lens[cl]++; - } -spout: + // Do 2 passes to find the longest word length with some data in it + uint16_t mx = 0; + for(uint16_t i=1; + i<=max_word; + i ++) + mx = max(mx, lens[i]>0 ? i : 0); for(uint16_t i=1; - ibuffer); + return 0; +} + +#endif \ No newline at end of file -- cgit v1.2.3-ZIG