summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTomasz Kramkowski <tk@the-tk.com>2021-12-03 15:13:20 +0000
committerTomasz Kramkowski <tk@the-tk.com>2021-12-03 15:13:20 +0000
commitccad94cf8d9adb60bd9ae1996c83935fc6205e9c (patch)
treea2e359ad43eafe93b730767f028c053f5cb6dc0c
parent19710b72fd58989e25dec27884c99ac5b65272ff (diff)
downloadaoc2021-ccad94cf8d9adb60bd9ae1996c83935fc6205e9c.tar.gz
aoc2021-ccad94cf8d9adb60bd9ae1996c83935fc6205e9c.tar.xz
aoc2021-ccad94cf8d9adb60bd9ae1996c83935fc6205e9c.zip
day 3: remove superfluous column func
-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)