{ "cells": [ { "cell_type": "markdown", "id": "d84ea0fd", "metadata": {}, "source": [ "# [Passcode Derivation](https://projecteuler.net/problem=79)\n", "\n", "Gotta read the data first." ] }, { "cell_type": "code", "execution_count": 1, "id": "56df44fb", "metadata": {}, "outputs": [], "source": [ "with open(\"txt/0079_keylog.txt\") as f:\n", " keylog = {tuple(int(c) for c in line.strip()) for line in f}" ] }, { "cell_type": "markdown", "id": "043f31a9", "metadata": {}, "source": [ "If we assume that no characters are repeated in the passcode, then each entry in the keylog gives a [partial ordering](https://en.wikipedia.org/wiki/Partially_ordered_set) of the characters in the passcode. In math jargon, we are then looking for a [linear extension](https://en.wikipedia.org/wiki/Linear_extension) of the partial ordering. This can be found with a [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting) algorithm.\n", "\n", "(If characters *are* repeated, we would instead have a [preordering](https://en.wikipedia.org/wiki/Preorder), and a topological sort wouldn't work. Fortunately for us, our assumption turns out to be correct.)\n", "\n", "Conveniently, and somewhat interestingly, Python has [graphlib](https://docs.python.org/3/library/graphlib.html) in its standard library, which (as of the time of writing) *only* implements topological sorting - but that's all we need for this problem, so I guess don't look a gift horse in the mouth." ] }, { "cell_type": "code", "execution_count": 2, "id": "4e742b06", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(7, 3, 1, 6, 2, 8, 9, 0)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from graphlib import TopologicalSorter\n", "\n", "ts = TopologicalSorter()\n", "for attempt in keylog:\n", " for (idx, d) in enumerate(attempt):\n", " predecessors = attempt[:idx]\n", " ts.add(d, *predecessors)\n", "\n", "tuple(ts.static_order())" ] }, { "cell_type": "markdown", "id": "242e35e6", "metadata": {}, "source": [ "#### Copyright (C) 2025 filifa\n", "\n", "This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)." ] } ], "metadata": { "kernelspec": { "display_name": "SageMath 9.5", "language": "sage", "name": "sagemath" }, "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.11.2" } }, "nbformat": 4, "nbformat_minor": 5 }