-
Notifications
You must be signed in to change notification settings - Fork 0
/
day04.go
90 lines (75 loc) · 1.49 KB
/
day04.go
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
package main
import (
_ "embed"
"fmt"
"strings"
)
//go:embed input.txt
var input string
func findStart(line string) int {
for i := 6; i < len(line); i++ {
if line[i] == ':' {
return i + 2
}
}
return 0
}
func findMidline(line string) int {
for i := 9; i < len(line); i++ {
if line[i] == '|' {
return i
}
}
return 0
}
func amountOfMatches(line string, start, midline int) int {
var amount int
for i := start; i < midline-1; i += 3 {
for j := midline + 2; j < len(line); j += 3 {
if line[i] == line[j] && line[i+1] == line[j+1] {
amount++
break
}
}
}
return amount
}
func pow2(n int) int {
if n > 0 {
return 1 << n
} else if n == 0 {
return 1
}
return 0
}
func part1(input string) int {
lines := strings.Split(input, "\n")
start := findStart(lines[0])
midline := findMidline(lines[0])
var sum int
for _, line := range lines {
amount := amountOfMatches(line, start, midline)
sum += pow2(amount - 1)
}
return sum
}
func part2(input string) int {
lines := strings.Split(input, "\n")
start := findStart(lines[0])
midline := findMidline(lines[0])
var sum int
cards := make([]int, len(lines))
for lineIndex, line := range lines {
amount := amountOfMatches(line, start, midline)
for i := 0; i < amount; i++ {
cards[lineIndex+1+i] += cards[lineIndex] + 1
}
sum += cards[lineIndex] + 1
}
return sum
}
func main() {
fmt.Println("--- 2023 day 04 answer ---")
fmt.Println("part 1:\t", part1(input))
fmt.Println("part 2:\t", part2(input))
}