Skip to content

Instantly share code, notes, and snippets.

@foobra
Last active May 22, 2017 05:50
Show Gist options
  • Save foobra/49c152f01053970c86695084733262b2 to your computer and use it in GitHub Desktop.
Save foobra/49c152f01053970c86695084733262b2 to your computer and use it in GitHub Desktop.
word-count FSM in simple way
#include <stdio.h>
#include <map>
#include <utility>
enum STATE
{
IN,
OUT,
};
enum EVENT
{
WhiteSpace,
Char,
};
enum TRANSITION
{
OUT_IN,
Nope,
};
//[WhiteSpace][IN] = OUT;
//[WhiteSpace][OUT] = OUT;
//[Char][IN] = IN;
//[Char][OUT] = IN;
STATE StateEvents[2][2] = {
OUT,
OUT,
IN,
IN,
};
std::map<std::pair<STATE, STATE>, TRANSITION> StateTrans = {
{{OUT, OUT}, Nope},
{{OUT, IN}, OUT_IN},
{{IN, OUT}, Nope},
{{IN, IN}, Nope},
};
int main()
{
char c;
int count = 0; // word count
STATE state = OUT;
while (scanf("%c", &c) != EOF && c != '\n') {
EVENT event;
// event judge
if (c == ' ' || c == '\t') {
event = WhiteSpace;
} else {
event = Char;
}
STATE newState = StateEvents[event][state];
auto trans = StateTrans[{state, newState}];
// tranition execute
if (trans == OUT_IN) {
count++;
}
state = newState;
}
printf("word count: %d\n", count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment