Skip to content

Commit 8452b6a

Browse files
committed
add day 17 part 2
1 parent a01ccb1 commit 8452b6a

File tree

1 file changed

+40
-24
lines changed

1 file changed

+40
-24
lines changed

d17.go

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,10 @@ import (
77
)
88

99
type d17puter struct {
10-
a, b, c int64
11-
program []int
12-
ip int64
13-
out []int64
14-
quine bool
15-
quineCnt int
10+
a, b, c int64
11+
program []int
12+
ip int64
13+
out []int64
1614
}
1715

1816
func (p *d17puter) load(input []string) {
@@ -39,8 +37,6 @@ func (p *d17puter) load(input []string) {
3937
p.c = n
4038
}
4139
}
42-
p.quine = true
43-
p.quineCnt = 0
4440
}
4541

4642
func (p *d17puter) combo(val int64) int64 {
@@ -60,9 +56,6 @@ func (p *d17puter) combo(val int64) int64 {
6056

6157
func (p *d17puter) cycle() bool {
6258
if p.ip >= int64(len(p.program)) || p.ip+1 >= int64(len(p.program)) {
63-
if p.quineCnt < len(p.program) {
64-
p.quine = false
65-
}
6659
return false
6760
}
6861
op := int64(p.program[p.ip])
@@ -88,11 +81,6 @@ func (p *d17puter) cycle() bool {
8881
case 5: // out
8982
val = p.combo(val)
9083
p.out = append(p.out, val%8)
91-
if p.quine && len(p.out) <= len(p.program) && p.out[len(p.out)-1] == int64(p.program[len(p.out)-1]) {
92-
p.quineCnt++
93-
} else {
94-
p.quine = false
95-
}
9684
case 6: // bdv
9785
val = p.combo(val)
9886
p.b = int64(float64(p.a) / math.Pow(2, float64(val)))
@@ -106,12 +94,9 @@ func (p *d17puter) cycle() bool {
10694
return true
10795
}
10896

109-
func (p *d17puter) run(quine bool) bool {
97+
func (p *d17puter) run() bool {
11098
for {
11199
running := p.cycle()
112-
if quine && !p.quine {
113-
return false
114-
}
115100
if !running {
116101
return true
117102
}
@@ -123,9 +108,7 @@ func (p *d17puter) reset() {
123108
p.b = 0
124109
p.c = 0
125110
p.ip = 0
126-
p.quine = true
127111
p.out = nil
128-
p.quineCnt = 0
129112
}
130113

131114
func (p *d17puter) printOutput() string {
@@ -144,9 +127,42 @@ func (*methods) D17P1(input string) string {
144127

145128
p := &d17puter{}
146129
p.load(lines)
147-
p.run(false)
130+
p.run()
148131

149132
return p.printOutput()
150133
}
151134

152-
//TODO: D17P2
135+
// 000 - 7
136+
// 001 - 6
137+
// 010 - 4
138+
// 011 - 7
139+
// 100 - 3
140+
// 101 - 2
141+
// 110 - 1
142+
// 111 - 0
143+
func (*methods) D17P2(input string) string {
144+
lines := strings.Split(strings.TrimSpace(input), "\n")
145+
if len(lines) != 5 {
146+
return "invalid input (unexpected amount of lines)"
147+
}
148+
149+
p := &d17puter{}
150+
p.load(lines)
151+
152+
a := int64(0b111) // this produces 0 in the end
153+
for i := len(p.program) - 2; i >= 0; i-- {
154+
a <<= 3
155+
d := p.program[i]
156+
for j := 0; j < 8; j++ {
157+
p.reset()
158+
p.a = a + int64(j)
159+
p.run()
160+
if int64(d) == p.out[0] {
161+
a += int64(j)
162+
break
163+
}
164+
}
165+
}
166+
167+
return strconv.FormatInt(a, 10)
168+
}

0 commit comments

Comments
 (0)