Read multiple lines from stdin and apply regex to each one; Convert the array of matchIndex structs into a flat array of indices; speeds up process of checking if we have to print a character in color

master
Aadhavan Srinivasan 1 month ago
parent b55b80ec6c
commit 11641596fa

@ -383,33 +383,39 @@ func main() {
var re string
re = os.Args[1]
var test_str string
// Read test string from stdin
var err error
// Create reader for stdin and writer for stdout
reader := bufio.NewReader(os.Stdin)
test_str, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
panic(err)
}
//fmt.Scanln(&test_str)
out := bufio.NewWriter(os.Stdout)
re_postfix := shuntingYard(re)
startState := thompson(re_postfix)
matchIndices := findAllMatches(startState, test_str)
inColor := false
if len(matchIndices) > 0 {
for i, c := range test_str {
for _, indices := range matchIndices {
if i >= indices.startIdx && i < indices.endIdx {
color.New(color.FgRed).Printf("%c", c)
inColor = true
break
// Read every string from stdin until we encounter an error. If the error isn't EOF, panic.'
for test_str, err = reader.ReadString('\n'); err == nil; test_str, err = reader.ReadString('\n') {
matchIndices := findAllMatches(startState, test_str)
// Decompose the array of matchIndex structs into a flat unique array of ints - if matchIndex is {4,7}, flat array will contain 4,5,6
// This should make checking O(1) instead of O(n)
indicesToPrint := new_uniq_arr[int]()
for _, idx := range matchIndices {
indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
}
if len(matchIndices) > 0 {
for i, c := range test_str {
if indicesToPrint.contains(i) {
color.New(color.FgRed).Fprintf(out, "%c", c)
} else {
fmt.Fprintf(out, "%c", c)
}
}
if inColor == false {
fmt.Printf("%c", c)
}
inColor = false
} else {
fmt.Fprint(out, test_str)
}
err = out.Flush()
if err != nil {
panic(err)
}
} else {
fmt.Print(test_str)
}
if err != io.EOF {
panic(err)
}
}

Loading…
Cancel
Save