From 1f2d646838eb03b08e4efd152529f658003bce2d Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 14 Dec 2020 09:53:24 +0100 Subject: [PATCH] 2020: d14: ex1: add solution --- 2020/d14/ex1/ex1.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100755 2020/d14/ex1/ex1.py diff --git a/2020/d14/ex1/ex1.py b/2020/d14/ex1/ex1.py new file mode 100755 index 0000000..a58c8f0 --- /dev/null +++ b/2020/d14/ex1/ex1.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +import re +import sys +from dataclasses import dataclass +from typing import Dict, List + + +@dataclass +class Mask: + ones: int + zeros: int + + +Memory = Dict[int, int] + + +def solve(raw: List[str]) -> int: + mask = Mask( + 0, + (2 << 36) - 1, + ) + mem_pattern = re.compile("mem\\[([0-9]+)\\] = ([0-9]+)") + mask_pattern = re.compile("mask = ([01X]+)") + mem: Memory = {} + for instr in raw: + if (mem_match := mem_pattern.match(instr)) is not None: + addr, val = int(mem_match.group(1)), int(mem_match.group(2)) + val |= mask.ones + val &= mask.zeros + mem[addr] = val + elif (mask_match := mask_pattern.match(instr)) is not None: + ones = int(mask_match.group(1).replace("X", "0"), 2) + zeros = int(mask_match.group(1).replace("X", "1"), 2) + mask = Mask(ones, zeros) + return sum(mem.values()) + + +def main() -> None: + input = [line.strip() for line in sys.stdin.readlines()] + print(solve(input)) + + +if __name__ == "__main__": + main()