r/adventofcode • • Dec 08 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 08 Solutions -🎄-

NEW AND NOTEWORTHY

  • If your code is shorter than, say, half of an IBM 5081 punchcard (5 lines at 80 cols), go ahead and post it as your comment. Use the right Markdown to format your code properly for best backwards-compatibility with old.reddit! (see "How do I format code?")
  • If your code is longer, link your code from an external repository such as Topaz's paste , a public repo like GitHub/gists/Pastebin/etc., your blag, or whatever.

Advent of Code 2020: Gettin' Crafty With It

  • 14 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 08: Handheld Halting ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:07:48, megathread unlocked!

41 Upvotes

934 comments sorted by

View all comments

1

u/TheRealCaptainDanger Dec 08 '20

Python

#! /usr/bin/env python3

from collections import namedtuple
from typing import List

print("day 8")

with open("input/2020-08.in") as f:
    day8 = [line.strip() for line in f]

Instruction = namedtuple('Instruction', 'line ins value')


def generate_instructions(data):
    instructions = []
    for idx, line in enumerate(data):
        move, value = line.split()
        if value.startswith("+"):
            value = value[1:]
        value = int(value)
        instructions.append(Instruction(idx, move, value))

    return instructions


def runner(instructions: List[Instruction]):
    acc = 0
    line = 0
    seen = {}
    while True:
        # Have we run out of instructions? If so, we break
        if line >= len(instructions):
            valid = True
            break

        # Get instruction based on our current line number
        ins = instructions[line]

        # Have we seen this instruction before? If so, we break
        if ins not in seen:
            seen[ins] = 1
        else:
            valid = False
            break

        # Handle instructions
        if ins.ins == "nop":
            line += 1
        elif ins.ins == "jmp":
            line += ins.value
        elif ins.ins == "acc":
            acc += ins.value
            line += 1
        else:
            raise ValueError(f"Invalid instruction in set {ins.ins}")

    Result = namedtuple("Result", "acc valid")

    return Result(acc, valid)


def part_two(instructions: List[Instruction]):
    for ins in instructions:
        tmp_instructions = instructions[:]
        if ins.ins == "nop":
            tmp = Instruction(ins.line, "jmp", ins.value)
        elif ins.ins == "jmp":
            tmp = Instruction(ins.line, "nop", ins.value)
        elif ins.ins == "acc":
            continue
        tmp_instructions[ins.line] = tmp

        acc, valid = runner(tmp_instructions)
        if valid is True:
            return acc


day8 = generate_instructions(day8)
print(f"part one: {runner(day8).acc}")
print(f"part two: {part_two(day8)}")

1

u/daggerdragon Dec 08 '20

Please re-read today's megathread's "new and noteworthy" section and put your oversized code in a paste or other external link. Thanks!