欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[算法] 有限状态机 FSM 使用 C++ 实现一组简单的状态机模型 - 原理详解: https://fangliang.blog.csdn.net/article/details/44120809

最编程 2024-07-12 07:51:00
...
// fsm_with_executable_code.h
#ifndef FSM_WITH_EXECUTABLE_CODE_H
#define FSM_WITH_EXECUTABLE_CODE_H

#include <string.h>

class State
{
public:
virtual State* Transition(char c) = 0;
};

class Fsm
{
public:
Fsm();
void Reset(); // move to start state
void Advance(char c); // advance one transition
int EndState();
int DoomState();

private:
State* p_current; // &s1, &s2, ..., &s6; NULL ==> doom
};


class State1 : public State
{
public:
State* Transition(char c);
};

class State2 : public State
{
public:
State* Transition(char c);
};

class State3 : public State
{
public:
State* Transition(char c);
};

class State4 : public State
{
public:
State* Transition(char c);
};

class State5 : public State
{
public:
State* Transition(char c);
};

class State6 : public State
{
public:
State* Transition(char c);
};

#endif // FSM_WITH_EXECUTABLE_CODE_H

// fsm_with_executable_code.cc
#include "fsm_with_executable_code.h"

State1 s1;
State2 s2;
State3 s3;
State4 s4;
State5 s5;
State6 s6;

Fsm::Fsm()
{
p_current = NULL;
}

void Fsm::Reset()
{
p_current = &s1;
}

void Fsm::Advance(char c)
{
if (p_current != NULL)
p_current = p_current->Transition(c);
}

int Fsm::EndState()
{
return p_current == &s6;
}

int Fsm::DoomState()
{
return p_current == NULL;
}
State* State1::Transition(char c)
{
switch(c)
{
case 'A':
return &s2;
case 'B':
return &s3;
case 'C':
return &s4;
case 'D':
return &s5;
case '\0':
return NULL;
default:
return NULL;
}
}

State* State2::Transition(char c)
{
switch(c)
{
case 'E':
return &s2;
case 'I':
return &s6;
case '\0':
return NULL;
default:
return NULL;
}
}

State* State3::Transition(char c)
{
switch(c)
{
case 'F':
return &s3;
case 'M':
return &s4;
case 'J':
return &s6;
case '\0':
return NULL;
default:
return NULL;
}
}

State* State4::Transition(char c)
{
switch(c)
{
case 'G':
return &s4;
case 'K':
return &s6;
case '\0':
return NULL;
default:
return NULL;
}
}

State* State5::Transition(char c)
{
switch(c)
{
case 'O':
return &s2;
case 'H':
return &s5;
case 'L':
return &s6;
case 'N':
return &s4;
case '\0':
return NULL;
default:
return NULL;
}
}

State* State6::Transition(char c)
{
return NULL;
}

// test_with_executable_code.cc
#include "fsm_with_executable_code.h"

#include "stdio.h" // printf, scanf
#include "stdlib.h" // system

void test_fsm()
{
char input_string[80];
printf("Enter input expression: ");
scanf("%s", input_string);

Fsm fsm;
fsm.Reset();
int index = 0;
fsm.Advance(input_string[index++]);

while (!fsm.EndState() && !fsm.DoomState())
fsm.Advance(input_string[index++]);

if (fsm.EndState())
printf("\nValid input expression");
else
printf("\nInvalid input expression");
}

int main()
{
test_fsm();

system("pause");
}