diff --git a/14/part2.py b/14/part2.py new file mode 100644 index 0000000..0b05357 --- /dev/null +++ b/14/part2.py @@ -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) \ No newline at end of file diff --git a/14/test2.txt b/14/test2.txt new file mode 100644 index 0000000..b4b4e06 --- /dev/null +++ b/14/test2.txt @@ -0,0 +1,4 @@ +mask = 000000000000000000000000000000X1001X +mem[42] = 100 +mask = 00000000000000000000000000000000X0XX +mem[26] = 1 \ No newline at end of file