-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
136 lines (109 loc) · 2.09 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"fmt"
"strconv"
"strings"
"github.com/devkvlt/aoc"
)
type Range struct {
dstStart int
srcStart int
len int
}
type Map []Range
func parseMaps(lines []string) []Map {
maps := []Map{}
for j := 0; j < len(lines); j++ {
if strings.HasSuffix(lines[j], " map:") {
m := Map{}
for i := j + 1; i < len(lines); i++ {
if lines[i] == "" {
break
}
fields := strings.Fields(lines[i])
d, _ := strconv.Atoi(fields[0])
s, _ := strconv.Atoi(fields[1])
l, _ := strconv.Atoi(fields[2])
m = append(m, Range{d, s, l})
}
maps = append(maps, m)
}
}
return maps
}
func src2dst(m Map, src int) int {
for _, r := range m {
d := src - r.srcStart
if 0 <= d && d < r.len {
return r.dstStart + d
}
}
return src
}
func dst2src(m Map, dst int) int {
for _, r := range m {
d := dst - r.dstStart
if 0 <= d && d < r.len {
return r.srcStart + d
}
}
return dst
}
func part1(lines []string) {
seeds := []int{}
for _, v := range strings.Split(lines[0][7:], " ") {
seed, _ := strconv.Atoi(v)
seeds = append(seeds, seed)
}
maps := parseMaps(lines)
best := seeds[0]
for i := 1; i < len(seeds); i++ {
src := seeds[i]
for _, m := range maps {
src = src2dst(m, src)
}
if src < best {
best = src
}
}
fmt.Println(best)
}
type SeedRange struct {
start int
count int
}
func inRange(ranges []SeedRange, seed int) bool {
for _, r := range ranges {
if r.start <= seed && seed < r.start+r.count {
return true
}
}
return false
}
func part2(lines []string) {
fields := strings.Split(lines[0][7:], " ")
seedRanges := []SeedRange{}
for i := 0; i < len(fields); i += 2 {
start, _ := strconv.Atoi(fields[i])
count, _ := strconv.Atoi(fields[i+1])
seedRanges = append(seedRanges, SeedRange{start, count})
}
maps := parseMaps(lines)
best := 0
for {
dst := best
for i := len(maps) - 1; i >= 0; i-- {
dst = dst2src(maps[i], dst)
}
if inRange(seedRanges, dst) {
break
}
best++
}
fmt.Println(best)
}
func main() {
lines := aoc.Lines("input")
part1(lines) // 174137457
part2(lines) // 1493866
}