|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "os" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +type instr struct { |
| 13 | + op string |
| 14 | + param1 string |
| 15 | + param2 int |
| 16 | +} |
| 17 | + |
| 18 | +func sim(instructions []instr, registers map[string]int) int { |
| 19 | + for ip := 0; ip < len(instructions); ip++ { |
| 20 | + op := instructions[ip] |
| 21 | + // fmt.Println(ip, op, registers) |
| 22 | + switch op.op { |
| 23 | + case "hlf": |
| 24 | + registers[op.param1] /= 2 |
| 25 | + case "tpl": |
| 26 | + registers[op.param1] *= 3 |
| 27 | + case "inc": |
| 28 | + registers[op.param1]++ |
| 29 | + case "jmp": |
| 30 | + ip += op.param2 - 1 |
| 31 | + case "jie": |
| 32 | + if registers[op.param1]%2 == 0 { |
| 33 | + // fmt.Println("jumping") |
| 34 | + ip += op.param2 - 1 |
| 35 | + } |
| 36 | + case "jio": |
| 37 | + // fmt.Println("j", op.param1, registers[op.param1], registers) |
| 38 | + if registers[op.param1] == 1 { |
| 39 | + // fmt.Println("jumping1") |
| 40 | + ip += op.param2 - 1 |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + return registers["b"] |
| 45 | +} |
| 46 | +func day22(file string) (int, int) { |
| 47 | + part1, part2 := 0, 0 |
| 48 | + f, err := os.Open(file) |
| 49 | + if err != nil { |
| 50 | + log.Fatal(err) |
| 51 | + } |
| 52 | + defer f.Close() |
| 53 | + |
| 54 | + scanner := bufio.NewScanner(f) |
| 55 | + instructions := []instr{} |
| 56 | + for scanner.Scan() { |
| 57 | + t := strings.ReplaceAll(scanner.Text(), ",", "") |
| 58 | + words := strings.Split(t, " ") |
| 59 | + switch words[0] { |
| 60 | + case "inc", "tpl", "hlf": |
| 61 | + instructions = append(instructions, instr{op: words[0], param1: words[1]}) |
| 62 | + case "jmp": |
| 63 | + p, _ := strconv.Atoi(words[1]) |
| 64 | + instructions = append(instructions, instr{op: words[0], param2: p}) |
| 65 | + case "jie", "jio": |
| 66 | + p, _ := strconv.Atoi(words[2]) |
| 67 | + instructions = append(instructions, instr{op: words[0], param1: words[1], param2: p}) |
| 68 | + } |
| 69 | + } |
| 70 | + fmt.Printf("%+v\n", instructions) |
| 71 | + |
| 72 | + registers := map[string]int{"a": 0, "b": 0} |
| 73 | + part1 = sim(instructions, registers) |
| 74 | + registers = map[string]int{"a": 1, "b": 0} |
| 75 | + part2 = sim(instructions, registers) |
| 76 | + |
| 77 | + return part1, part2 |
| 78 | +} |
| 79 | + |
| 80 | +func main() { |
| 81 | + log.SetFlags(log.Lshortfile | log.LstdFlags) |
| 82 | + |
| 83 | + part1, part2 := day22("test.txt") |
| 84 | + fmt.Println(part1, part2) |
| 85 | + fmt.Println(day22("input.txt")) |
| 86 | +} |
0 commit comments