mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-05-18 19:13:27 +02:00
2016-day9: really... ugly... dfs string parsing algo
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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 := decompressLength(util.ReadFile("./input.txt"), part)
|
||||
fmt.Println("Output:", ans)
|
||||
}
|
||||
|
||||
// well...... this is gross.......
|
||||
func decompressLength(in string, part int) int {
|
||||
var decompressedLen int
|
||||
for i := 0; i < len(in); {
|
||||
switch in[i] {
|
||||
case '(':
|
||||
// find index of closing paren, then find total length of substring
|
||||
relativeCloseIndex := strings.Index(in[i:], ")")
|
||||
closeIndex := relativeCloseIndex + i
|
||||
|
||||
var copyLen, repeat int
|
||||
fmt.Sscanf(in[i:closeIndex+1], "(%dx%d)", ©Len, &repeat)
|
||||
|
||||
substring := in[closeIndex+1 : closeIndex+1+copyLen]
|
||||
patternLength := len(substring)
|
||||
if part == 2 {
|
||||
patternLength = decompressLength(substring, 2)
|
||||
}
|
||||
decompressedLen += patternLength * repeat
|
||||
// jump the closed paren (+1) the length of the substring from THIS
|
||||
// function call
|
||||
i = closeIndex + 1 + len(substring)
|
||||
default:
|
||||
decompressedLen++
|
||||
i++
|
||||
}
|
||||
}
|
||||
return decompressedLen
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
func Test_decompressLength(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
part int
|
||||
want int
|
||||
}{
|
||||
{"example part1_0", "ADVENT", 1, len("ADVENT")},
|
||||
{"example part1_1", "A(1x5)BC", 1, len("ABBBBBC")},
|
||||
{"example part1_2", "(6x1)(1x3)A", 1, len("(1x3)A")},
|
||||
{"actual part1", util.ReadFile("input.txt"), 1, 107035},
|
||||
{"example part2_1", "X(8x2)(3x3)ABCY", 2, len("XABCABCABCABCABCABCY")},
|
||||
{"example part2_2", "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN", 2, 445},
|
||||
{"actual part2", util.ReadFile("input.txt"), 2, 11451628995},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := decompressLength(tt.input, tt.part); got != tt.want {
|
||||
t.Errorf("decompressLength() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user