-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (88 loc) · 1.96 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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
// cmd is a structure for one command, which consists of (ins)truction and (arg)ument
type cmd struct {
ins string
arg int
}
// isInSlice returns a boolean true if "n" is "in" sl or false if "n" is not in "sl"
func isInSlice(n int, sl []int) bool {
for _, v := range sl {
if n == v {
return true
}
}
return false
}
// isInfiniteLoop tests the command list to be an inf loop of not to be an inf loop and returns boolean value and acc value
func isInfiniteLoop(cmds []cmd) (bool, int) {
var calledInstructions []int
acc := 0
for i := 0; i < len(cmds); i++ {
// test if this instruction has been already called
if isInSlice(i, calledInstructions) {
return true, acc
}
calledInstructions = append(calledInstructions, i)
// "run" the command
switch cmds[i].ins {
case "nop":
break
case "acc":
acc += cmds[i].arg
break
case "jmp":
i += cmds[i].arg - 1
break
}
}
return false, acc
}
func main() {
// open file with the input values
file, err := os.Open("input.txt")
if err != nil {
log.Fatal("Cannot open the input file.")
}
defer file.Close()
// open a scanner to read from the file
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
// process all lines
var cmds []cmd
for scanner.Scan() {
val := scanner.Text()
ins := val[:3]
arg, _ := strconv.Atoi(val[4:])
cmds = append(cmds, cmd{
ins: ins,
arg: arg,
})
}
// part 1 - what is the acc value before starting inf loop
_, acc := isInfiniteLoop(cmds)
fmt.Println("Part 1:", acc)
// part 2 - what has to be changed to break the inf loop
for i, c := range cmds {
// change exactly one jmp/nop command
if c.ins == "nop" {
cmds[i].ins = "jmp"
} else if c.ins == "jmp" {
cmds[i].ins = "nop"
}
// if this is not an inf loop, print acc
inf, acc := isInfiniteLoop(cmds)
if !inf {
fmt.Println("Part 2:", acc)
break
}
// reset previous value
cmds[i].ins = c.ins
}
}