You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.6 KiB
Go

2 months ago
package main
const EPSILON int = 0
type State struct {
content int // Contents of current state
isEmpty bool // If it is empty - Union operator and Kleene star states will be empty
isLast bool // If it is the last state (acept state)
output []*State // The outputs of the current state ie. the 'outward arrows'. A union operator state will have more than one of these.
transitions map[int][]*State // Transitions to different states (maps a character (int representation) to a _list of states. This is useful if one character can lead multiple states eg. ab|aa)
isKleene bool // Identifies whether current node is a 0-state representing Kleene star
2 months ago
}
type NFA struct {
start State
outputs []State
}
// verifyLastStatesHelper performs the depth-first recursion needed for verifyLastStates
func verifyLastStatesHelper(state *State, visited map[*State]bool) {
if len(state.transitions) == 0 {
state.isLast = true
return
}
if len(state.transitions) == 1 && len(state.transitions[state.content]) == 1 && state.transitions[state.content][0] == state { // Eg. a*
state.isLast = true
return
}
if len(state.transitions) == 1 && state.isKleene { // A State representing a Kleene Star has a transition going out, which loops back to it. If that is the only transition (and it contains only one state), then it must be a last-state
for _, v := range state.transitions { // Should only loop once
if len(v) == 1 {
state.isLast = true
return
}
}
}
2 months ago
if visited[state] == true {
return
}
visited[state] = true
for _, states := range state.transitions {
for i := range states {
if states[i] != state {
verifyLastStatesHelper(states[i], visited)
}
2 months ago
}
}
}
// verifyLastStates enables the 'isLast' flag for the leaf nodes (last states)
func verifyLastStates(start []*State) {
verifyLastStatesHelper(start[0], make(map[*State]bool))
2 months ago
}
func concatenate(s1 *State, s2 *State) *State {
for i := range s1.output {
s1.output[i].transitions[s2.content] = append(s1.output[i].transitions[s2.content], s2)
}
s1.output = s2.output
return s1
}
func kleene(s1 State) *State {
toReturn := &State{}
toReturn.transitions = make(map[int][]*State)
toReturn.content = EPSILON
toReturn.isEmpty = true
toReturn.isKleene = true
toReturn.output = append(toReturn.output, toReturn)
for i := range s1.output {
s1.output[i].transitions[toReturn.content] = append(s1.output[i].transitions[toReturn.content], toReturn)
}
toReturn.transitions[s1.content] = append(toReturn.transitions[s1.content], &s1)
return toReturn
}