Skip to content

Commit 9c07440

Browse files
authored
Merge pull request #73 from tholok97/day8
Day 8 in go
2 parents a27130f + 9d34e95 commit 9c07440

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

days/day-08/solutions/tholok97.go

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"os"
7+
"regexp"
8+
"strconv"
9+
)
10+
11+
type instruction struct {
12+
arg int
13+
op string
14+
}
15+
16+
func main() {
17+
scanner := bufio.NewScanner(os.Stdin)
18+
19+
instructions := make([]instruction, 0)
20+
21+
for scanner.Scan() {
22+
line := scanner.Text()
23+
24+
re := regexp.MustCompile(`^(nop|acc|jmp) ([+-]\d+)$`)
25+
matches := re.FindStringSubmatch(line)
26+
27+
arg, err := strconv.Atoi(matches[2])
28+
29+
if err != nil {
30+
panic("Misbehaving number")
31+
}
32+
33+
instructions = append(instructions, instruction{
34+
op: matches[1],
35+
arg: arg,
36+
})
37+
}
38+
39+
_, accumulator := run(instructions)
40+
41+
fmt.Println(accumulator)
42+
43+
for i := 0; i < len(instructions); i++ {
44+
swap := instructions[i].op
45+
46+
switch swap {
47+
case "jmp":
48+
instructions[i].op = "nop"
49+
case "nop":
50+
instructions[i].op = "jmp"
51+
default:
52+
continue
53+
}
54+
55+
isInfinite, accumulator := run(instructions)
56+
57+
if !isInfinite {
58+
fmt.Println(accumulator)
59+
break
60+
}
61+
62+
instructions[i].op = swap
63+
}
64+
}
65+
66+
func run(instructions []instruction) (isinfinite bool, accumulator int) {
67+
curr := 0
68+
69+
visited := make([]bool, len(instructions))
70+
71+
for {
72+
if curr == len(instructions) {
73+
return false, accumulator
74+
}
75+
76+
if visited[curr] {
77+
return true, accumulator
78+
}
79+
80+
visited[curr] = true
81+
82+
ins := instructions[curr]
83+
84+
switch ins.op {
85+
case "acc":
86+
accumulator += ins.arg
87+
curr++
88+
case "nop":
89+
curr++
90+
case "jmp":
91+
curr += ins.arg
92+
}
93+
}
94+
}

days/day-08/test.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ D=$(dirname $(realpath $0))
66

77
echo ""
88
echo "--- Day 8: Handheld Halting ---"
9+
$D/../../languages/go.sh $D/input.txt $D/output.txt $D/solutions/tholok97.go
910
$D/../../languages/sml.sh $D/input.txt $D/output.txt $D/solutions/day08.sml
1011
$D/../../languages/deno.sh $D/input.txt $D/output.txt $D/solutions/day08.ts
1112
echo ""

0 commit comments

Comments
 (0)