summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--3.py19
1 files changed, 7 insertions, 12 deletions
diff --git a/3.py b/3.py
index 29cae70..b61cda1 100644
--- a/3.py
+++ b/3.py
@@ -1,34 +1,29 @@
-from typing import Generator
from collections.abc import Iterable
Bits = tuple[bool, ...]
Input = list[Bits]
-def column(rows: Iterable[Bits], n: int) -> Generator[bool, None, None]:
- for row in rows:
- yield row[n]
-
-def most_common(bits: Iterable[bool]) -> bool:
- count1: int = 0
+def most_common(nums: Iterable[Bits], n: int) -> bool:
+ count: int = 0
length: int = 0
- for b in bits:
- if b: count1 += 1
+ for num in nums:
+ if num[n]: count += 1
length += 1
- return count1 >= length - count1
+ return count >= length - count
def bits_to_int(bits: Bits) -> int:
return sum(b * 2 ** i for i, b in enumerate(reversed(bits)))
def part1(nums: Input) -> int:
nbits: int = len(nums[0])
- gamma: Bits = tuple(most_common(column(inp, i)) for i in range(nbits))
+ gamma: Bits = tuple(most_common(inp, i) for i in range(nbits))
epsilon: Bits = tuple(not bit for bit in gamma)
return bits_to_int(gamma) * bits_to_int(epsilon)
def part2_impl(nums: Input, complement: bool, bit: int = 0) -> Bits:
if len(nums) == 1:
return nums[0]
- target: bool = most_common(column(nums, bit)) ^ complement
+ target: bool = most_common(nums, bit) ^ complement
nums = list(filter(lambda n: n[bit] == target, nums))
return part2_impl(nums, complement, bit + 1)