diff options
author | Thomas Voss <thomasvoss@live.com> | 2021-10-29 23:02:39 +0200 |
---|---|---|
committer | Thomas Voss <thomasvoss@live.com> | 2021-10-29 23:02:39 +0200 |
commit | e7c9108b95e39d7ea5a29ae06d619c4727f11027 (patch) | |
tree | 237261eef3afd0720be77dbcbb9599fa66a24b67 /2020/14/puzzle-2.py |
Initial commit
Diffstat (limited to '2020/14/puzzle-2.py')
-rwxr-xr-x | 2020/14/puzzle-2.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/2020/14/puzzle-2.py b/2020/14/puzzle-2.py new file mode 100755 index 0000000..45fb6ad --- /dev/null +++ b/2020/14/puzzle-2.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + + +def bitmask(mask: str, num: int) -> tuple[int, ...]: + binary = bin(num)[2:] + binary = binary.zfill(36) + res = "" + + for i in range(len(binary)): + if mask[i] == "0": + res += binary[i] + else: + res += mask[i] + + n = res.count("X") + combos = tuple(bin(i)[2:].zfill(n) for i in range(2 << n - 1)) + + acc: list[str] = [] + for combo in combos: + temp = res + for i in range(n): + temp = temp.replace("X", combo[i], 1) + acc.append(temp) + + return tuple(int(x, 2) for x in acc) + + +def main() -> None: + with open("input", "r") as f: + lines = f.read().splitlines() + + mem: dict[str, int] = {} + mask = "" + for line in lines: + line = line.split(" ") + if line[0] == "mask": + mask = line[2] + else: + address = line[0][4:-1] + addresses = bitmask(mask, int(address)) + for a in addresses: + mem[a] = int(line[2]) + + print(sum(mem[val] for val in mem)) + + +if __name__ == "__main__": + main() |