Last active
May 22, 2017 05:50
-
-
Save foobra/49c152f01053970c86695084733262b2 to your computer and use it in GitHub Desktop.
word-count FSM in simple way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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