mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-06-07 12:45:10 +02:00
2015-day8: calculating encoded and decoded string lengths
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
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)
|
||||
|
||||
var ans int
|
||||
if part == 1 {
|
||||
ans = part1(util.ReadFile("./input.txt"))
|
||||
} else {
|
||||
ans = part2(util.ReadFile("./input.txt"))
|
||||
}
|
||||
fmt.Println("Output:", ans)
|
||||
}
|
||||
|
||||
func part1(input string) int {
|
||||
var codeChars, stringChars int
|
||||
for _, line := range strings.Split(input, "\n") {
|
||||
codeChars += len(line)
|
||||
|
||||
for i := 1; i < len(line)-1; i++ {
|
||||
switch line[i] {
|
||||
case '\\':
|
||||
nextChar := line[i+1]
|
||||
if nextChar == '\\' || nextChar == '"' {
|
||||
i++ // skip an extra character
|
||||
} else if nextChar == 'x' {
|
||||
i += 3 // skip 2 extra chars
|
||||
}
|
||||
}
|
||||
stringChars++
|
||||
}
|
||||
}
|
||||
|
||||
return codeChars - stringChars
|
||||
}
|
||||
|
||||
func part2(input string) int {
|
||||
var encodedLen, originalLen int
|
||||
for _, line := range strings.Split(input, "\n") {
|
||||
originalLen += len(line)
|
||||
encodedLen += 2 // outer quotes
|
||||
for i := 0; i < len(line); i++ {
|
||||
switch line[i] {
|
||||
case '"', '\\':
|
||||
encodedLen += 2
|
||||
default:
|
||||
encodedLen++
|
||||
}
|
||||
}
|
||||
}
|
||||
return encodedLen - originalLen
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
func Test_part1(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want int
|
||||
}{
|
||||
{"actual", util.ReadFile("input.txt"), 1371},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := part1(tt.input); got != tt.want {
|
||||
t.Errorf("part1() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_part2(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want int
|
||||
}{
|
||||
{"actual", util.ReadFile("input.txt"), 2117},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := part2(tt.input); got != tt.want {
|
||||
t.Errorf("part2() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user