From 719bf0b6a263d0a9828f2d9f6d64c46611ba6c32 Mon Sep 17 00:00:00 2001 From: Lucidiot Date: Sat, 4 Dec 2021 00:08:17 +0100 Subject: [PATCH] 2021 day 3 --- 2021/3/day3.py | 31 +++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 2021/3/day3.py diff --git a/2021/3/day3.py b/2021/3/day3.py new file mode 100644 index 0000000..8dcb35e --- /dev/null +++ b/2021/3/day3.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +from collections import Counter +from functools import reduce +import fileinput + +def tonumber(num_list): + return reduce(lambda number, digit: (number << 1) + digit, num_list) + +matrix = sorted(map(lambda line: list(map(int, line.strip())), fileinput.input())) +zipped_matrix = list(zip(*matrix)) +gamma = tonumber([numbers.count(1) >= len(numbers) / 2 for numbers in zipped_matrix]) +epsilon = ~gamma & (2 ** len(zipped_matrix) - 1) +print(gamma * epsilon) + +def binary_search(criteria): + min, max = 0, len(matrix) + i = 0 + while (max - min) > 1 and i < len(zipped_matrix): + slice = zipped_matrix[i][min:max] + zeroes, ones = slice.count(0), slice.count(1) + if criteria(zeroes, ones): + min += zeroes + else: + max -= ones + i += 1 + assert (max - min) == 1 + return tonumber(matrix[min]) + +oxygen = binary_search(lambda zeroes, ones: ones >= zeroes) +co2 = binary_search(lambda zeroes, ones: ones < zeroes) +print(oxygen * co2) diff --git a/README.md b/README.md index 3bfe148..95fceb4 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ is acceptable; anything goes as long as I solve it myself! 15 16 17 18 19 20 21 1 ██ ██ ██ ██ ██ ██ 2 ██ ██ ██ ██ ██ ██ - 3 ██ ██ ██ ██ ██ + 3 ██ ██ ██ ██ ██ ██ 4 ██ ██ ██ ██ 5 ██ ██ ██ ██ 6 ██ ██ ██