97 lines
1.4 KiB
Go
97 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func readLines(filename string) []string {
|
|
raw, err := os.ReadFile(filename)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return strings.Split(string(raw), "\n")
|
|
}
|
|
|
|
func parseLine(line string) (int, error) {
|
|
var c int
|
|
switch {
|
|
case strings.HasPrefix(line, "R"):
|
|
c = 1
|
|
case strings.HasPrefix(line, "L"):
|
|
c = -1
|
|
default:
|
|
return 0, fmt.Errorf("invalid line")
|
|
}
|
|
x, err := strconv.Atoi(line[1:])
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
if x <= 0 {
|
|
return x, fmt.Errorf("non-positive value")
|
|
}
|
|
return c * x, nil
|
|
}
|
|
|
|
func countZeros(lines []string) int {
|
|
count := 0
|
|
current := 50
|
|
max := 100
|
|
for _, line := range lines {
|
|
if line == "" {
|
|
continue
|
|
}
|
|
x, err := parseLine(line)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
current = (current + x) % max
|
|
if current == 0 {
|
|
count++
|
|
}
|
|
}
|
|
return count
|
|
}
|
|
|
|
func countClicks(lines []string) int {
|
|
count := 0
|
|
current := 50
|
|
max := 100
|
|
for _, line := range lines {
|
|
if line == "" {
|
|
continue
|
|
}
|
|
x, err := parseLine(line)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
for {
|
|
if x > 0 {
|
|
x--
|
|
current++
|
|
if current == 0 || current == max {
|
|
count++
|
|
current = 0
|
|
}
|
|
} else if x < 0 {
|
|
x++
|
|
current--
|
|
if current == 0 || current == -max {
|
|
count++
|
|
current = 0
|
|
}
|
|
} else {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return count
|
|
}
|
|
|
|
func main() {
|
|
lines := readLines("part1.txt")
|
|
println(countZeros(lines))
|
|
println(countClicks(lines))
|
|
}
|