add problem 79

This commit is contained in:
filifa 2025-05-25 21:50:29 -04:00
parent 49ede13ec6
commit 3d25f78422
2 changed files with 137 additions and 0 deletions

View File

@ -0,0 +1,87 @@
{
"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())"
]
}
],
"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
}

View File

@ -0,0 +1,50 @@
319
680
180
690
129
620
762
689
762
318
368
710
720
710
629
168
160
689
716
731
736
729
316
729
729
710
769
290
719
680
318
389
162
289
162
718
729
319
790
680
890
362
319
760
316
729
380
319
728
716