1
0

Completed part 2 of day 14

This commit is contained in:
Rokas Puzonas 2020-12-14 20:58:01 +02:00
parent 70cd09ce6d
commit 5d9ede4659
2 changed files with 38 additions and 0 deletions

34
14/part2.py Normal file
View File

@ -0,0 +1,34 @@
def getInstructions(filename):
with open(filename, "r") as f:
return list(line.split(" = ") for line in f.read().split("\n"))
def decToBin(decimal):
binary = bin(decimal)[2:]
return "0"*(36 - len(binary)) + binary
def applyMask(address, mask):
return "".join(mask[i] if mask[i] in ["X", "1"] else address[i] for i in range(36))
def writeToMemory(memory, address: str, value):
numOfFloatingBits = address.count("X")
for i in range(2**numOfFloatingBits):
realAddress = address
for j in range(numOfFloatingBits):
realAddress = realAddress.replace("X", str((i & 2**j) >> j), 1)
memory[int(realAddress, 2)] = value
memory = {}
currentMask = "X" * 36
instructions = getInstructions("input.txt")
for instruction in instructions:
if instruction[0] == "mask":
currentMask = instruction[1]
else:
address = int(instruction[0][4:-1])
value = int(instruction[1])
maskedAddress = applyMask(decToBin(address), currentMask)
writeToMemory(memory, maskedAddress, value)
memorySum = sum(memory.values())
print(memorySum)

4
14/test2.txt Normal file
View File

@ -0,0 +1,4 @@
mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1