From 32660da53ecbf835a4764bbb522576fa6c9442a2 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Fri, 3 Dec 2021 07:13:45 +0100 Subject: [PATCH] 2021 day3/python: add solution --- 2021/day3/day3.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100755 2021/day3/day3.py diff --git a/2021/day3/day3.py b/2021/day3/day3.py new file mode 100755 index 0000000..2921012 --- /dev/null +++ b/2021/day3/day3.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import sys +from collections import Counter + +def most_common(ns, pos): + c = Counter(n[pos] for n in ns) + num_zeros = c['0'] + num_ones = c['1'] + if num_ones >= num_zeros: + return '1' + else: + return '0' + +def least_common(ns, pos): + return '0' if most_common(ns, pos) == '1' else '1' + +def find_criteria(ns, criteria): + ns = ns + i = 0 + while len(ns) > 1: + x = criteria(ns, i) + ns = [n for n in ns if n[i] == x] + i += 1 + return ns[0] + +if __name__ == '__main__': + lines = [line.strip() for line in sys.stdin.readlines()] + + line_len = len(lines[0]) + gamma = ''.join(most_common(lines, n) for n in range(line_len)) + epsilon = ''.join(least_common(lines, n) for n in range(line_len)) + print(int(gamma, 2) * int(epsilon, 2)) + + oxygen_rating = find_criteria(lines, most_common) + co2_rating = find_criteria(lines, least_common) + + print(int(oxygen_rating, 2) * int(co2_rating, 2))