Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 10, 2022 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnyman/8c7f5ddb3c14c2c098d16731710fc2c2 to your computer and use it in GitHub Desktop.
Save gnyman/8c7f5ddb3c14c2c098d16731710fc2c2 to your computer and use it in GitHub Desktop.
# 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