algos added for splitting on multiple seperators

This commit is contained in:
alexchao26
2020-12-22 23:10:30 -05:00
parent 10abb50bca
commit c7da89ec4b
3 changed files with 54 additions and 17 deletions
+2 -17
View File
@@ -6,6 +6,7 @@ import (
"sort"
"strings"
"github.com/alexchao26/advent-of-code-go/algos"
"github.com/alexchao26/advent-of-code-go/util"
)
@@ -92,7 +93,7 @@ func parseInput(input string) (botsMap map[int][]int, rules []rule) {
}
botsMap[botID] = append(botsMap[botID], value)
} else {
parts := splitOn(line, []string{" gives ", " and "})
parts := algos.SplitStringOn(line, []string{" gives ", " and "})
r := rule{lowRule: parts[1], highRule: parts[2]}
_, err := fmt.Sscanf(parts[0], "bot %d", &r.botID)
if err != nil {
@@ -103,19 +104,3 @@ func parseInput(input string) (botsMap map[int][]int, rules []rule) {
}
return botsMap, rules
}
func splitOn(in string, cutset []string) []string {
parts := strings.Split(in, cutset[0])
cutset = cutset[1:]
var done bool
for !done && len(cutset) > 0 {
divider := cutset[0]
cutset = cutset[1:]
var newParts []string
for _, oldPart := range parts {
newParts = append(newParts, strings.Split(oldPart, divider)...)
}
parts = newParts
}
return parts
}
+21
View File
@@ -0,0 +1,21 @@
package algos
import "strings"
// SplitStringOn is like strings.Split but takes in a slice of strings that are
// all used as dividers in the incoming string
func SplitStringOn(in string, cutset []string) []string {
parts := strings.Split(in, cutset[0])
cutset = cutset[1:]
var done bool
for !done && len(cutset) > 0 {
divider := cutset[0]
cutset = cutset[1:]
var newParts []string
for _, oldPart := range parts {
newParts = append(newParts, strings.Split(oldPart, divider)...)
}
parts = newParts
}
return parts
}
+31
View File
@@ -0,0 +1,31 @@
package algos_test
import (
"reflect"
"testing"
"github.com/alexchao26/advent-of-code-go/algos"
)
func TestSplitStringOn(t *testing.T) {
type args struct {
in string
cutset []string
}
tests := []struct {
name string
args args
want []string
}{
{"simple_cutset_len_1", args{"bot 1 gets 4", []string{" gets "}}, []string{"bot 1", "4"}},
{"simple", args{"hello x world y potato", []string{" x ", " y "}}, []string{"hello", "world", "potato"}},
{"longer example", args{"onextwoxthree-one-two-threexfour", []string{"x", "-"}}, []string{"one", "two", "three", "one", "two", "three", "four"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := algos.SplitStringOn(tt.args.in, tt.args.cutset); !reflect.DeepEqual(got, tt.want) {
t.Errorf("SplitStringOn() = %v, want %v", got, tt.want)
}
})
}
}