Skip to content

Instantly share code, notes, and snippets.

View rcshubhadeep's full-sized avatar
💭
Creating the future

Shubhadeep Roychowdhury rcshubhadeep

💭
Creating the future
  • Goa
View GitHub Profile
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 18:12
full code
package main
import (
"errors"
"fmt"
"strconv"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/multi"
)
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 18:01
Main function
func main() {
stateMachine := New()
initState := stateMachine.Init("locked")
unlockedSate := stateMachine.NewState("unlocked")
coinRule := NewRule(Operator("eq"), Event("coin"))
pushRule := NewRule(Operator("eq"), Event("push"))
stateMachine.LinkStates(initState, unlockedSate, coinRule)
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:39
Compute the State Machine
func (s *StateMachine) Compute(events []string, printState bool) State {
for _, e := range events {
s.FireEvent(Event(e))
if printState {
fmt.Printf("%s\n", s.PresentState.String())
}
}
return s.PresentState
}
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:16
Fire Event function
func (s *StateMachine) FireEvent(e Event) error {
presentNode := s.PresentState
it := s.g.From(presentNode.Id)
for it.Next() {
n := s.g.Node(it.Node().ID()).(State)
line := graph.LinesOf(s.g.Lines(presentNode.Id, n.Id))[0].(Link) // There can be one defined path between two distinct states
for key, val := range line.Rules {
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:13
Create New Rule
func NewRule(triggerConditionOperator Operator, comparisonValue Event) map[Operator]Event {
return map[Operator]Event{triggerConditionOperator: comparisonValue}
}
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:09
Init, Add State, Link State
func (s *StateMachine) Init(initStateValue interface{}) State {
s.PresentState = State{Id: int64(NodeIDCntr), Value: initStateValue}
s.g.AddNode(s.PresentState)
NodeIDCntr++
return s.PresentState
}
func (s *StateMachine) NewState(stateValue interface{}) State {
state := State{Id: int64(NodeIDCntr), Value: stateValue}
s.g.AddNode(state)
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:03
New StateMachine
func New() *StateMachine {
s := &StateMachine{}
s.g = multi.NewDirectedGraph()
return s
}
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 17:00
StateMachine definiton
type Event string
type Operator string
var NodeIDCntr = 0
var LineIdCntr = 1
type StateMachine struct {
PresentState State
g *multi.DirectedGraph
}
@rcshubhadeep
rcshubhadeep / main.go
Last active July 21, 2021 17:45
FSM Go Graph Definition
type State struct {
Id int64
Value interface{}
}
type Link struct {
Id int64
T, F graph.Node
Rules map[Operator]Event
}
@rcshubhadeep
rcshubhadeep / main.go
Created July 21, 2021 15:01
FSM Go Imports
package main
import (
"errors"
"fmt"
"strconv"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/multi"
)