{ "cells": [ { "cell_type": "code", "execution_count": 38, "id": "structural-optimization", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4147524\n" ] } ], "source": [ "def count(f):\n", " sums = {}\n", " lines = 0\n", " for l in f:\n", " for p, ch in enumerate(l.rstrip()):\n", " sums[p] = sums.get(p, 0) + int(ch)\n", " lines += 1\n", "\n", " return sums, lines\n", "\n", "def rates(f):\n", " sums, lines = count(f)\n", " digits = len(sums)\n", " gamma = 0\n", " epsilon = 0\n", " for p, s in sums.items():\n", " if s > lines/2:\n", " gamma |= 1<<(digits-p-1)\n", " else:\n", " epsilon |= 1<<(digits-p-1)\n", "\n", " return gamma, epsilon\n", "\n", "import import_ipynb\n", "import helper\n", "f = helper.open_file('2021_3.txt')\n", "\n", "gamma, epsilon = rates(f)\n", "\n", "print(gamma*epsilon)" ] }, { "cell_type": "code", "execution_count": 39, "id": "intellectual-railway", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3570354" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Node:\n", " def __init__(self):\n", " self.children = [None, None]\n", " \n", "def insert(node, bitstring):\n", " for bit in bitstring:\n", " bit = int(bit)\n", " if node.children[bit] is None:\n", " node.children[bit] = Node()\n", " node = node.children[bit]\n", " \n", "def count_leafs(node):\n", " if node is None:\n", " return 0\n", " \n", " c = 0\n", " \n", " leaf = True\n", " for n in node.children:\n", " if n:\n", " c += count_leafs(n)\n", " leaf = False\n", " \n", " if leaf:\n", " c += 1\n", " \n", " return c\n", "\n", "import import_ipynb\n", "import helper\n", "f = helper.open_file('2021_3.txt')\n", "\n", "root = Node()\n", "\n", "for l in f:\n", " insert(root, l.rstrip())\n", " \n", "def rating(node, bit_criteria):\n", " r = 0\n", " while node: \n", " c0 = count_leafs(node.children[0])\n", " c1 = count_leafs(node.children[1])\n", " \n", " if c0 == 0 and c1 == 0:\n", " break\n", " \n", " r <<= 1\n", " if not (c0 == 0 and c1 == 1) and \\\n", " (bit_criteria(c0, c1) or (c0 == 1 and c1 == 0)):\n", " \n", " node = node.children[0]\n", " else:\n", " node = node.children[1]\n", " r |= 1 \n", " \n", " return r\n", "\n", "import operator\n", "\n", "oxygen_generator_rate = rating(root, operator.gt)\n", "c02_scrubber_rate = rating(root, operator.le)\n", "\n", "oxygen_generator_rate * c02_scrubber_rate" ] }, { "cell_type": "code", "execution_count": null, "id": "wrapped-deputy", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.2" }, "title": "Binary Diagnostic" }, "nbformat": 4, "nbformat_minor": 5 }