Skip to content

Instantly share code, notes, and snippets.

@foobra
Last active May 22, 2017 01:43
Show Gist options
  • Save foobra/fe6181a420d61431ba3068e44d3c0084 to your computer and use it in GitHub Desktop.
Save foobra/fe6181a420d61431ba3068e44d3c0084 to your computer and use it in GitHub Desktop.
First word-count FSM Implement
#include <stdio.h>
#include <map>
#include <utility>
#include <functional>
enum STATE {
IN,
OUT,
};
std::map<STATE, std::function<STATE(char, int *)>> fsm = {
{
OUT, [](char c, int *count){
if (c == ' ' || c == '\t')
return OUT;
else {
*count = *count + 1;
return IN;
}
}},
{
IN, [](char c, int *count){
if (c != ' ' && c != '\t') {
return IN;
} else {
return OUT;
}
}
}
};
std::map<std::pair<STATE, STATE>, std::function<STATE(int *)>> fsm2 = {
{
{OUT, OUT}, [](int *count){
return OUT;
}
},
{
{OUT, IN}, [](int *count){
*count = *count + 1;
return IN;
}
},
{
{IN, OUT}, [](int *count){
return OUT;
}
},
{
{IN, IN}, [](int *count){
return IN;
}
},
};
std::map<STATE, std::function<void(void)>> fsm2_enter = {
{
OUT, [](){
printf("enter OUT\n");
}
},
{
IN, [](){
printf("enter IN\n");
}
},
};
std::map<STATE, std::function<void(void)>> fsm2_exit = {
{
OUT, [](){
printf("exit OUT\n");
}
},
{
IN, [](){
printf("exit IN\n");
}
},
};
std::map<std::pair<STATE, STATE>, std::function<void(int *)>> fsm2_2 = {
{
{OUT, IN}, [](int *count){
fsm2_exit[OUT]();
*count = *count + 1;
fsm2_enter[IN]();
}
},
{
{OUT, OUT}, [](int *count){
fsm2_exit[OUT]();
fsm2_enter[OUT]();
}
},
{
{IN, IN}, [](int *count){
fsm2_exit[IN]();
fsm2_enter[IN]();
}
},
{
{IN, OUT}, [](int *count){
fsm2_exit[IN]();
fsm2_enter[OUT]();
}
},
};
std::map<STATE, std::function<std::pair<STATE,STATE>(char)>> fsm2_judge = {
{
OUT, [](char c){
return (c == ' ' || c == '\t') ? std::make_pair(OUT, OUT) : std::make_pair(OUT, IN);
}
},
{
IN, [](char c){
return (c != ' ' && c != '\t') ? std::make_pair(IN, IN) : std::make_pair(IN, OUT);
}
},
};
int main()
{
char c;
int count = 0; // word count
STATE state = OUT;
while ( scanf("%c", &c) != EOF && c != '\n' ) {
// 1. first implement
// state = fsm[state](c, &count);
// 2. second implement
/*
switch (state) {
case OUT:
{
if (c == ' ' || c == '\t')
{
state = fsm2[{OUT,OUT}](&count);
}
else
{
state = fsm2[{OUT,IN}](&count);
}
}
break;
case IN:
if (c != ' ' && c != '\t') {
state = fsm2[{IN,IN}](&count);
}
else {
state = fsm2[{IN,OUT}](&count);
}
break;
}
*/
// 3. third implement based on 2
//state = fsm2[fsm2_judge[state](c)](&count);
// 4. 4th implement based on 3
auto state_transfrom = fsm2_judge[state](c);
if (fsm2_2.find(state_transfrom) != fsm2_2.end()) {
fsm2_2[state_transfrom](&count);
}
state = state_transfrom.second;
}
printf("word count: %d\n",count);
return 0;
}
@foobra
Copy link
Author

foobra commented May 21, 2017

TODO: rewrite it in OOP way

@foobra
Copy link
Author

foobra commented May 22, 2017

image5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment