\n",
"\n",
"# Advent of Code 2024\n",
"\n",
"I enjoy doing the [**Advent of Code**](https://adventofcode.com/) (AoC) programming puzzles, so here we go for 2024! Our old friend [@GaryJGrady](https://x.com/garyjgrady) is here to provide illustrations:\n",
"\n",
"\n",
"\n",
"I traditionally start by loading up my [**AdventUtils.ipynb**](AdventUtils.ipynb) notebook (same as last time except for the `current_year`):"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "ed82ed5b-a42d-468b-8f6e-288d3c2de20b",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Matplotlib is building the font cache; this may take a moment.\n"
]
}
],
"source": [
"%run AdventUtils.ipynb\n",
"current_year = 2024"
]
},
{
"cell_type": "markdown",
"id": "dfecffd7-6955-45ba-9dc2-1ec805baba85",
"metadata": {},
"source": [
"Each day's solution consists of three parts, making use of my `parse` and `answer` utilities:\n",
"- **Reading the day's input**. E.g. `pairs = parse(1, ints)`. \n",
"- **Solving Part One**. Find the solution and record it with, e.g., `answer(1.1, 4, lambda: 2 + 2)`.\n",
"- **Solving Part Two**. Find the solution and record it with, e.g., `answer(1.2, 9, lambda: 3 * 3)`.\n",
"\n",
"The function `parse` assumes that the input is a sequence of records (default one per line), each of which should be parsed in some way (default just left as a string, but the argument `ints` says to treat each record as a tuple of integers). The function `answer` records the correct answer (for regression testing), and records the run time (that's why a `lambda:` is used).\n",
"\n",
"To fully understand each day's puzzle, and to follow along the drama involving Santa, the elves, the Chief Historian, and all the rest, you need to read the descriptions on the [**AoC**](https://adventofcode.com/) site, as linked in the header for each of my day's solutions, e.g. [**Day 1**](https://adventofcode.com/2023/day/1) below. Since you can't read Part 2 until you solve Part 1, I'll partially describe Part 2 in this notebook. But I can't copy the content of AoC here, nor show my input files; you need to go to the site for that.\n",
"\n",
"\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"id": "4c6120a1-3129-44ff-935c-30c1d81ae028",
"metadata": {},
"source": [
"# [Day 1](https://adventofcode.com/2024/day/1) Historian Hysteria\n",
"\n",
"According to the narrative, North Pole Historians created two lists of **location IDs**. We can parse them as a sequence of pairs of integers, and then use the transpose function, `T` to get two lists of ID numbers:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "22e5d621-a152-4712-866f-f8b962b5dd14",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 1000 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"38665 13337\n",
"84587 21418\n",
"93374 50722\n",
"68298 57474\n",
"54771 18244\n",
"49242 83955\n",
"66490 44116\n",
"65908 51323\n",
"...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 1000 tuples:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(38665, 13337)\n",
"(84587, 21418)\n",
"(93374, 50722)\n",
"(68298, 57474)\n",
"(54771, 18244)\n",
"(49242, 83955)\n",
"(66490, 44116)\n",
"(65908, 51323)\n",
"...\n"
]
}
],
"source": [
"left, right = location_ids = T(parse(1, ints))"
]
},
{
"cell_type": "markdown",
"id": "63cf2940-e251-49e4-8bc9-f1bcd599f8f4",
"metadata": {},
"source": [
"\n",
"\n",
"### Part 1: What is the total distance between your lists?\n",
"\n",
"The **distance** between two numbers is the absolute value of their difference, and the **total distance** between two lists is the sum of the distances between respective pairs, where \"respective\" means to sort each list and then take the distance between the first element of each list, plus the distance between the second element of each list, and so on. (I use the transpose utility function, `T`, to turn the input sequence of 1000 pairs into two lists, each of 1000 integers.)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "2dbfa3ae-3d47-4711-8821-7d1b2564bdc8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 1.1: .0002 seconds, answer 1830467 ok"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def total_distance(left: Ints, right: Ints) -> int:\n",
" \"\"\"Total distance between respective list elements, after sorting.\"\"\"\n",
" return sum(abs(a - b) for a, b in zip(sorted(left), sorted(right)))\n",
"\n",
"answer(1.1, 1830467, lambda:\n",
" total_distance(left, right))"
]
},
{
"cell_type": "markdown",
"id": "88e26234-f1d2-4a62-86b0-2ad9251215eb",
"metadata": {},
"source": [
"### Part 2: What is their similarity score?\n",
"\n",
"The **similarity score** is the sum of each element of the left list times the number of times that value appears in the right list."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "e33f9705-3b51-4314-a302-6b3445290713",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 1.2: .0001 seconds, answer 26674158 ok"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def similarity_score(left: Ints, right: Ints) -> int:\n",
" \"\"\"The sum of each x in `left` times the number of times x appears in `right`.\"\"\"\n",
" counts = Counter(right)\n",
" return sum(x * counts[x] for x in left)\n",
"\n",
"answer(1.2, 26674158, lambda:\n",
" similarity_score(left, right))"
]
},
{
"cell_type": "markdown",
"id": "b9fa4fe0-4194-47d7-b815-b571af98caee",
"metadata": {},
"source": [
"# [Day 2](https://adventofcode.com/2024/day/2): Red-Nosed Reports\n",
"\n",
"Today's input is a sequence of **reports**, each of which is a sequence of integers:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "10e1ab83-a6ec-4143-ad9a-eaae220adcde",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 1000 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"74 76 78 79 76\n",
"38 40 43 44 44\n",
"1 2 4 6 8 9 13\n",
"65 68 70 72 75 76 81\n",
"89 91 92 95 93 94\n",
"15 17 16 18 19 17\n",
"46 47 45 48 51 52 52\n",
"77 78 79 82 79 83\n",
"...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 1000 tuples:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(74, 76, 78, 79, 76)\n",
"(38, 40, 43, 44, 44)\n",
"(1, 2, 4, 6, 8, 9, 13)\n",
"(65, 68, 70, 72, 75, 76, 81)\n",
"(89, 91, 92, 95, 93, 94)\n",
"(15, 17, 16, 18, 19, 17)\n",
"(46, 47, 45, 48, 51, 52, 52)\n",
"(77, 78, 79, 82, 79, 83)\n",
"...\n"
]
}
],
"source": [
"reports = parse(2, ints)"
]
},
{
"cell_type": "markdown",
"id": "5dfd72c2-06c6-4c71-ae37-0c2c84074091",
"metadata": {},
"source": [
"### Part 1: How many reports are safe?\n",
"\n",
"A report is **safe** if it is monotonically strictly increasing or strictly decreasing, and if no difference between adjacent numbers is greater than 3 in absolute value."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "368cbe1c-b6b6-4a82-bef9-599ee9725899",
"metadata": {},
"outputs": [],
"source": [
"def safe(report: Ints) -> bool:\n",
" \"\"\"A report is safe if all differences are either in {1, 2, 3} or in {-1, -2, -3}.\"\"\"\n",
" deltas = diffs(report)\n",
" return deltas.issubset({1, 2, 3}) or deltas.issubset({-1, -2, -3})\n",
" \n",
"def diffs(report: Ints) -> set:\n",
" \"\"\"The set of differences between adjacent numbers in the report.\"\"\"\n",
" return {report[i] - report[i - 1] for i in range(1, len(report))}\n",
"\n",
"assert diffs((7, 6, 4, 2, 1)) == {-1, -2}\n",
"assert safe((7, 6, 4, 2, 1)) == True"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "e662bf10-4d6a-40f1-95ce-dfc39f5b3fc2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 2.1: .0004 seconds, answer 257 ok"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(2.1, 257, lambda:\n",
" quantify(reports, safe))"
]
},
{
"cell_type": "markdown",
"id": "ee48bf63-8a67-407b-9a73-df097811eabc",
"metadata": {},
"source": [
"### Part 2: How many reports are safe using the Problem Dampener?\n",
"\n",
"The **problem dampener** says that a report is safe if you can drop one element and get a safe report."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "67ba1d53-95b7-4811-b225-2ff15d6bdc5c",
"metadata": {},
"outputs": [],
"source": [
"def safe_with_dampener(report: Ints) -> bool:\n",
" \"\"\"Is there any way to drop one element of `report` to get a safe report?\"\"\"\n",
" return any(map(safe, drop_one(report)))\n",
"\n",
"def drop_one(report) -> Iterable:\n",
" \"\"\"All ways of dropping one element of the input report.\"\"\"\n",
" return (report[:i] + report[i + 1:] for i in range(len(report)))\n",
"\n",
"assert set(drop_one('1234')) == {'234', '134', '124', '123'}"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "d1b9ffb5-af7a-465f-a063-c31df2d0605c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 2.2: .0022 seconds, answer 328 ok"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(2.2, 328, lambda:\n",
" quantify(reports, safe_with_dampener))"
]
},
{
"cell_type": "markdown",
"id": "54d6a0c2-a8ed-404d-abc0-72aa28a49f5d",
"metadata": {},
"source": [
"# [Day 3](https://adventofcode.com/2024/day/3): Mull It Over\n",
"\n",
"Today's input is a computer program with some corrupted characters. The program has multiple lines, but lines don't matter, so I will concatenate them into one big string:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "78080200-0f9f-4492-9bee-c936737ee96f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 6 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"where(536,162)~'what()what()how(220,399){ mul(5,253);mul(757,101)$where()@why()who()&when()from( ...\n",
"}?~who()select()-mul(316,505)&%*how()mul(363,589)>?%-:)where()~{{mul(38,452)select()%>[{]%>%mul( ...\n",
"?>where(911,272)'mul(894,309)~+%@#}@#why()mul(330,296)what()mul(707,884)mul;&}<{>where()$why()]m ...\n",
"> (when()[where()/#!/usr/bin/perl,@;mul(794,217)select():'])select()mul(801,192)why()&]why()/:]* ...\n",
",+who():mul(327,845)/ >@[>@}}mul(86,371)!~&&~how(79,334)mul(637,103)why()mul(358,845)-#~?why(243 ...\n",
"where()#{*,!?:$mul(204,279)what()!{ what()mul(117,94)!select()>:mul(665,432)#don't()!!\n",
"\n",
"\n",
"### Part 1: What do you get if you add up all of the results of the multiplications?\n",
"\n",
"For Part 1, just look for instructions of the form \"mul(*digits*,*digits*)\", using a regular expression and `re.findall`. Perform each of these multiplications and add them up, and ignore all other characters/instructions:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "bf6366b1-6952-47d8-8b3c-09f8d05ec093",
"metadata": {},
"outputs": [],
"source": [
"def execute(program: str) -> int:\n",
" \"\"\"The sum of the results of the multiply instructions.\"\"\"\n",
" return sum(prod(ints(m)) for m in multiplications(program))\n",
"\n",
"def multiplications(program: str) -> List[str]:\n",
" \"\"\"A list of all the multiplication instructions in the program.\"\"\"\n",
" return re.findall(r'mul\\(\\d+,\\d+\\)', program)\n",
"\n",
"test = \"xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))\"\n",
"assert execute(test) == 161\n",
"assert multiplications(test) == ['mul(2,4)', 'mul(5,5)', 'mul(11,8)', 'mul(8,5)']"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "2032c903-5f23-4c16-ba68-410b6c1750e1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 3.1: .0006 seconds, answer 156388521 ok"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(3.1, 156388521, lambda: \n",
" execute(program))"
]
},
{
"cell_type": "markdown",
"id": "622d7010-145e-422a-a592-d4b446afcc0f",
"metadata": {},
"source": [
"### Part 2: What do you get if you add up all of the results of just the enabled multiplications?\n",
"\n",
"For Part 2, the instruction \"don't()\" says to disable (ignore) following multiply instructions until a \"do()\" instruction enables them again. I will define the function `enabled`, which returns the part of the program that is enabled, by susbstituting a space for the \"don't()...do()\" sequence."
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "4525d01a-bac0-41c2-92b8-baf0fd395e88",
"metadata": {},
"outputs": [],
"source": [
"def enabled(program: str) -> str:\n",
" \"\"\"Just the part of the program that is enabled; remove \"don't()...do()\" text.\"\"\"\n",
" return re.sub(r\"don't\\(\\).*?(do\\(\\)|$)\", \" \", program)\n",
"\n",
"test2 = \"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))\"\n",
"assert enabled(test2) == 'xmul(2,4)&mul[3,7]!^ ?mul(8,5))'\n",
"assert execute(enabled(test2)) == 2 * 4 + 8 * 5 == 48\n",
"assert multiplications(enabled(test2)) == ['mul(2,4)', 'mul(8,5)']"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "ce40f258-ca76-48c3-9965-27a6979a4243",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 3.2: .0004 seconds, answer 75920122 ok"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(3.2, 75920122, lambda:\n",
" execute(enabled(program)))"
]
},
{
"cell_type": "markdown",
"id": "e1448343-6488-45ad-b03d-d7928feb75cd",
"metadata": {},
"source": [
"# [Day 4](https://adventofcode.com/2024/day/4): Ceres Search\n",
"\n",
"Today's puzzle is a 2D word-search puzzle:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "a0d903b9-018e-4861-9314-cafed59055fd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 140 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"MASAMXMSSXXMAMXXMXMASXMASXMMSMSMMMAXMASASMMSSMSXAXMASMMSMMMSSMSASMSSSSMSMSMXXMXMAXAMXMSMSSXSAMXM ...\n",
"MASMMXMASAXASMSMMMSAMXSMSAMXAAAAAXAMXASXAMAAAAMMSMMMMMASXAAAAMMAMAMMASAAAAXMXMSSSSSSMMSAMAXAXXSM ...\n",
"MMXAXMMMSXMAMAAXAAXAAAXXSMMSMSMSMXAXMXSMMMMSSMXAMXAAXMAMMMMSSMMAMAMMAMMMMMXSAAXAAMMAXXSAMXMSMAXM ...\n",
"SXSAMASASMSXMSMSMSSMMMMMMXAMXMMXMASMMMMAXXAAAMMMSSSSSMASXXAAXASMSXXMXSXSXSASMSMMSMSAMMMAMXAAMASX ...\n",
"AAAXXXMASASXMXMAXXMMASAASMXSASASXAAAAMSSMMMSXMAAMMMMMXAXMMMMSAMXAMASAMXSAMASXXAXAAMAMXSAMXSXSMMA ...\n",
"MSMMXXMMMAMAMMMMMMXSAXXAMMMMXSAXMMXXAMXAAMMXMASXMAAASMMXAAMXAXAMMMAMAMAMAMXMASXMMXMAAXMAXMAMXMSA ...\n",
"MXAXAMXXMMMMSAMAASMMMSMMASASAMAMAXMSXMSMMXAMXAXMMSSXSASXSSSMAMSMXMXSAMSSSMAMXMXAMAXXMMSAXAXMMXMA ...\n",
"ASXMMXSAMXAASXXMXSAAAXASAMMMASMSSSMAAMMXMMSSMASAMAMMMAMMAXMAXMASXMAXMSAAASASAMXSSMXSAAXSSMXAAXXA ...\n",
"...\n"
]
}
],
"source": [
"xmas_grid = Grid(parse(4))"
]
},
{
"cell_type": "markdown",
"id": "16d56872-be2c-4e9d-8821-a0fe9f66970b",
"metadata": {},
"source": [
"### Part 1: How many times does XMAS appear?\n",
"\n",
"We just have to find how many times the word \"XMAS\" appears in the grid, horizontally, vertically, or diagonally, forwards or backwards. The variable `directions8` contains those eight directions (as (delta-x, delta-y) pairs). So examine each square of the grid and if it contains \"X\", see in how many of the directions it spells \"XMAS\". (Note that locations in the grid are denoted by `(x, y)` coordinates, as are directions (e.g., `(1, 0)` is the `East` direction. The functions `add` and `mul` do addition and scalar multiplication on these vectors.)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "72d48abb-7a82-452f-b91d-838b3836a90f",
"metadata": {},
"outputs": [],
"source": [
"def word_search(grid: Grid, word='XMAS') -> int:\n",
" \"\"\"How many times does the given word appear in the grid?\"\"\"\n",
" return quantify(grid_can_spell(grid, start, dir, word) \n",
" for start in grid \n",
" if grid[start] == word[0]\n",
" for dir in directions8)\n",
"\n",
"def grid_can_spell(grid, start, dir, word):\n",
" \"\"\"Does `word` appear in grid starting at `start` and going in direction `dir`?\"\"\"\n",
" return all(grid[add2(start, mul(dir, i))] == word[i] for i in range(len(word)))"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "6175362b-d8b4-45d1-b70c-d8575a0fe188",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 4.1: .0338 seconds, answer 2401 ok"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(4.1, 2401, lambda:\n",
" word_search(xmas_grid))"
]
},
{
"cell_type": "markdown",
"id": "eabe90c4-b668-4d9e-a345-b09f4b8ee42b",
"metadata": {},
"source": [
"### Part 1: How many times does an X-MAS appear?\n",
"\n",
"Upon further review, the goal is not to find \"XMAS\" byt rather X-\"MAS\"; that is, two \"MAS\" words in an X pattern. The pattern can be any of these four:\n",
"\n",
" M.S S.M M.M S.S\n",
" .A. .A. .A. .A.\n",
" M.S S.M S.S M.M\n",
"\n",
"I decided to find these by looking for each instance of the middle letter (\"A\") in the grid, and then, for each pair of diagonal directions, see if the target word (\"MAS\") can be spelled in both directions:"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "ff7540fd-b5cb-4d02-810d-5c77da2bd9f4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 4.2: .0259 seconds, answer 1822 ok"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"diagonal_pairs = ([SE, NE], [SW, NW], [SE, SW], [NE, NW])\n",
"\n",
"def x_search(grid: Grid, word='MAS') -> int:\n",
" \"\"\"How many times does an X-MAS appear in the grid?\"\"\"\n",
" return quantify((grid_can_spell(grid, sub(mid_pos, dir1), dir1, word) and\n",
" grid_can_spell(grid, sub(mid_pos, dir2), dir2, word))\n",
" for mid_pos in grid if grid[mid_pos] == word[1]\n",
" for dir1, dir2 in diagonal_pairs)\n",
"\n",
"answer(4.2, 1822, lambda:\n",
" x_search(xmas_grid))"
]
},
{
"cell_type": "markdown",
"id": "0249ce80-e649-44b3-8c02-613fc7652110",
"metadata": {},
"source": [
"# [Day 5](https://adventofcode.com/2024/day/5): Print Queue\n",
"\n",
"Today's puzzle involves a **sleigh launch safety manual** that needs to be updated. The day's input is in two parts: the first a set of **rules** such as \"47|53\", which means that page 47 must be printed before page 53; and the second a list of **updates** of the form \"75,47,61,53,29\", meaning that those pages are to be printed in that order.\n",
"\n",
"\n",
"\n",
"I mostly like my `parse` function, but I admit it is not ideal when an input file has two parts like this. I'll parse the two parts into paragraphs, and then call `parse` again on each paragraph:"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "b77a5a1f-a43b-4ce8-a60c-94d69a595505",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 1366 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"48|39\n",
"39|84\n",
"39|23\n",
"95|51\n",
"95|76\n",
"95|61\n",
"14|52\n",
"14|49\n",
"...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 2 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"48|39\n",
"39|84\n",
"39|23\n",
"95|51\n",
"95|76\n",
"95|61\n",
"14|52\n",
"14|49\n",
"14|39\n",
"14|53\n",
"85|19\n",
"85|25\n",
"85|61\n",
"85|35\n",
"85|58\n",
"74|86\n",
" ...\n",
"61,58,51,32,12,14,71\n",
"58,25,54,14,12,94,32,76,39\n",
"35,53,26,77,14,71,25,76,85,55,51,49,95\n",
"32,91,76, ...\n"
]
}
],
"source": [
"manual = parse(5, sections=paragraphs)\n",
"rules = set(parse(manual[0], ints))\n",
"updates = parse(manual[1], ints)\n",
"\n",
"assert (48, 39) in rules # `rules` is a set of (earlier, later) page number pairs\n",
"assert updates[0] == (61,58,51,32,12,14,71) # `updates` is a sequence of page number tuples"
]
},
{
"cell_type": "markdown",
"id": "d6b6d374-cbe9-4b84-a1dd-d9df927c7182",
"metadata": {},
"source": [
"### Part 1: What do you get if you add up the middle page number from the correctly-ordered updates?\n",
"\n",
"I'll define `is_correct` to determine if an update is in the correct order, and `sum_of_correct_middles` to add up the middle numbers of the correct updates:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "78898d37-46ff-4367-9d89-b2a107a90aa1",
"metadata": {},
"outputs": [],
"source": [
"def sum_of_correct_middles(rules: Set[Ints], updates: Tuple[Ints]) -> int:\n",
" \"\"\"The sum of the middle elements of each update that is correct.\"\"\"\n",
" return sum(middle(update) for update in updates if is_correct(update, rules))\n",
"\n",
"def is_correct(update: Ints, rules: Set[Ints]) -> bool:\n",
" \"\"\"An update is correct if no pair of pages violates a rule in the rules set.\"\"\"\n",
" return not any((second, first) in rules for (first, second) in combinations(update, 2))\n",
"\n",
"def middle(sequence) -> object: return sequence[len(sequence) // 2]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "b1c87359-1d2d-4a90-8305-9d152ce5d547",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 5.1: .0006 seconds, answer 5762 ok"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(5.1, 5762, lambda:\n",
" sum_of_correct_middles(rules, updates))"
]
},
{
"cell_type": "markdown",
"id": "80da4fd9-b11e-4dbb-8d22-2071d1a89827",
"metadata": {},
"source": [
"### Part 2: What do you get if you add up the middle page numbers after correctly re-ordering the incorrect updates?\n",
"\n",
"In Part 2 we have to find the incorrect updates, re-order them into a correct order, and again sum the middle page numbers.\n",
"Since I have already defined `is_correct`, i could just generate all permutations of each update and find one that `is_correct`. That would work great if the longest update is only 5 pages long, as it is in the example input. But what is the longest update in the actual input?"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "d8718c3e-0b3b-49ce-8cca-abd82aa788d7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"23"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(map(len, updates))"
]
},
{
"cell_type": "markdown",
"id": "4449200f-dd19-48f1-94b2-7304daa9fa00",
"metadata": {},
"source": [
"That's not great. With 23 numbers there are 23! permutations, which is over 25 sextillion. So instead, here's my strategy:\n",
"\n",
"- `sum_of_corrected_middles` will find the incorrect rules, perform a correction on each, and sum the middle numbers.\n",
"- `correction` will sort an update, obeying the rules. It used to be that Python's `sort` method allowed a `cmp` keyword to compare two values; there is vestigial support for this with the `functools.cmp_to_key` function. I will **sort** each update so that page *m* comes before page *n* if (*m*, *n*) is in the rules.\n",
"- Sorting will be a sextillion times faster than enumerating permutations."
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "7222dc1c-067f-4bb5-84e1-3c2fc72fd53a",
"metadata": {},
"outputs": [],
"source": [
"def sum_of_corrected_middles(rules, updates) -> int:\n",
" \"\"\"The sum of the middle elements of each update that is correct.\"\"\"\n",
" incorrect = [update for update in updates if not is_correct(update, rules)]\n",
" corrected = [correction(update, rules) for update in incorrect]\n",
" return sum(map(middle, corrected))\n",
" \n",
"def correction(update: Ints, rules) -> Ints:\n",
" \"\"\"Reorder the update to make it correct.\"\"\"\n",
" def rule_lookup(m, n): return +1 if (m, n) in rules else -1 \n",
" return sorted(update, key=functools.cmp_to_key(rule_lookup))"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "dc1fbda9-2cfd-442a-afef-12c9b0d2b17f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 5.2: .0008 seconds, answer 4130 ok"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(5.2, 4130, lambda:\n",
" sum_of_corrected_middles(rules, updates))"
]
},
{
"cell_type": "markdown",
"id": "53b1ccbc-01ae-43d0-a75f-3f9389fdd3c9",
"metadata": {},
"source": [
"I have to say, I'm pleased that this day I got both parts right the first time (and in fact, the same for the previous days). I was worried I might have my `+1` and `-1` backwards in `cmp_to_key`, but so far, everything has gone very smoothly. (However, even if I started solving right at midnight (which I don't), I don't think I would show up on the leaderboard; I have been good at getting a correct answer the first time, but I'm still way slower than the skilled contest programmers."
]
},
{
"cell_type": "markdown",
"id": "38258423-e3b8-4bae-8aeb-28f07f0d5a35",
"metadata": {},
"source": [
"# [Day 6](https://adventofcode.com/2024/day/6): Guard Gallivant\n",
"\n",
"Today's input is a 2D map of the manufacturing lab, with \"`.`\" indicating an empty space, \"`#`\" indicating an obstruction, and \"`^`\" indicating the position of the security guard."
]
},
{
"cell_type": "code",
"execution_count": 46,
"id": "6ec71cf8-c43d-457e-8e14-0e9eb99b956a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 130 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"........#........................................#......#........#.............................. ...\n",
"....................................#......#.....#............#.............#..........#........ ...\n",
"......................#.......................................................#................. ...\n",
".......#..#..#....#...#...#....#..............#......#.......#...#................#.......#..... ...\n",
"......................#....##...#.......#....#.......................................#.......... ...\n",
"...#............................#........................................#...................... ...\n",
"....................#............#...............#......#.........#...........#................. ...\n",
"............................#......#...#................#.............#......................... ...\n",
"...\n"
]
}
],
"source": [
"lab_grid = Grid(parse(6))"
]
},
{
"cell_type": "markdown",
"id": "4ba233f4-90aa-4249-9569-10288c34940d",
"metadata": {},
"source": [
"### Part 1: How many distinct positions will the guard visit before leaving the mapped area?\n",
"\n",
"The guard follows this protocol: If there is something directly in front of you, turn right 90 degrees.\n",
"Otherwise, take a step forward.\n",
"\n",
"I'll define `follow_path` to output a list of all the positions the guard occupies. I realize the puzzle is only asking for a count of the positions, but the path might be useful for Part 2, or for debugging, so I'll return it. I worried that it is also possible for a path to become a loop, but the problem statement says that can't happen, so I won't test for it."
]
},
{
"cell_type": "code",
"execution_count": 48,
"id": "aecb67fd-2c8a-40a8-9e67-e495b7cb8043",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 6.1: .0014 seconds, answer 5329 ok"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def follow_path(grid: Grid, guard='^', facing=North) -> List[Point]:\n",
" \"\"\"A list of all points in the path followed by the guard.\"\"\"\n",
" path = grid.findall(guard) # A one-element list of positions, e.g. [(3, 4)]\n",
" while True:\n",
" ahead = add2(path[-1], facing)\n",
" if ahead not in grid:\n",
" return path\n",
" elif grid[ahead] == '#':\n",
" facing = make_turn(facing, 'R')\n",
" else:\n",
" path.append(ahead)\n",
"\n",
"answer(6.1, 5329, lambda: len(set(follow_path(lab_grid))))"
]
},
{
"cell_type": "markdown",
"id": "eaf72ac3-ade0-4479-a090-1d0f292ecc27",
"metadata": {},
"source": [
"I initially had a **bug**; I asked for the length of the path, not the length of the **set** of positions in the path.\n",
" \n",
"### Part 2: How many different positions could you choose for an obstruction to put the guard in a loop?\n",
"\n",
"The historians would like to place a single obstacle so that the guard *will* get stuck in a loop, rather than exiting the grid. They want to know all possible positions for the obstacle. What do we know about such positions?\n",
"- An obstacle position must be somewhere on the guard's path, otherwise it would have no effect.\n",
"- The instructions say it can't be the guard's initial position.\n",
"- A loop is when the guard's path returns to the same position with the same facing. This suggests that my Part 1 solution was not completely helpful: to find duplicate positions in the path I would need a set of position/facing pairs, not just positions.\n",
"- I can make slightly less work by only storing the corners of the path: the places where the guard turns. \n",
"- The simplest approach for finding obstacle positions is to temporarily place an obstacle on each point on the path, one at a time, and see if it leads to a loop.\n",
"- There are 5,329 positions on the path, so the runtime should be about 5,000 times longer than Part 1; on the order of 10 seconds or so. I'll try it, and if it seems too slow, I'll try to think of something better."
]
},
{
"cell_type": "code",
"execution_count": 50,
"id": "1718fecb-aa3e-4162-9948-1c06d4ec5e8a",
"metadata": {},
"outputs": [],
"source": [
"def is_loopy_path(grid: Grid, guard_pos, facing=North) -> bool:\n",
" \"\"\"Does the path followed by the guard form a loop?\"\"\"\n",
" path = {(guard_pos, facing)}\n",
" while True:\n",
" ahead = add2(guard_pos, facing)\n",
" if ahead not in grid:\n",
" return False # Walked off the grid; not a loop\n",
" elif grid[ahead] == '#':\n",
" facing = make_turn(facing, 'R')\n",
" if (guard_pos, facing) in path:\n",
" return True\n",
" path.add((guard_pos, facing))\n",
" else:\n",
" guard_pos = ahead\n",
" \n",
"def find_loopy_obstacles(grid: Grid) -> Iterable[Point]:\n",
" \"\"\"All positions in which placing an obstacle would result in a loopy path for the guard.\"\"\"\n",
" guard_pos = the(grid.findall('^'))\n",
" for pos in set(follow_path(grid)) - {guard_pos}:\n",
" grid[pos] = '#' # Temporarily place an obstacle \n",
" if is_loopy_path(grid, guard_pos):\n",
" yield pos\n",
" grid[pos] = '.' # Remove the obstacle"
]
},
{
"cell_type": "code",
"execution_count": 51,
"id": "36196264-eb33-4fc0-95d5-06c985105ebf",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 6.2: 1.9151 seconds, answer 2162 ok"
]
},
"execution_count": 51,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(6.2, 2162, lambda:\n",
" quantify(find_loopy_obstacles(lab_grid)))"
]
},
{
"cell_type": "markdown",
"id": "9f3ee6f9-7ec7-4248-ae52-1804fdc81dbd",
"metadata": {},
"source": [
"That was a bit slow, but I'll take it. I had a **bug** when I was keeping a set of previously visited states to detect loops; the bug went away when I switched to the step-count limit."
]
},
{
"cell_type": "markdown",
"id": "9eae8cf2-8c97-418e-b00b-3ea0187da526",
"metadata": {},
"source": [
"# [Day 7](https://adventofcode.com/2024/day/7): Bridge Repair\n",
"\n",
"The narrative for today involves fixing a bridge, and each line of our input represents a calibration equation for the bridge. Unfortunately, some nearby elephants stole all the operators from the equations, so all that is left are the integers:"
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "c1c6cee8-122c-43c9-8c7d-ed8980ea2b76",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 850 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"202998336: 686 9 7 62 2 673\n",
"19275222: 361 3 7 170 65 5 223\n",
"23101: 7 694 916 4 6\n",
"2042426: 6 34 2 423 3\n",
"40369523: 8 880 91 45 23\n",
"46629044796: 990 471 4 4 796\n",
"1839056: 3 42 2 4 3 258 703 4 8\n",
"26205: 2 9 5 9 9 4 3 7 44 5 8 7\n",
"...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 850 tuples:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(202998336, 686, 9, 7, 62, 2, 673)\n",
"(19275222, 361, 3, 7, 170, 65, 5, 223)\n",
"(23101, 7, 694, 916, 4, 6)\n",
"(2042426, 6, 34, 2, 423, 3)\n",
"(40369523, 8, 880, 91, 45, 23)\n",
"(46629044796, 990, 471, 4, 4, 796)\n",
"(1839056, 3, 42, 2, 4, 3, 258, 703, 4, 8)\n",
"(26205, 2, 9, 5, 9, 9, 4, 3, 7, 44, 5, 8, 7)\n",
"...\n"
]
}
],
"source": [
"equations = parse(7, ints)"
]
},
{
"cell_type": "markdown",
"id": "be207b67-a970-4f79-85be-5d62b7cedd9f",
"metadata": {},
"source": [
" "
]
},
{
"cell_type": "markdown",
"id": "2e31d28f-97b1-4a3d-a298-18fcad297150",
"metadata": {},
"source": [
"### Part 1: What is the total calibration result of possibly true equations?\n",
"\n",
"Our task is to find operators to balance each equation. The input \"`3267: 81 40 27`\" can be made into the equation \"`3267 = 81 + 40 * 27`\", with the understanding that all evaluations are done left-to-right, so this is \"`3267 = ((81 + 40) * 27)`\". The two allowable operators are addition and multiplication. Our task is to compute the sum of all the equations that can be balanced.\n",
"\n",
"The straightforward approach is to try both operators on every number. If there are *n* numbers in an equation then there will be 2*n*-2 possible equations; is that going to be a problem?"
]
},
{
"cell_type": "code",
"execution_count": 57,
"id": "6fa3907c-0e1a-4d4a-9fc3-f809b9325674",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"13"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(map(len, equations))"
]
},
{
"cell_type": "markdown",
"id": "e0d9b0b2-fe1e-434e-b84e-c044da3d3673",
"metadata": {},
"source": [
"No problem! With 13 numbers on a line there are 211 = 2048 equations; a small number. I'll define `can_be_calibrated` to keep a set of `results`, updating the set for each new number and each possible operator. Although the instructions were a bit vague, it appears that when they talk about \"numbers\" in the equations they mean \"positive integers\". That means that neither addition nor multiplication can cause a number to decrease, so once a result exceeds the target, we'll drop it."
]
},
{
"cell_type": "code",
"execution_count": 59,
"id": "5dfe0edf-cf29-4623-bb2c-6180f832f4d7",
"metadata": {},
"outputs": [],
"source": [
"def can_be_calibrated(numbers: ints, operators=(operator.add, operator.mul)) -> bool:\n",
" \"\"\"Can the tuple of numbers be calibrated as a correct equation using '+' and '*' ?\"\"\"\n",
" target, first, *rest = numbers\n",
" results = {first} # A set of all possible results of the partial computation\n",
" for y in rest:\n",
" results = {op(x, y) for x in results if x <= target for op in operators}\n",
" return target in results"
]
},
{
"cell_type": "code",
"execution_count": 60,
"id": "3085596d-f5ec-4ba8-b05a-cf70cf276a0c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 7.1: .0217 seconds, answer 1985268524462 ok"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(7.1, 1985268524462, lambda:\n",
" sum(numbers[0] for numbers in equations if can_be_calibrated(numbers)))"
]
},
{
"cell_type": "markdown",
"id": "62a5fe5f-e23f-4420-87a8-47d8be02fbc0",
"metadata": {},
"source": [
"### Part 2: What is the total calibration result of possibly true equations, allowing concatenation?\n",
"\n",
"In Part 2, we add a third operator: concatentation. The equation \"`192: 17 8 14`\" can be balanced by concatenated 17 and 8 to get 178, and then adding 14: \"`192 = ((17 || 8) + 14)`\". With three operators, the equation with 11 operators now has 311 = 177,147 possibilities, almost 100 times more than Part 1, so this will take a few seconds:"
]
},
{
"cell_type": "code",
"execution_count": 62,
"id": "5bdcb999-7f38-4814-bca5-13db88f4e214",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 7.2: 1.1006 seconds, answer 150077710195188 ok"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"operators3 = (operator.add, operator.mul, lambda x, y: int(str(x) + str(y)))\n",
" \n",
"answer(7.2, 150077710195188, lambda:\n",
" sum(numbers[0] for numbers in equations if can_be_calibrated(numbers, operators3)))"
]
},
{
"cell_type": "markdown",
"id": "2e5693b7-dab8-4f89-a000-c69ee75a11c9",
"metadata": {},
"source": [
"# [Day 8](https://adventofcode.com/2024/day/8): Resonant Collinearity\n",
"\n",
"Another grid input, this one a map of antenna locations. Each different non-\".\" character denotes an antenna of a given frequency."
]
},
{
"cell_type": "code",
"execution_count": 64,
"id": "cf6361a7-e3bc-42ec-ae16-f9eec166055e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 50 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"..................................................\n",
".................................C................\n",
".e..........7O....................................\n",
".....................................z............\n",
"......................t.........C.......k.........\n",
"............h................................9....\n",
".............5.7....O.............9C..............\n",
".......5.O................T.......................\n",
"...\n"
]
}
],
"source": [
"antennas = Grid(parse(8))"
]
},
{
"cell_type": "markdown",
"id": "c8e1006d-37bc-432e-bf1f-7a639287382a",
"metadata": {},
"source": [
"### Part 1: How many unique locations within the bounds of the map contain an antinode?\n",
"\n",
"An **antinode** occurs at a point that is perfectly in line with two antennas of the same frequency, but only when one of the antennas is twice as far away as the other.\n",
"\n",
"That means that if two antennas are at points *A* and *B*, then the two antinodal points are at 2*A* - *B* and 2*B* - A. If there are three or more antennas with the same frequency then we consider each pair of them in turn. So all we have to do is group the antennas by frequency, compute the antinodes for each pair with the same frequency, and determine which of those antinodal points are on the grid."
]
},
{
"cell_type": "code",
"execution_count": 66,
"id": "22180ce8-5d03-4aee-8c73-62f2afbddf71",
"metadata": {},
"outputs": [],
"source": [
"def antinodes(antennas: Grid) -> Set[Point]:\n",
" \"\"\"The set of all antinodal points in the grid.\n",
" (That is, points that are of distance d and 2d from same frequency antennas.)\"\"\"\n",
" groups = [antennas.findall(f) for f in set(antennas.values()) if f != '.']\n",
" return union(antinodes2(A, B, antennas)\n",
" for points in groups\n",
" for A, B in combinations(points, 2))\n",
"\n",
"def antinodes2(A: Point, B: Point, antennas: Grid) -> Set[Point]:\n",
" \"\"\"The set of antinodal points for two antenna points, A and B.\"\"\"\n",
" return {P for P in {sub(mul(A, 2), B), sub(mul(B, 2), A)}\n",
" if P in antennas}"
]
},
{
"cell_type": "code",
"execution_count": 67,
"id": "dd173ce9-cbbb-4282-b43f-c7cff662bd90",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 8.1: .0026 seconds, answer 220 ok"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(8.1, 220, lambda:\n",
" len(antinodes(antennas)))"
]
},
{
"cell_type": "markdown",
"id": "ff79d605-813a-46ac-8473-a1198be0e99f",
"metadata": {},
"source": [
"### Part 2: How many unique locations within the bounds of the map contain an updated antinode?\n",
"\n",
"For Part 2, the updated definition of antinodes means that they can now occur at *any* point that is exactly on line with two antennas of the same frequency, regardless of distance. So if the two antennas are *A* and *B* then the antinodal points can be found by starting at *A* and going step by step in the direction of the vector *A* - *B* and also in the direction *B* - *A*, going as far as you can while staying on the grid. The `Grid.follow_line` method facilitates that.\n",
"\n",
"I'll parametrize `updated_antinodes` so it can handle both parts:"
]
},
{
"cell_type": "code",
"execution_count": 69,
"id": "d30f8ce9-f186-46a0-a2e7-f74eceae6905",
"metadata": {},
"outputs": [],
"source": [
"def antinodes(antennas: Grid, antinodes2=antinodes2) -> Set[Point]:\n",
" \"\"\"The set of all updated antinodal points in the grid.\n",
" (That is, points that are on a line with two same frequency antennas.)\"\"\"\n",
" groups = [antennas.findall(f) for f in set(antennas.values()) if f != '.']\n",
" return union(antinodes2(A, B, antennas)\n",
" for points in groups\n",
" for A, B in combinations(points, 2))\n",
"\n",
"def updated_antinodes2(A: Point, B: Point, antennas: Grid) -> Set[Point]:\n",
" \"\"\"The set of updated antinodal points for two antenna points, A and B.\"\"\"\n",
" return (set(antennas.follow_line(A, sub(A, B))) | \n",
" set(antennas.follow_line(A, sub(B, A))))"
]
},
{
"cell_type": "code",
"execution_count": 70,
"id": "6bf85b57-8b8f-4196-9903-6d5fe082f404",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 8.1: .0025 seconds, answer 220 ok"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(8.1, 220, lambda:\n",
" len(antinodes(antennas)))"
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "f232952c-5fc6-4696-a8b1-d0b54137ac02",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 8.2: .0030 seconds, answer 813 ok"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(8.2, 813, lambda:\n",
" len(antinodes(antennas, updated_antinodes2)))"
]
},
{
"cell_type": "markdown",
"id": "9696a986-b6a2-4530-b55b-9db959ef7485",
"metadata": {},
"source": [
"I got both of these right the first time (except for some simple typos: a mismatched paren and typing `grid` when I meant the grid called `antennas`)."
]
},
{
"cell_type": "markdown",
"id": "d4835cad-7777-4636-b9af-52cc9782b2b8",
"metadata": {},
"source": [
"# [Day 9](https://adventofcode.com/2024/day/9): Disk Fragmenter\n",
"\n",
"Today we're confronted with a computer disk that needs to be compressed to gain some contiguous free space. The contents of the disk is represented in the **disk map** format: a string of digits, where the digits alternate between the number of blocks of a file, followed by the number of blocks of free space. We'll parse that as a tuple of digits:"
]
},
{
"cell_type": "code",
"execution_count": 74,
"id": "0e944f9e-5c16-440c-b12e-178058a87048",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 1 str:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"692094513253604282899448234539616972499153261626907217394161512944107098953354935354419233821564 ...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 1 tuple:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(6, 9, 2, 0, 9, 4, 5, 1, 3, 2, 5, 3, 6, 0, 4, 2, 8, 2, 8, 9, 9, 4, 4, 8, 2, 3, 4, 5, 3, 9, 6, 1, ...\n"
]
}
],
"source": [
"disk_map = the(parse(9, digits))"
]
},
{
"cell_type": "markdown",
"id": "99d40379-65e1-4872-8c68-17ba4925c24e",
"metadata": {},
"source": [
"\n",
"\n",
"### Part 1: Compress the hard drive. What is the resulting filesystem checksum? \n",
"\n",
"The disk map \"`12345`\" means that there is 1 block for the first file (which has ID number 0), followed by 2 empty blocks, then 3 blocks for the second file (with ID number 1), followed by 4 empty blocks, and finally 5 blocks for the third file (with ID number 2). It makes sense to convert this into a **disk layout** format, which would be \"`0..111....22222`\", where \"`.`\" represents an empty block.\n",
"\n",
"To **compress** a disk layout, move file blocks one at a time starting by taking the rightmost non-empty block and moving it to the leftmost empty position; repeat until no more moves are possible.\n",
"\n",
"The final answer is a **checksum** of the compressed disk: the sum of the product of the block position times the file ID number for all non-empty blocks."
]
},
{
"cell_type": "code",
"execution_count": 76,
"id": "76e8454d-a2f3-4b6b-92df-182116cf46e0",
"metadata": {},
"outputs": [],
"source": [
"empty = '.'\n",
"\n",
"def disk_layout(disk_map: Ints) -> list:\n",
" \"\"\"Convert a disk map into a disk layout.\"\"\"\n",
" layout = []\n",
" for id, i in enumerate(range(0, len(disk_map), 2)):\n",
" layout.extend(disk_map[i] * [id])\n",
" if i + 1 < len(disk_map):\n",
" layout.extend(disk_map[i + 1] * [empty])\n",
" return layout\n",
"\n",
"def compress_layout(layout: list) -> list:\n",
" \"\"\"Mutate layout by moving blocks one at a time from the end to the leftmost free space.\"\"\"\n",
" N = len(layout)\n",
" free = -1 # Start looking for free space from the left\n",
" end = N # Start looking for non-empty blocks from the right\n",
" while True:\n",
" free = first(i for i in range(free + 1, N) if layout[i] is empty)\n",
" end = first(i for i in range(end - 1, 0, -1) if layout[i] is not empty)\n",
" if free is None or free >= end:\n",
" return layout\n",
" layout[free], layout[end] = layout[end], empty\n",
"\n",
"def checksum(layout: list) -> list:\n",
" \"\"\"The sum of the product of the block position times the file ID number for all non-empty blocks.\"\"\"\n",
" return sum(i * id for i, id in enumerate(layout) if id is not empty)"
]
},
{
"cell_type": "code",
"execution_count": 77,
"id": "2aa7e2b9-844e-49ed-b41b-4a4cecff86b7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 9.1: .0193 seconds, answer 6332189866718 ok"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(9.1, 6332189866718, lambda:\n",
" checksum(compress_layout(disk_layout(disk_map))))"
]
},
{
"cell_type": "markdown",
"id": "2c05a497-cc66-4698-b88b-25c33eea224a",
"metadata": {},
"source": [
"### Part 2: Compress the hard drive with the new method. What is the resulting filesystem checksum? \n",
"\n",
"In Part 2, there is a new method of compressing the disk, where we move full files rather than a block at a time. Again we start on the right, and try to move a file to the leftmost position where it will fit. If there is no such position, the file doesn't move. `compress_layout2` implements this new method, performing a move by swapping two [**slices**](https://docs.python.org/3/library/functions.html#slice) of the disk layout: \n",
"\n",
" layout[file], layout[free] = layout[free], layout[file]`\n",
"\n",
"To find all the slices that indicate files, it is easier to run through the disk map than the disk layout. The function `file_slices` quickly finds all such slices.\n",
"\n",
"Finding a free space for a file is more difficult, because we need to find one that is big enough. I'll run through the whole layout from left-to-right each time. This will make it *O*(*n*2) rather than *O*(*n*), but hopefully it won't be too slow. (If I wanted to speed it up I could have an array of starting positions for each desired size of free space.)"
]
},
{
"cell_type": "code",
"execution_count": 79,
"id": "fcf4d832-3d7d-4987-aa57-e6e0f1df16bf",
"metadata": {},
"outputs": [],
"source": [
"def compress_layout2(disk_map: Ints) -> list:\n",
" \"\"\"Mutate layout by moving files one at a time from the end to the leftmost free space.\"\"\"\n",
" layout = disk_layout(disk_map)\n",
" for file in file_slices(disk_map):\n",
" free = find_freespace(layout, file)\n",
" if free:\n",
" layout[file], layout[free] = layout[free], layout[file]\n",
" return layout\n",
"\n",
"def file_slices(disk_map: Ints) -> List[slice]:\n",
" \"\"\"Given a disk map, find all the slice positions of files in the disk layout (last one first).\"\"\"\n",
" slices = []\n",
" block = 0\n",
" for i, length in enumerate(disk_map):\n",
" if i % 2 == 0:\n",
" slices.append(slice(block, block + length))\n",
" block += length\n",
" slices.reverse()\n",
" return slices\n",
"\n",
"def find_freespace(layout, file_slice) -> Optional[slice]:\n",
" \"\"\"Find a slice position big enough to fit the given file slice, or return None if there is no position.\"\"\"\n",
" length = file_slice.stop - file_slice.start\n",
" run = 0\n",
" for i in range(layout.index(empty), len(layout)):\n",
" if i >= file_slice.start:\n",
" return None # We only want to move a file left, not right\n",
" elif layout[i] is empty:\n",
" run += 1\n",
" if run == length:\n",
" return slice(i + 1 - length, i + 1)\n",
" else:\n",
" run = 0\n",
" return None"
]
},
{
"cell_type": "code",
"execution_count": 80,
"id": "e3036875-88d0-496e-9d2f-facd0e80a5b2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 9.2: 2.6956 seconds, answer 6353648390778 ok"
]
},
"execution_count": 80,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(9.2, 6353648390778, lambda:\n",
" checksum(compress_layout2(disk_map)))"
]
},
{
"cell_type": "markdown",
"id": "24c0e7d7-6ac7-4e4b-9557-bd4e215ad0a9",
"metadata": {},
"source": [
"I got the right answer, but I confess I had an off-by-one **bug** in `find_freespace` on the first try."
]
},
{
"cell_type": "markdown",
"id": "7a900425-fe22-4d2f-8d1d-46c319c109e9",
"metadata": {},
"source": [
"# [Day 10](https://adventofcode.com/2024/day/10): Hoof It\n",
"\n",
"Today's input is a topological map, with digits indicating the elevation of each terrain position."
]
},
{
"cell_type": "code",
"execution_count": 83,
"id": "5804fb03-05f3-402f-b6cc-6804c5d22512",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 60 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"432109865210212123765432101234321098543289654320132112121058\n",
"045678774324301012892343023445456787650198763013241001034569\n",
"187678789465692321001056014896234986456787012894653212123678\n",
"296589921056789433217837895687145675323891233765784589238987\n",
"345437835434576544786921278761010014210710321212098676521067\n",
"032126546323465435695430789760121223121653450303145125430678\n",
"123010567810156543212345699859834321056544067654236012321589\n",
"543213498987657665401030787348765430187432198765987622345432\n",
"...\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 60 tuples:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(4, 3, 2, 1, 0, 9, 8, 6, 5, 2, 1, 0, 2, 1, 2, 1, 2, 3, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, ...\n",
"(0, 4, 5, 6, 7, 8, 7, 7, 4, 3, 2, 4, 3, 0, 1, 0, 1, 2, 8, 9, 2, 3, 4, 3, 0, 2, 3, 4, 4, 5, 4, 5, ...\n",
"(1, 8, 7, 6, 7, 8, 7, 8, 9, 4, 6, 5, 6, 9, 2, 3, 2, 1, 0, 0, 1, 0, 5, 6, 0, 1, 4, 8, 9, 6, 2, 3, ...\n",
"(2, 9, 6, 5, 8, 9, 9, 2, 1, 0, 5, 6, 7, 8, 9, 4, 3, 3, 2, 1, 7, 8, 3, 7, 8, 9, 5, 6, 8, 7, 1, 4, ...\n",
"(3, 4, 5, 4, 3, 7, 8, 3, 5, 4, 3, 4, 5, 7, 6, 5, 4, 4, 7, 8, 6, 9, 2, 1, 2, 7, 8, 7, 6, 1, 0, 1, ...\n",
"(0, 3, 2, 1, 2, 6, 5, 4, 6, 3, 2, 3, 4, 6, 5, 4, 3, 5, 6, 9, 5, 4, 3, 0, 7, 8, 9, 7, 6, 0, 1, 2, ...\n",
"(1, 2, 3, 0, 1, 0, 5, 6, 7, 8, 1, 0, 1, 5, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 9, 9, 8, 5, 9, 8, 3, ...\n",
"(5, 4, 3, 2, 1, 3, 4, 9, 8, 9, 8, 7, 6, 5, 7, 6, 6, 5, 4, 0, 1, 0, 3, 0, 7, 8, 7, 3, 4, 8, 7, 6, ...\n",
"...\n"
]
}
],
"source": [
"topo = Grid(parse(10, digits))"
]
},
{
"cell_type": "markdown",
"id": "d951807a-3611-445f-84ee-352221a25968",
"metadata": {},
"source": [
"### Part 1: What is the sum of the scores of all trailheads on your topographic map?\n",
"\n",
"A **trailhead** is any position with elevation 0, and a **peak** is any position with elevation 9. The **score** of a trailhead is the number of peaks that can be reached by following a path where each step increases the elevation by exactly 1. All moves are in one of the four cardinal directions (north/south/east/west).\n",
"\n",
"I'll keep a set of points on the frontier of possible paths, updating this set on each iteratation from 1 to 9, by looking at each point on the frontier and seeing which of the neighboring points `p` have the right elevation:"
]
},
{
"cell_type": "code",
"execution_count": 85,
"id": "76b5379e-ee19-4607-91b8-88ec7b38023f",
"metadata": {},
"outputs": [],
"source": [
"def score(topo: Grid, trailhead: Point) -> int:\n",
" \"\"\"How many peaks can be reached from this trailhead?\"\"\"\n",
" frontier = {trailhead}\n",
" for elevation in range(1, 10):\n",
" frontier = {p for p in union(map(topo.neighbors, frontier))\n",
" if topo[p] == elevation}\n",
" return len(frontier)"
]
},
{
"cell_type": "code",
"execution_count": 86,
"id": "97cf05f7-fa56-4a90-b2d8-2cd4d9b81f95",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 10.1: .0046 seconds, answer 744 ok"
]
},
"execution_count": 86,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(10.1, 744, lambda:\n",
" sum(score(topo, head) for head in topo.findall([0])))"
]
},
{
"cell_type": "markdown",
"id": "4656eb08-b12a-4a02-92b8-ac23f2361387",
"metadata": {},
"source": [
"### Part 2: What is the sum of the ratings of all trailheads?\n",
"\n",
"The **rating** of a trailhead is the number of distinct paths from the trailhead to a peak.\n",
"\n",
"As in Part 1, I'll keep a frontier and update it on each iteration from 1 to 9, but this time the frontier will be a counter of `{position: count}` where the count indicates the number of paths to that position. On each iteration I'll look at each point `f` on the frontier and see which of the neighboring points `p` have the right elevation, and increment the counts for those points by the count for `f`. This approach is linear in the number of positions, whereas if I followed all possible paths depth-first there could be an exponential number of paths."
]
},
{
"cell_type": "code",
"execution_count": 88,
"id": "b763450f-a565-4936-bee4-e531c2eeebdb",
"metadata": {},
"outputs": [],
"source": [
"def rating(topo: Grid, trailhead: Point) -> int:\n",
" \"\"\"How many distinct paths are there from this trailhead to any peak?\"\"\"\n",
" frontier = Counter({trailhead: 1})\n",
" for elevation in range(1, 10):\n",
" frontier = accumulate((p, frontier[f]) \n",
" for f in frontier\n",
" for p in topo.neighbors(f) if topo[p] == elevation)\n",
" return sum(frontier.values())"
]
},
{
"cell_type": "code",
"execution_count": 89,
"id": "f8a87032-6556-4fc9-9bb8-573611aee8dc",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 10.2: .0057 seconds, answer 1651 ok"
]
},
"execution_count": 89,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(10.2, 1651, lambda:\n",
" sum(rating(topo, head) for head in topo.findall([0])))"
]
},
{
"cell_type": "markdown",
"id": "af410d30-7096-4be6-bb20-904b3c8e2f59",
"metadata": {},
"source": [
"Today I went pretty fast (for me); I started a few minutes late and finished in 15 minutes. From the point of view of a competitive coder I did foolish things like write docstrings and use variables of more than one letter, so while this time was fast for me, it placed well out of the top 1000."
]
},
{
"cell_type": "markdown",
"id": "3e01d7f5-d0f0-4e7b-8cab-eef2afc02f6b",
"metadata": {},
"source": [
"# [Day 11](https://adventofcode.com/2024/day/11): Plutonian Pebbles\n",
"\n",
"Today's narrative involves a straight line of stones, each of which has a number enscribed on it. The input is a single line of these numbers:"
]
},
{
"cell_type": "code",
"execution_count": 92,
"id": "76b68cef-d8de-4145-b65c-b254fedf1671",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 1 str:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"0 27 5409930 828979 4471 3 68524 170\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Parsed representation ➜ 1 tuple:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"(0, 27, 5409930, 828979, 4471, 3, 68524, 170)\n"
]
}
],
"source": [
"stones = the(parse(11, ints))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "a7302dc5-5163-4f0b-bdcc-8c00e367391c",
"metadata": {},
"source": [
"### Part 1: How many stones will you have after blinking 25 times?\n",
"\n",
"Every time you blink, the stones appear to change, according to these rules:\n",
"- A stone marked 0 changes to 1.\n",
"- Otherwise, a stone with an even number of digits splits into two stones, with the first and second halves of those digits.\n",
"- Otherwise, the stone's number is multiplied by 2024.\n",
"\n",
"\n",
"\n",
"\n",
"I'll define `blink` to simulate the effect of a given number of blinks, and `change_stone` to change a single stone, returning a list of wither one or two stones (the two stones computed by `split_stone`):"
]
},
{
"cell_type": "code",
"execution_count": 94,
"id": "1513df56-3d6f-42cf-8aec-1bdbeb991d90",
"metadata": {},
"outputs": [],
"source": [
"def blink(stones: Ints, blinks=25) -> List[int]:\n",
" \"\"\"Simulate the changes in the list of stones after blinking `blinks` times.\"\"\"\n",
" for _ in range(blinks):\n",
" stones = append(map(change_stone, stones))\n",
" return stones\n",
" \n",
"def change_stone(stone: int) -> List[int]:\n",
" \"\"\"Change a single stone into one or two, according to the rules.\"\"\"\n",
" digits = str(stone)\n",
" return ([1] if stone == 0 else\n",
" split_stone(digits) if len(digits) % 2 == 0 else\n",
" [stone * 2024])\n",
"\n",
"def split_stone(digits: str) -> List[int]:\n",
" \"\"\"Split a stone into two halves.\"\"\"\n",
" half = len(digits) // 2\n",
" return [int(digits[:half]), int(digits[half:])]"
]
},
{
"cell_type": "code",
"execution_count": 95,
"id": "eff17cd0-a2c7-4d69-bc55-c0ef97917915",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 11.1: .0626 seconds, answer 194482 ok"
]
},
"execution_count": 95,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(11.1, 194482, lambda:\n",
" len(blink(stones)))"
]
},
{
"cell_type": "markdown",
"id": "2f65e94f-43e8-4f08-85df-827928c57e0b",
"metadata": {},
"source": [
"### Part 2: How many stones would you have after blinking a total of 75 times?\n",
"\n",
"It looks like the number of stones is roughly doubling every 1 or 2 blinks, so for 75 blinks we could have trillions of stones. I'd like something more efficient. I note that:\n",
"- Although the puzzle makes it clear that the stones are in a line, it turns out their position in the line is irrelevant.\n",
"- Because all the even-digit numbers get split in half, it seems like many small numbers will appear multiple times.\n",
"- (In the given example, after 6 blinks the number 2 appears 4 times.)\n",
"- Therefore, I'll keep a `Counter` of stones rather than a `list` of stones."
]
},
{
"cell_type": "code",
"execution_count": 97,
"id": "707b5a97-0296-48df-bdab-e34064cc67c2",
"metadata": {},
"outputs": [],
"source": [
"def blink2(stones: Ints, blinks=25) -> Counter:\n",
" \"\"\"Simulate the changes after blinking `blinks` times and return a Counter of stones.\"\"\"\n",
" counts = Counter(stones)\n",
" for _ in range(blinks):\n",
" counts = accumulate((s, counts[stone]) \n",
" for stone in counts \n",
" for s in change_stone(stone))\n",
" return counts"
]
},
{
"cell_type": "markdown",
"id": "f5bf07ce-b48e-40db-8992-b9b571e66554",
"metadata": {},
"source": [
"Now we can re-run Part 1 (it should be slightly faster), and run Part 2 without fear of having trillion-element lists:"
]
},
{
"cell_type": "code",
"execution_count": 99,
"id": "efdcdbf8-e8ec-4a85-9d09-90a20e08c66a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 11.1: .0015 seconds, answer 194482 ok"
]
},
"execution_count": 99,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(11.1, 194482, lambda:\n",
" total(blink2(stones, 25)))"
]
},
{
"cell_type": "code",
"execution_count": 100,
"id": "657b1f13-ffcc-44c6-84f1-398fa2fcdac7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 11.2: .0548 seconds, answer 232454623677743 ok"
]
},
"execution_count": 100,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(11.2, 232454623677743, lambda:\n",
" total(blink2(stones, 75)))"
]
},
{
"cell_type": "markdown",
"id": "ce377749-b3e2-4ca4-b50d-e7c3d2e7201a",
"metadata": {},
"source": [
"Again, I did pretty well, with no errors, and moving at what I thought was a good pace, but I didn't even crack the top 2000 on the leaderboard. I guess I spent too much time writing docstrings and type hints, and refactoring as I went."
]
},
{
"cell_type": "markdown",
"id": "391cec1e-32fe-4e6e-81c2-4e38469b15e3",
"metadata": {},
"source": [
"# [Day 12](https://adventofcode.com/2024/day/12): Garden Groups\n",
"\n",
"Today's input is yet another 2D map. This one depicts different garden plots on a farm, each plot planted with a crop, indicated by a letter (maybe \"I\" is iceberg lettuce and \"U\" is udo, and so on):"
]
},
{
"cell_type": "code",
"execution_count": 103,
"id": "8161ee7e-76e3-499a-abf8-a607991c9602",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"Puzzle input ➜ 140 strs:\n",
"────────────────────────────────────────────────────────────────────────────────────────────────────\n",
"IIIIIIIIIIIIIIIIIIIIIUUUUUUUUJLLLLAAAAAAMMMAUUUUPPXPZZZZZZZZZZZXXXXXXXXXXXXXXXXXXXXXFFFFFFFFFFZZ ...\n",
"IIIIIIIIIIIIIIIIIIIIUUUUUUUUUJALEAAAAAAAAAAAAUUUUPXPPZZZZZHHHHHHXHXXXXXXXXXXXXXXXXXXFXFFFFFFFFZZ ...\n",
"IIIIIIIIIIIIIIIIIIIIUUUUUUUUUJAAAAAAAAAAAAAAUUPPPPPPPZZZZZZZHHHHHHHXXXXXXXXXXXXXXXXXXXFFFFFFFFFZ ...\n",
"IIIIIIIIIIIAAIIIIIIIIIUUUUUUUJJAAAAAAAAAAAAAAVVPPPPPPPPZHHHHHHHHHHHXXXXXXXXXXXXXXXXXFFFFFFFFFFFZ ...\n",
"IOOIIIIIIIIAAIIIIIIIIIIUUUQVUJJAAAAAAAAAAAAAEVVZPPPPPPPHHHHHHHHHHHHXXXXXXXXXXXXXXXXXXXXFFFFFFLLL ...\n",
"OOOOOOOOIIAAAAAIIIIIIIIUQQQQVQJAAAAAAAAAAAAAAVVPPPPPIIHHHHHHHHHHHHHXXXXXUXXXXXXUUXXBBBSFFFLLLLLL ...\n",
"OOOOOOOOIAAAAAAIIIIIIQQQQQQQQQQQEADDAAAAAAAAHHVVPPPIIIIHHHHHHHHHHHHHXXXUUUUUXXUUUXXBBBSFFFLLELLL ...\n",
"OOOOOOOOIIIAAIIIIIQQQQQQQQQQTQJQEEDDDAAAAAAHHVVVVPIIIIIHHHHHHHHHHHHHXUUUUUUUUUUUMMXBBBSSSFFFLLLL ...\n",
"...\n"
]
}
],
"source": [
"farm = Grid(parse(12))"
]
},
{
"cell_type": "markdown",
"id": "bb95a10b-1f83-4940-a68b-b94696c3aab3",
"metadata": {},
"source": [
"### Part 1: What is the total price of fencing all regions on your map?\n",
"\n",
"We are asked to calculate the cost of putting fences around each **region** (a region is a set of plots with the same crop that abut each other horizontally or vertically). The price of the fence for a region is defined as the product of the region's area and its perimeter. If we represent a region as a set of (x, y) points, then the area is easy: it is just the number of points. The perimeter length can be computed by, for each plot point in the region, looking at each of the four directions and counting cases where the adjacent plot in that direction is *not* in the region. (Initially I had a **bug** in that I looked at the `farm.neighbors` of each plot. That doesn't work because a plot on the edge of the grid should count as part of the perimeter.)"
]
},
{
"cell_type": "code",
"execution_count": 105,
"id": "79f91f38-e325-44f2-9e53-b64ce12d9d35",
"metadata": {},
"outputs": [],
"source": [
"Region = Set[Point]\n",
"region_area = len\n",
"\n",
"def fence_price(farm: Grid) -> int:\n",
" \"\"\"Total price of fences for all the regions in the farm.\"\"\"\n",
" return sum(map(region_price, regions(farm)))\n",
"\n",
"def region_price(region) -> int: return region_area(region) * perimeter_length(region)\n",
"\n",
"def perimeter_length(region: Region) -> int:\n",
" \"\"\"The number of sides on the perimeter of the region.\"\"\"\n",
" return quantify(add2(plot, d) not in region for plot in region for d in directions4)"
]
},
{
"cell_type": "markdown",
"id": "9524ee15-c378-4cd4-a79b-14fb99b17cb3",
"metadata": {},
"source": [
"To find all the regions I'll start at a point and do a [flood fill](https://en.wikipedia.org/wiki/Flood_fill) to neighboring points with the same region letter, keeping track of points that have already been found so as to not duplicate them. The function `regions` iterates over all points to make sure it finds every region, and `flood_fill` recursively expands to all points that neighbor `p` and have the same crop (letter). This function mutates the set `already_found` as it goes (and also mutates the `region` it is building up)."
]
},
{
"cell_type": "code",
"execution_count": 107,
"id": "1fbabbfb-50c8-4197-8517-e7cee9582765",
"metadata": {},
"outputs": [],
"source": [
"def regions(farm: Grid) -> List[Region]:\n",
" \"\"\"Find all the regions in the farm.\"\"\"\n",
" already_found = set() # Set of plots already accounted for\n",
" return [flood_fill(p, farm, set(), already_found) \n",
" for p in farm if p not in already_found]\n",
"\n",
"def flood_fill(p: Point, grid: Grid, region: set, already_found: set) -> set:\n",
" \"\"\"Starting at point p, recursively add all neighboring points to `region`, keeping track of `already_found`.\"\"\"\n",
" if p not in already_found:\n",
" region.add(p)\n",
" already_found.add(p)\n",
" for p2 in grid.neighbors(p):\n",
" if farm[p2] == farm[p]:\n",
" flood_fill(p2, grid, region, already_found)\n",
" return region"
]
},
{
"cell_type": "code",
"execution_count": 108,
"id": "cdaf655b-d12c-4973-b19b-3132e5e691c6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 12.1: .0307 seconds, answer 1402544 ok"
]
},
"execution_count": 108,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(12.1, 1402544, lambda:\n",
" fence_price(farm))"
]
},
{
"cell_type": "markdown",
"id": "b3383560-2bbc-4dfc-b643-feb103876823",
"metadata": {},
"source": [
"### Part 2: What is the new total price of fencing all regions on your map, with the bulk discount?\n",
"\n",
"In Part 2 we get a **bulk discount** on the fencing; we only need to pay for the number of straight line sides on the perimeter, not the total length of the perimeter. For example, a 10 x 10 square has perimeter 40, but has only 4 sides; that's a 90% discount!\n",
"\n",
"It took me a while to figure out a good approach for this. At first I was reminded of the Convex Hull problem, for which I have [a notebook](https://github.com/norvig/pytudes/blob/main/ipynb/Convex%20Hull.ipynb). But that's not really appropriate here; our regions could be non-convex, and the set of points in a region are not the same as the vertexes of a polygon (e.g., a region with one point has 4 sides, not 0).\n",
"\n",
"A better idea is to start with the perimeter length and subtract one for every case in which a points has an edge in one direction (e.g., an edge to the North) and also has a neighbor with the same edge. To be precise, I'll look for four cases:\n",
"- A point with an edge to the North whose neighbor to the East also has an edge to the North\n",
"- A point with an edge to the East whose neighbor to the South also has an edge to the East\n",
"- A point with an edge to the South whose neighbor to the West also has an edge to the South\n",
"- A point with an edge to the West whose neighbor to the North also has an edge to the West\n",
"\n",
"Here's a diagram of a region of \"`X`\" crops with a \"`-`\" marking each place where a perimeter piece would be subtracted.\n",
"\n",
" .X-...\n",
" -X-.X-\n",
" -XXXX-\n",
" ..XXX.\n",
" ...--.\n",
"\n",
"Again, I'll parameterize `fence_price` to take a `region_price` parameter:"
]
},
{
"cell_type": "code",
"execution_count": 110,
"id": "38c30e15-3a33-40c2-b734-163a15af7a8a",
"metadata": {},
"outputs": [],
"source": [
"def fence_price(farm: Grid, region_price=region_price) -> int:\n",
" \"\"\"Total price of fences for all the regions in the farm, given the price function for a region.\"\"\"\n",
" return sum(map(region_price, regions(farm)))\n",
"\n",
"def discount_region_price(region) -> int: return region_area(region) * region_sides(region)\n",
" \n",
"def region_sides(region):\n",
" \"\"\"How many straight-line sides does this region have?\"\"\"\n",
" def has_edge(p: Point, d: Vector): return p in region and add2(p, d) not in region\n",
" def neighbor(p: Point, d: Vector): return add2(p, make_turn(d, 'R'))\n",
" subtract = quantify(has_edge(p, d) and has_edge(neighbor(p, d), d)\n",
" for p in region\n",
" for d in directions4)\n",
" return perimeter_length(region) - subtract"
]
},
{
"cell_type": "code",
"execution_count": 111,
"id": "72175812-dcd0-4f1b-9efa-0dceeeafa609",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 12.1: .0302 seconds, answer 1402544 ok"
]
},
"execution_count": 111,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(12.1, 1402544, lambda:\n",
" fence_price(farm))"
]
},
{
"cell_type": "code",
"execution_count": 112,
"id": "9defcd35-91bc-41d4-a16f-bb7a4ede75e7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Puzzle 12.2: .0426 seconds, answer 862486 ok"
]
},
"execution_count": 112,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer(12.2, 862486, lambda: \n",
" fence_price(farm, discount_region_price))"
]
},
{
"cell_type": "markdown",
"id": "c3317844-2b4a-4756-8a59-b765aa467445",
"metadata": {},
"source": [
"# Summary\n",
"\n",
"So far, I've solved all the puzzles. Most of them run in well under a second, but three of them take over a second."
]
},
{
"cell_type": "code",
"execution_count": 114,
"id": "34813fc9-a000-4cd8-88ae-692851b3242c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Puzzle 1.1: .0002 seconds, answer 1830467 ok\n",
"Puzzle 1.2: .0001 seconds, answer 26674158 ok\n",
"Puzzle 2.1: .0004 seconds, answer 257 ok\n",
"Puzzle 2.2: .0022 seconds, answer 328 ok\n",
"Puzzle 3.1: .0006 seconds, answer 156388521 ok\n",
"Puzzle 3.2: .0004 seconds, answer 75920122 ok\n",
"Puzzle 4.1: .0338 seconds, answer 2401 ok\n",
"Puzzle 4.2: .0259 seconds, answer 1822 ok\n",
"Puzzle 5.1: .0006 seconds, answer 5762 ok\n",
"Puzzle 5.2: .0008 seconds, answer 4130 ok\n",
"Puzzle 6.1: .0014 seconds, answer 5329 ok\n",
"Puzzle 6.2: 1.9151 seconds, answer 2162 ok\n",
"Puzzle 7.1: .0217 seconds, answer 1985268524462 ok\n",
"Puzzle 7.2: 1.1006 seconds, answer 150077710195188 ok\n",
"Puzzle 8.1: .0025 seconds, answer 220 ok\n",
"Puzzle 8.2: .0030 seconds, answer 813 ok\n",
"Puzzle 9.1: .0193 seconds, answer 6332189866718 ok\n",
"Puzzle 9.2: 2.6956 seconds, answer 6353648390778 ok\n",
"Puzzle 10.1: .0046 seconds, answer 744 ok\n",
"Puzzle 10.2: .0057 seconds, answer 1651 ok\n",
"Puzzle 11.1: .0015 seconds, answer 194482 ok\n",
"Puzzle 11.2: .0548 seconds, answer 232454623677743 ok\n",
"Puzzle 12.1: .0302 seconds, answer 1402544 ok\n",
"Puzzle 12.2: .0426 seconds, answer 862486 ok\n"
]
}
],
"source": [
"for d in sorted(answers):\n",
" print(answers[d])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}