Fixed greediness of kleene star

master
Aadhavan Srinivasan 2 months ago
parent d1205c781c
commit cd2b800b04

@ -29,8 +29,11 @@ func findAllMatches(start *State, str string) (indices []matchIndex) {
return findAllMatchesHelper(start, str, make([]matchIndex, 0), 0) return findAllMatchesHelper(start, str, make([]matchIndex, 0), 0)
} }
func findAllMatchesHelper(start *State, str string, indices []matchIndex, offset int) []matchIndex { func findAllMatchesHelper(start *State, str string, indices []matchIndex, offset int) []matchIndex {
// 'Base case' - exit if string is empty // 'Base case' - exit if string is empty. If the starting state is a last-state, then append the final set of indices (trailing whitespace)
if len(str) == 0 { if len(str) == 0 {
if start.isLast {
indices = append(indices, matchIndex{offset, offset + 1})
}
return indices return indices
} }
@ -74,16 +77,17 @@ func findAllMatchesHelper(start *State, str string, indices []matchIndex, offset
if len(state.transitions[int(str[i])]) > 0 { if len(state.transitions[int(str[i])]) > 0 {
tempStates = append(tempStates, state.transitions[int(str[i])]...) tempStates = append(tempStates, state.transitions[int(str[i])]...)
foundPath = true foundPath = true
} else { }
// This enables the 'greedy' behavior - last-state status is only checked if we can't match anything else }
if foundPath == false {
// This enables the 'greedy' behavior - last-state status is only checked if we didn't find a path forward
for _, state := range currentStates {
if state.isLast { if state.isLast {
endIdx = i endIdx = i
indices = append(indices, matchIndex{startIdx + offset, endIdx + offset}) indices = append(indices, matchIndex{startIdx + offset, endIdx + offset})
} }
} }
}
if foundPath == false {
// Recursion - match with rest of string if we have nowhere to go. If we haven't moved in the string, increment the counter by 1 to ensure we don't keep trying the same string over and over // Recursion - match with rest of string if we have nowhere to go. If we haven't moved in the string, increment the counter by 1 to ensure we don't keep trying the same string over and over
if i == startingFrom { if i == startingFrom {
i++ i++

Loading…
Cancel
Save