From 49b68602ffa019716e82d86345568a9ccfcb08d1 Mon Sep 17 00:00:00 2001 From: tholok97 Date: Tue, 8 Dec 2020 19:57:27 +0100 Subject: [PATCH] day 8 in go --- days/day-08/solutions/tholok97.go | 94 +++++++++++++++++++++++++++++++ days/day-08/test.sh | 1 + 2 files changed, 95 insertions(+) create mode 100644 days/day-08/solutions/tholok97.go diff --git a/days/day-08/solutions/tholok97.go b/days/day-08/solutions/tholok97.go new file mode 100644 index 00000000..c06ab115 --- /dev/null +++ b/days/day-08/solutions/tholok97.go @@ -0,0 +1,94 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "regexp" + "strconv" +) + +type instruction struct { + arg int + op string +} + +func main() { + scanner := bufio.NewScanner(os.Stdin) + + instructions := make([]instruction, 0) + + for scanner.Scan() { + line := scanner.Text() + + re := regexp.MustCompile(`^(nop|acc|jmp) ([+-]\d+)$`) + matches := re.FindStringSubmatch(line) + + arg, err := strconv.Atoi(matches[2]) + + if err != nil { + panic("Misbehaving number") + } + + instructions = append(instructions, instruction{ + op: matches[1], + arg: arg, + }) + } + + _, accumulator := run(instructions) + + fmt.Println(accumulator) + + for i := 0; i < len(instructions); i++ { + swap := instructions[i].op + + switch swap { + case "jmp": + instructions[i].op = "nop" + case "nop": + instructions[i].op = "jmp" + default: + continue + } + + isInfinite, accumulator := run(instructions) + + if !isInfinite { + fmt.Println(accumulator) + break + } + + instructions[i].op = swap + } +} + +func run(instructions []instruction) (isinfinite bool, accumulator int) { + curr := 0 + + visited := make([]bool, len(instructions)) + + for { + if curr == len(instructions) { + return false, accumulator + } + + if visited[curr] { + return true, accumulator + } + + visited[curr] = true + + ins := instructions[curr] + + switch ins.op { + case "acc": + accumulator += ins.arg + curr++ + case "nop": + curr++ + case "jmp": + curr += ins.arg + } + } +} diff --git a/days/day-08/test.sh b/days/day-08/test.sh index b5be87c9..be8072ec 100755 --- a/days/day-08/test.sh +++ b/days/day-08/test.sh @@ -6,4 +6,5 @@ D=$(dirname $(realpath $0)) echo "" echo "--- Day 8: Handheld Halting ---" +$D/../../languages/go.sh $D/input.txt $D/output.txt $D/solutions/tholok97.go echo ""