Is it showing age or mental fatigue or ...?
In my graduate school days, one of my favorite professor told me that I've to fiddle around with formulas, patterns, and little concept to nurture the brain. So I tried to that and I still tries to do it... And I saw both a success and failures. It is basically the interplay of intuition and rigor. Both tries to beat each other. And if rigor can win I'm all the more happy.
So I thought I will use rigor, and set out to draw a simple state machine to search for a line in a buffer of character. So until the end of the buffer, I've to search, find '\r' and '\n' in two succeeding position, and return the length of a line if found otherwise length is zero. It is very elementary form of boyer moore string algorithm. Note that I could have taken a getline() function from standard library, and change it point to buffer instead of stdin. Well, the success was there, but after few failures. My mistake was to capture all the three states: start, CR, LF. And when I reach LF state, I return the length. Now I feed a line consist of only CR, and LF. I get to LF state, but I don't have any more char in the buf, so I happily declare that I don't have a complete line. Actually what should have been done is that as soon as I reach to LF from the CR state, capture and return... So the moral of this error is that "Reduction of states" that I learned a long time back and forgot.
I did not try to do the simple way of writing a while loop and parse thru because I wanted to keep the scanning separate and if necessary I could introduce more states to change the state machine for other recognition, so basically my thinking was for patterns in general.
I think once in a while we should try to solve the exercises of the classic book on C and C++.
Reader Comments