AdventOfCode2023/04/main.go

136 lines
2.3 KiB
Go
Raw Normal View History

2023-12-04 19:11:44 +00:00
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"time"
)
func mustAtoi(line []rune) int {
i, _ := strconv.Atoi(string(line))
return i
}
func main() {
start := time.Now()
partOne()
duration := time.Since(start)
partTwo()
duration2 := time.Since(start)
fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration)
}
func makeScanner(test bool) *bufio.Scanner {
var f *os.File
if test {
f, _ = os.Open("inputs/testinput")
} else {
f, _ = os.Open("inputs/input")
}
reader := bufio.NewReader(f)
return bufio.NewScanner(reader)
}
func partOne() {
scanner := makeScanner(false)
sum := 0
for scanner.Scan() {
line := scanner.Text()
draws := map[int]struct{}{}
state := 0
acc := []rune{}
score := 0
for _, c := range line {
// slice off the 'game :' part
if state == 0 {
if c == ':' {
state = 1
}
continue
}
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
acc = append(acc, c)
case '|':
state = 2
acc = []rune{}
case ' ':
if len(acc) != 0 && state == 1 {
draws[mustAtoi(acc)] = struct{}{}
} else if state == 2 {
if _, ok := draws[mustAtoi(acc)]; ok {
if score == 0 {
score = 1
} else {
score *= 2
}
}
}
acc = []rune{}
}
}
if _, ok := draws[mustAtoi(acc)]; ok {
if score == 0 {
score = 1
} else {
score *= 2
}
}
sum += score
}
fmt.Println(sum)
}
func partTwo() {
scanner := makeScanner(false)
card := 1
dupes := map[int]int{}
sum := 0
for scanner.Scan() {
line := scanner.Text()
draws := map[int]struct{}{}
state := 0
acc := []rune{}
score := 0
dupes[card]++
for _, c := range line {
// slice off the 'game :' part
if state == 0 {
if c == ':' {
state = 1
}
continue
}
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
acc = append(acc, c)
case '|':
state = 2
acc = []rune{}
case ' ':
if len(acc) != 0 && state == 1 {
draws[mustAtoi(acc)] = struct{}{}
} else if state == 2 {
if _, ok := draws[mustAtoi(acc)]; ok {
score++
}
}
acc = []rune{}
}
}
if _, ok := draws[mustAtoi(acc)]; ok {
score++
}
for i := card + 1; i <= card+score; i++ {
dupes[i] += dupes[card]
}
sum += dupes[card]
card++
}
fmt.Println(sum)
}