advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

main.go (1247B)

    1 package main
    2 
    3 import (
    4 	"bufio"
    5 	"fmt"
    6 	"os"
    7 	"strconv"
    8 	"strings"
    9 )
   10 
   11 const (
   12 	NOP = iota
   13 	ACC
   14 	JMP
   15 )
   16 
   17 func readInput(filename string) (ops []int, args []int) {
   18 	file, _ := os.Open(filename)
   19 	defer file.Close()
   20 	op_table := map[string]int{
   21 		"nop": NOP,
   22 		"acc": ACC,
   23 		"jmp": JMP,
   24 	}
   25 	scanner := bufio.NewScanner(file)
   26 	for scanner.Scan() {
   27 		inst := strings.Split(scanner.Text(), " ")
   28 		ops = append(ops, op_table[inst[0]])
   29 		arg, _ := strconv.Atoi(inst[1])
   30 		args = append(args, arg)
   31 	}
   32 	return
   33 }
   34 
   35 func main() {
   36 	ops, args := readInput("./input.txt")
   37 	// 1179
   38 	fmt.Println(part1(ops, args))
   39 	// 1089
   40 	fmt.Println(part2(ops, args))
   41 }
   42 
   43 func part1(ops []int, args []int) (acc int, fin bool) {
   44 	exec := make([]bool, len(ops))
   45 	ip := 0
   46 	for ip < len(exec) && !exec[ip] {
   47 		exec[ip] = true
   48 		switch ops[ip] {
   49 		case NOP:
   50 			ip += 1
   51 		case JMP:
   52 			ip += args[ip]
   53 		case ACC:
   54 			acc += args[ip]
   55 			ip += 1
   56 		}
   57 	}
   58 	fin = ip >= len(exec)
   59 	return
   60 }
   61 
   62 func part2(ops []int, args []int) (acc int, fin bool) {
   63 	for i := 0; i < len(ops); i++ {
   64 		old_op := ops[i]
   65 		switch ops[i] {
   66 		case ACC:
   67 			continue
   68 		case JMP:
   69 			ops[i] = NOP
   70 		case NOP:
   71 			ops[i] = JMP
   72 		}
   73 		acc, fin = part1(ops, args)
   74 		ops[i] = old_op
   75 		if fin {
   76 			return
   77 		}
   78 	}
   79 	return 0, false
   80 }