|
| 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 | +} |
0 commit comments