-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (71 loc) · 1.55 KB
/
main.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
91
92
93
package main
import (
"fmt"
"io"
"os"
"slices"
"strconv"
"strings"
)
func main() {
input, _ := io.ReadAll(os.Stdin)
fmt.Printf("Part 1: %d\n", part1(input))
fmt.Printf("Part 2: %d\n", part2(input))
}
func part1(input []byte) int {
seeds, maps := parse(input)
var locations []int
for _, cur := range seeds {
nextMap:
for _, m := range maps {
for _, l := range m {
if cur >= l[1] && cur < l[1]+l[2] {
cur = l[0] + cur - l[1]
continue nextMap
}
}
}
locations = append(locations, cur)
}
return slices.Min(locations)
}
func part2(input []byte) int {
seeds, maps := parse(input)
var minLocation int
for n := 0; n < len(seeds)-1; n += 2 {
start, length := seeds[n], seeds[n+1]
for seed := start; seed < start+length; seed++ {
cur := seed
nextMap:
for _, m := range maps {
for _, l := range m {
if cur >= l[1] && cur < l[1]+l[2] {
cur = l[0] + cur - l[1]
continue nextMap
}
}
}
if minLocation == 0 || cur < minLocation {
minLocation = cur
}
}
}
return minLocation
}
func parse(input []byte) (seeds []int, maps [][][3]int) {
parts := strings.Split(string(input), "\n\n")
for _, s := range strings.Fields(parts[0][7:]) {
n, _ := strconv.Atoi(s)
seeds = append(seeds, n)
}
for _, mapStr := range parts[1:] {
var lines [][3]int
for _, lineStr := range strings.Split(strings.TrimSpace(mapStr), "\n")[1:] {
var l [3]int
fmt.Sscanf(lineStr, "%d %d %d", &l[0], &l[1], &l[2])
lines = append(lines, l)
}
maps = append(maps, lines)
}
return seeds, maps
}