-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
129 lines (115 loc) · 1.76 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
// NOTE: kinda difficult...
package main
import (
"fmt"
"slices"
"github.com/devkvlt/aoc"
)
var (
disk []int
ptr int
)
func init() {
for k, v := range aoc.Lines("input")[0] {
var what int
if k%2 == 0 {
what = k / 2
} else {
what = -1
}
for range int(v - '0') {
disk = append(disk, what)
}
}
ptr = len(disk) - 1
}
// func DEBUG() {
// for _, x := range disk {
// if x == -1 {
// fmt.Printf(".")
// } else {
// fmt.Printf("%d", x)
// }
// }
// fmt.Println()
// }
func checksum(disk []int) int {
sum := 0
for i, id := range disk {
if id != -1 {
sum += i * id
}
}
return sum
}
func part1() {
disk := slices.Clone(disk)
for l, r := 0, len(disk)-1; l < r; {
if disk[r] != -1 && disk[l] == -1 {
disk[l] = disk[r]
disk[r] = -1
}
if disk[l] != -1 {
l++
}
if disk[r] == -1 {
r--
}
}
fmt.Println(checksum(disk))
}
func nextFile() (int, int) {
end := ptr
for end >= 0 && disk[end] == -1 {
end--
}
if end < 0 {
return -1, -1
}
start := end
for start >= 0 && disk[start] == disk[end] {
start--
}
start++
ptr = start - 1
return start, end
}
func nextBlankStart(size int) int {
for i := 0; i <= ptr-size+1; i++ {
isBlank := true
for j := 0; j < size; j++ {
if disk[i+j] != -1 {
isBlank = false
break
}
}
if isBlank {
return i
}
}
return -1
}
func part2() {
var start, end, size int
var blankStart int
for {
start, end = nextFile()
size = end - start + 1
blankStart = nextBlankStart(size)
if start != -1 {
if blankStart != -1 {
for m := 0; m < size; m++ {
disk[blankStart+m] = disk[start]
disk[end-m] = -1
}
}
} else {
break
}
}
fmt.Println(checksum(disk))
}
func main() {
part1() // 6446899523367
part2() // 6478232739671
}