Skip to content

Instantly share code, notes, and snippets.

@andylshort
Created March 24, 2018 10:58
Show Gist options
  • Save andylshort/9f5c12f04786805e8388f21067f0d3e0 to your computer and use it in GitHub Desktop.
Save andylshort/9f5c12f04786805e8388f21067f0d3e0 to your computer and use it in GitHub Desktop.
Basic Finite State Machine Implementation
using System;
using System.Linq;
public class FSM<T> where T : struct, IConvertible, IComparable
{
public Transition<T, T>[] Transitions { get; private set; }
public T CurrentState { get; private set; }
private FSM() { }
public static FSM<T> Construct(Transition<T, T>[] transitions, T EntryState)
{
return new FSM<T>()
{
Transitions = transitions,
CurrentState = EntryState
};
}
public void TransitionToState(T state)
{
if (Transitions.Contains(new Transition<T, T>(CurrentState, state)))
{
CurrentState = state;
}
}
public class Transition<T, T1>
where T : struct, IConvertible, IComparable
where T1 : struct, IConvertible, IComparable
{
public T FromState { get; private set; }
public T1 ToState { get; private set; }
public Transition(T fromState, T1 toState)
{
FromState = fromState;
ToState = toState;
}
public override bool Equals(object obj)
{
Transition<T, T1> otherTransition = obj as Transition<T, T1>;
if (obj == null) return false;
return FromState.Equals(otherTransition.FromState) && ToState.Equals(otherTransition.ToState);
}
public override int GetHashCode()
{
int hashCode = 17;
hashCode = 31 * hashCode + FromState.GetHashCode();
hashCode = 31 * hashCode + ToState.GetHashCode();
return hashCode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment