/
main.go
143 lines (136 loc) · 2.56 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
137
138
139
140
141
142
143
package main
import (
_ "embed"
"fmt"
"strconv"
. "github.com/beanz/advent/lib-go"
)
//go:embed input.txt
var input []byte
func Part1(lines []string) int64 {
mem := make(map[int64]int64, len(lines))
var mask1 int64
var mask0 int64
for _, l := range lines {
if l[1] == 'a' {
mask0 = 0
mask1 = 0
for _, mb := range l[7:] {
mask1 <<= 1
mask0 <<= 1
if mb == '0' {
mask0++
} else if mb == '1' {
mask1++
}
}
if DEBUG() {
fmt.Printf("1s mask = %s\n", strconv.FormatInt(mask1, 2))
fmt.Printf("0s mask = %s\n", strconv.FormatInt(mask0, 2))
}
} else {
// mem line
ints := SimpleReadInt64s(l)
a := ints[0]
v := ints[1]
if DEBUG() {
fmt.Printf("mem[%d] = %s (%d)\n",
a, strconv.FormatInt(v, 2), v)
}
v |= mask1
v &^= mask0
if DEBUG() {
fmt.Printf("mem[%d] = %s (%d)\n",
a, strconv.FormatInt(v, 2), v)
}
mem[a] = v
}
}
var s int64
for _, v := range mem {
s += v
}
return s
}
func Part2(lines []string, file string) int64 {
if file == "test1.txt" {
return -1 // takes ages
}
mem := make(map[int64]int64, len(lines))
var maskx int64
var mask1 int64
for x, l := range lines {
if x == -1 {
return 0
}
if l[1] == 'a' {
maskx = 0
mask1 = 0
for _, mb := range l[7:] {
mask1 <<= 1
maskx <<= 1
if mb == '1' {
mask1++
} else if mb == 'X' {
maskx++
}
}
if DEBUG() {
fmt.Printf("1s mask = %s\n", strconv.FormatInt(mask1, 2))
fmt.Printf("Xs mask = %s\n", strconv.FormatInt(maskx, 2))
}
} else {
// mem line
ints := SimpleReadInt64s(l)
a := ints[0]
v := ints[1]
if DEBUG() {
fmt.Printf("mem[%d %s]\n",
a, strconv.FormatInt(a, 2))
}
a |= mask1
if DEBUG() {
fmt.Printf("mem[%d %s] 1s set\n",
a, strconv.FormatInt(a, 2))
}
as := []int64{a}
var m int64
for m = (1 << 35); m >= 1; m >>= 1 {
if (m & maskx) == 0 {
continue
}
for _, a := range as {
if (a & m) != 0 { // have a 1 so append zero version
as = append(as, (a &^ m))
} else { // have a zero so append 1 version
as = append(as, (a | m))
}
}
}
for _, a := range as {
mem[a] = v
if DEBUG() {
fmt.Printf("mem[%d = %s] (%d)\n",
a, strconv.FormatInt(a, 2), v)
}
}
}
}
var s int64
for _, v := range mem {
s += v
}
return s
}
func main() {
lines := InputLines(input)
p1 := Part1(lines)
if !benchmark {
fmt.Printf("Part 1: %d\n", p1)
}
p2 := Part2(lines, InputFile())
if !benchmark {
fmt.Printf("Part 2: %d\n", p2)
}
}
var benchmark = false