Created
October 26, 2024 16:50
-
-
Save adammyhre/9cc8154d2c79c3b9154dc1c70d4d56cd to your computer and use it in GitHub Desktop.
Stack-Based Finite State Machine (Push Down Automata)
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
using System.Collections.Generic; | |
namespace Automata { | |
public abstract class State { | |
protected readonly PushDownAutomata pda; | |
protected State(PushDownAutomata pda) { | |
this.pda = pda; | |
} | |
public abstract void Enter(); | |
public abstract void Update(); | |
public abstract void Exit(); | |
} | |
public struct Context {} | |
public class PushDownAutomata { | |
readonly Stack<State> stateStack = new(); | |
public State CurrentState => stateStack.Count > 0 ? stateStack.Peek() : null; | |
public Context context; | |
public PushDownAutomata(Context context) { | |
this.context = context; | |
} | |
public void PushState(State newState) { | |
stateStack.Push(newState); | |
newState.Enter(); | |
} | |
public void PopState() { | |
if (stateStack.Count == 0) return; | |
CurrentState.Exit(); | |
stateStack.Pop(); | |
} | |
public void Update() => CurrentState?.Update(); | |
public void SetContext(Context context) => this.context = context; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment