mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-05-19 03:23:27 +02:00
2017-day9: balanced parens with a twist
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var part int
|
||||
flag.IntVar(&part, "part", 1, "part 1 or 2")
|
||||
flag.Parse()
|
||||
fmt.Println("Running part", part)
|
||||
|
||||
ans := streamProcessing(util.ReadFile("./input.txt"), part)
|
||||
util.CopyToClipboard(fmt.Sprintf("%v", ans))
|
||||
fmt.Println("Output:", ans)
|
||||
}
|
||||
|
||||
func streamProcessing(input string, part int) int {
|
||||
var totalScore, garbageCount int
|
||||
|
||||
var inGarbage bool
|
||||
var openCurlies int // equivalent to the current group's score
|
||||
|
||||
for i := 0; i < len(input); i++ {
|
||||
char := string(input[i])
|
||||
if inGarbage {
|
||||
switch char {
|
||||
case "!":
|
||||
i++
|
||||
case ">":
|
||||
inGarbage = false
|
||||
default:
|
||||
garbageCount++ // part 2
|
||||
}
|
||||
} else {
|
||||
switch char {
|
||||
case "{":
|
||||
openCurlies++
|
||||
case "}":
|
||||
totalScore += openCurlies // part 1
|
||||
openCurlies--
|
||||
case "<":
|
||||
inGarbage = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if part == 1 {
|
||||
return totalScore
|
||||
}
|
||||
return garbageCount
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
func Test_streamProcessing(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
part int
|
||||
want int
|
||||
}{
|
||||
{"part1_example 1", "{}", 1, 1},
|
||||
{"part1_example 2", "{{}}", 1, 3},
|
||||
{"part1_example 1", "{{}, {}}", 1, 5},
|
||||
{"part1_example 1", "{{},<aksdljfsd!<> {}}", 1, 5},
|
||||
{"part1_actual", util.ReadFile("input.txt"), 1, 16021},
|
||||
{"part2_actual", util.ReadFile("input.txt"), 2, 7685},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := streamProcessing(tt.input, tt.part); got != tt.want {
|
||||
t.Errorf("streamProcessing() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user