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 69f9fb9e..727d6560 100755 --- a/days/day-08/test.sh +++ b/days/day-08/test.sh @@ -6,6 +6,7 @@ D=$(dirname $(realpath $0)) echo "" echo "--- Day 8: Handheld Halting ---" +$D/../../languages/go.sh $D/input.txt $D/output.txt $D/solutions/tholok97.go $D/../../languages/sml.sh $D/input.txt $D/output.txt $D/solutions/day08.sml $D/../../languages/deno.sh $D/input.txt $D/output.txt $D/solutions/day08.ts echo ""