This commit is contained in:
2024-12-06 00:43:31 +01:00
parent 35ef0a9776
commit 080b6ba980
5 changed files with 1530 additions and 0 deletions

1385
day5/data.txt Normal file

File diff suppressed because it is too large Load Diff

28
day5/example.txt Normal file
View File

@ -0,0 +1,28 @@
47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47

3
day5/go.mod Normal file
View File

@ -0,0 +1,3 @@
module stevenlr.com/aoc2024/day5
go 1.22.2

113
day5/main.go Normal file
View File

@ -0,0 +1,113 @@
package main
import (
"bufio"
"fmt"
"os"
"slices"
"sort"
"strconv"
"strings"
)
func main() {
fmt.Println(doTheThing("example.txt"))
fmt.Println(doTheThing("data.txt"))
}
func fill[T any](s []T, value T) {
for i := range s {
s[i] = value
}
}
func doTheThing(fileName string) (resultPart1, resultPart2 int) {
fp, err := os.Open(fileName)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(fp)
forbiddenAfter := readForbiddenAfter(scanner)
seen := make([]bool, 100)
forbidden := make([]bool, 100)
for scanner.Scan() {
seq := readLine(strings.TrimSpace(scanner.Text()))
fill(seen, false)
fill(forbidden, false)
ok := true
for _, n := range seq {
if seen[n] {
continue
}
if forbidden[n] {
ok = false
break
}
for _, f := range forbiddenAfter[n] {
forbidden[f] = true
}
seen[n] = true
}
if ok {
resultPart1 += seq[len(seq)/2]
} else {
sort.Slice(seq, func(i, j int) bool {
return slices.Index(forbiddenAfter[seq[j]], seq[i]) != -1
})
resultPart2 += seq[len(seq)/2]
}
}
return
}
func readLine(s string) (line []int) {
split := strings.Split(s, ",")
line = make([]int, len(split))
for i, num := range split {
n, err := strconv.Atoi(num)
if err != nil {
panic(err)
}
line[i] = n
}
return
}
func readForbiddenAfter(scanner *bufio.Scanner) (forbiddenAfter map[int][]int) {
forbiddenAfter = make(map[int][]int)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 {
return
}
split := strings.Split(line, "|")
if len(split) != 2 {
panic("Not enough data for ordering")
}
a, err := strconv.Atoi(split[0])
if err != nil {
panic(err)
}
b, err := strconv.Atoi(split[1])
if err != nil {
panic(err)
}
forbiddenAfter[b] = append(forbiddenAfter[b], a)
}
return
}

View File

@ -5,4 +5,5 @@ use (
./day2 ./day2
./day3 ./day3
./day4 ./day4
./day5
) )