summaryrefslogtreecommitdiff
path: root/day5/main.go
blob: 1dd1672aa0e91e712a7570cc9396be800c1b77f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
}