Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 10, 2022 19:18
Embed
What would you like to do?
# Define the instruction set
INSTRUCTION_SET = {
"addx": lambda x, v: x + v,
"noop": lambda x, v: x
}
# Define the delay for each instruction
INSTRUCTION_DELAYS = {
"addx": 2,
"noop": 1
}
# Read the input from the file
with open("sample.txt") as file:
instructions = [line.strip().split(" ") for line in file.readlines()]
# Initialize the CPU state
x = 0
cycles = 0
in_flight = []
# Execute the instructions
for instruction in instructions:
# Check if the instruction has the correct number of arguments
if len(instruction) == 2:
instruction_name, value = instruction
elif len(instruction) == 1:
instruction_name, value = instruction[0], None
else:
raise ValueError("Invalid instruction: {}".format(instruction))
# Update the in-flight instructions
i = 0
while i < len(in_flight):
if in_flight[i][1] > 0:
in_flight[i][1] -= 1
else:
x = INSTRUCTION_SET[in_flight[i][0]](x, in_flight[i][2])
in_flight.pop(i)
i += 1
# Check if the current instruction is valid
if instruction_name in INSTRUCTION_SET:
# Convert the value to an integer
if instruction_name == "addx":
value = int(value)
# Add the instruction to the in-flight instructions
in_flight.append([instruction_name, INSTRUCTION_DELAYS[instruction_name], value])
cycles += INSTRUCTION_DELAYS[instruction_name]
else:
raise ValueError("Invalid instruction: {}".format(instruction))
# Print the final state of the CPU
print("CPU state after execution:")
print("X = {}".format(x))
print("Cycles = {}".format(cycles))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment