AdventOfCode2023/README.md

152 lines
14 KiB
Markdown
Raw Normal View History

2024-06-26 09:32:52 +02:00
# :christmas_tree: Advent of Code 2023
2023-12-01 23:03:05 +01:00
2023-12-03 01:55:36 +01:00
Solver for [Advent of Code 2023](https://adventofcode.com/2023/) puzzles.
2023-12-01 23:04:26 +01:00
This is a single command line application for all puzzles written in [FreePascal](https://www.freepascal.org) with [Lazarus](https://www.lazarus-ide.org/) 2.2.6 and compiled with FPC 3.2.2.
## Puzzle Input
This project does not contain the puzzle or example inputs as per the [copyright notice of Advent of Code](https://adventofcode.com/about). In order to run the compiled application, the puzzle inputs have to be downloaded from the [Advent of Code 2023](https://adventofcode.com/2023/) puzzle pages, and placed as text files into the `bin\data` directory, e.g. `bin\data\cube_conundrum.txt` or `bin\data\example\cube_conundrum.txt`. The application will output an error with details, if it cannot find an input file.
2024-06-26 09:34:05 +02:00
## Tests
On day 3, I introduced unit tests to help troubleshoot issues and prevent regressions while I kept iterating over the solver class framework. These tests cover the provided example solutions and occasional partial data tests whenever I felt the need for it.
I also added tests for the full puzzle data once I found the solution, but these tests are not public to not spoil the Advent of Code puzzles.
2024-06-26 09:32:52 +02:00
## Solutions
2024-06-26 09:32:52 +02:00
### Day 1: Trebuchet?!
:mag_right: Puzzle: <https://adventofcode.com/2023/day/1>, :white_check_mark: Solver: [`UTrebuchet.pas`](solvers/UTrebuchet.pas)
My solution parses each line once forward for the right number, and once backward for the left number for both parts of the puzzle.
2024-06-26 09:32:52 +02:00
### Day 2: Cube Conundrum
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/2>, :white_check_mark: Solver: [`UCubeConundrum.pas`](solvers/UCubeConundrum.pas)
That one seemed pretty straight forward. For each line, the solution immediately sums up games that fulfill the maxima and finds the maxima of each color.
2024-06-26 09:32:52 +02:00
### Day 3: Gear Ratios
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/3>, :white_check_mark: Solver: [`UGearRatios.pas`](solvers/UGearRatios.pas)
This was the first puzzle where I had to implement a solver processing mutliple lines at once instead of one by one. Here, it also needs the lines directly before and after the one being processed.
The algorithm processes the numbers in the middle line and looks for additional symbols in the lines before and after. The tricky part was to correctly track the data needed for processing of each line and discarding it in time, without resorting to reading all data in before processing.
2024-06-26 09:32:52 +02:00
### Day 4: Scratchcards
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/4>, :white_check_mark: Solver: [`UScratchCards.pas`](solvers/UScratchCards.pas)
2023-12-10 10:33:31 +01:00
For part 1, the algorithm simply matches winning numbers against numbers we have, and multiplies the current line result by two for every match (except the first).
For part 2, there is a list of numbers of card copies for the upcoming cards, where the list index is shifted to be always relative to the current line. This works because the copies are always applied contiguously over upcoming cards. Once a card has been processed, its copy value is deleted from the beginning of the list.
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
### Day 5: If You Give A Seed A Fertilizer
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/5>, :white_check_mark: Solver: [`UGiveSeedFertilizer.pas`](solvers/UGiveSeedFertilizer.pas)
2023-12-10 10:33:31 +01:00
Originally, I had implemented this by reading all data in first, constructing a list of the seven mappings, each containing a list of mapping ranges. I rewrote this when I realized that the conversion can be done line-by-line by maintaining separate lists of "unconverted" and "converted" values. Each mapping range is applied to all unconverted values, and if one matches it is converted and moved into the list of converted values. At the end of a map all converted values are moved back into the unconverted list. Unconverted values simply remain unconverted for the next map.
For part 2, it is not necessary (and not feasible) to convert the input ranges into individual values to run through the existing algorithm. Instead I modified the algorithm to run on ranges of input directly. This means that a successful conversion can split a range in up to three parts, where one is moved into the "converted" pile, while the others remain unconverted.
2024-06-26 09:32:52 +02:00
### Day 6: Wait For It
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/6>, :white_check_mark: Solver: [`UWaitForIt.pas`](solvers/UWaitForIt.pas)
This one I solved by calculating the roots of the function *f(x) = -time ^2 * x + distance* and determining the distance between them. Part 2 was the first puzzle where my solver required 64-bit integers for the calculations.
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
### Day 7: Camel Cards
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/7>, :white_check_mark: Solver: [`UCamelCards.pas`](solvers/UCamelCards.pas)
The first puzzle that I could not solve line-by-line (day 6 doesn't count). For this one I store all the card hands and assign them a "type", e.g. "four of a kind", when processing them by counting the different card values in a hand. The rest of work is done in a custom compare function. When all data is processed, I just use the compare function to sort all card hands, and then multiply the resulting indices with the bids.
2023-12-10 10:33:31 +01:00
For part 2, each card hands gets a "joker type" analoguous to the "type", for which the number of joker cards is added to the highest number of a different card type.
2024-06-26 09:32:52 +02:00
### Day 8: Haunted Wasteland
2023-12-10 10:33:31 +01:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/8>, :white_check_mark: Solver: [`UHauntedWasteland.pas`](solvers/UHauntedWasteland.pas)
2023-12-10 10:33:31 +01:00
Again a puzzle where I had to read in all of the data before starting the algorithm. It proved difficult to verify parts of the algorithm by hand, but part 1 was still pretty straight forward.
Part 2 was a bit sneaky. This is the first puzzle where the result is outside the 32-bit unsigned integer range. And it is solvable only because each starting node leads into a loop with one of the target nodes, where the length of the loop is a multiple of the length of the sequence of instructions. With this knowledge, one can stop traversing the network once each target node has been reached and calculate the result directly.
2024-06-26 09:32:52 +02:00
### Day 9: Mirage Maintenance
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/9>, :white_check_mark: Solver: [`UMirageMaintenance.pas`](solvers/UMirageMaintenance.pas)
This one I enjoyed the most so far. The process that is discribed in the puzzle, constructing a series of differences from the previous series, and then reverting the process to extend the series, is equivalent to finding a polynomial with maximum degree of *n - 1*, where the original series are *n* equidistant values of the polynomial.
So instead of using the outlined "brute force" method, I used Lagrange polynomials with *x1 = 0, x2 = 1, ..., xn = n - 1* evaluated at *x = n* (for part 1) and *x = -1* (for part 2) to find the function values for the extrapolated "points". Conveniently, the Lagrange polynomials can be precalculated for the whole puzzle (with some tricks to not run over Int64 limits) because they only depend on *x* values, which remain constant. This makes the calculation of the extrapolated values quite easy.
A nice explanation of the Lagrange method can be found here <http://bueler.github.io/M310F11/polybasics.pdf>.
2024-06-26 09:32:52 +02:00
### Day 10: Pipe Maze
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/10>, :white_check_mark: Solver: [`UPipeMaze.pas`](solvers/UPipeMaze.pas)
The input data is such that there are only two pipes pointing to *S*, so finding the loop is only a matter of following the chars as instructed. It seems best to read in the full input before trying to traverse the maze, I did not see another option. The length of the loop is always even, so my algorithm just follows the path until it is back to *S* and counts only every other step.
For part 2, I tracked tiles that are "left" and "right" of the path the algorithm took, and implemented a little flood-fill algorithm that tries to fill the area in between the "left" tiles and the "right" tiles, while counting them. The "outside" group is the one where the flood-fill touches the edge of the map and is simply ignored.
2024-06-26 09:32:52 +02:00
### Day 11: Cosmic Expansion
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/11>, :white_check_mark: Solver: [`UCosmicExpansion.pas`](solvers/UCosmicExpansion.pas)
While parsing the input, the solver tracks coordinates of each galaxy, and for each row and column a *1* if it is empty and a *0* if not. At the end we sum for each pair of galaxies the values for each row and column between their coordinates *+1* to get the sum of their (Manhattan) distances.
This approach was trivial to adapt for part 2, since all that was needed was another factor that had to be multiplied with the values tracked for the rows and columns before applying the *+1*.
2024-06-26 09:32:52 +02:00
### Day 13: Point of Incidence
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/13>, :white_check_mark: Solver: [`UPointOfIncidence.pas`](solvers/UPointOfIncidence.pas)
While going through each line, the algorithm keeps updating two lists of mirror candidates, one for horizontal and one for vertical mirrors. For horizontal mirrors, a new candidate is added whenever two consecutive lines are identical. After it is added, new lines are each compared against the potentially mirrored earlier line, until the candidate is discarded or the last line successfully mirrored.
For vertical mirrors, all candidates are added during processing of the first line, based on whether they mirror the first line or not. While processing further lines, each candidates is verified against each line or discarded.
To solve part 2, each candidate is allowed one character switch, and tracks whether that switch happened or not to successfully mirror all processed lines. If a second character switch is required or no switch had occurred at the end, the candidate is discarded. By setting this tracker as if a switch had already happened even for new candidates, both parts of the puzzle can be solved simultanously.
2024-06-26 09:32:52 +02:00
### Day 14: Parabolic Reflector Dish
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/14>, :white_check_mark: Solver: [`UParabolicReflectorDish.pas`](solvers/UParabolicReflectorDish.pas)
I spent too much time on this one. I had originally implemented a relatively naive algorithm that would do the tilting of the platform by operating directly the string list, swapping out round rocks as it went, which seemed quite slow.
So I reimplemented the whole thing with proper data structures consisting of lists of non-empty intervals between cube-shaped rocks, and lists of rows and columns of rounded rocks, between which the algorithm would alternate, to facilitate a faster computation without string manipulation. This improved the performance of the algorithm, but unfortunately not as much as I had expected.
An essential revelation to make any algorithm for this work is that the formations of the rounded rocks on the platform repeat while spinning it 1,000,000,000 times, so once a previous formation is discovered, the calculation can be short-cut significantly.
2024-06-26 09:32:52 +02:00
### Day 15: Lens Library
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/15>, :white_check_mark: Solver: [`ULensLibrary.pas`](solvers/ULensLibrary.pas)
Pretty straight-forward implementation of a Hashmap with a custom Hash function.
2024-06-26 09:32:52 +02:00
### Day 16: The Floor Will Be Lava
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/16>, :white_check_mark: Solver: [`UFloorWillBeLava.pas`](solvers/UFloorWillBeLava.pas)
The solver calculates how a beam traverses through the grid until it is reflected outwards. Every time it hits a splitter, a new beam is put on a stack to be calculated later. I found the difficulty to be finding a good way to track how a beam has already travelled through the grid. This seems essential to detect when the calculation for a part of the beam can be aborted, since splitters can create loops. However, two beams could pass through the same tile in different ways without forming a loop. I settled for tracking four energy states for each tile of the grid, one being "not energized", two describing generically the two directions a beam could travel through some tiles, and one for the combination of those two directions. This energy state of the current field and the beam's direction could then be used to abandon a beam early, before it leaves the boundaries of the grid.
Once this was solved for one starting beam in part 1, I just iterated over all possible starting beams to find the maximum for part 2.
2024-06-26 09:32:52 +02:00
### Day 24: Never Tell Me the Odds
2024-05-27 03:10:14 +02:00
2024-06-26 09:32:52 +02:00
:mag_right: Puzzle: <https://adventofcode.com/2023/day/24>, :white_check_mark: Solver: [`UNeverTellMeTheOdds.pas`](solvers/UNeverTellMeTheOdds.pas)
2024-05-27 03:10:14 +02:00
While I found part 1 quite trivial, part 2 left me with the feeling that my approach might be mad. Eventually, I managed to find the ray hitting all other rays by solving the general equation system for three known and one unknown rays with some shortcuts for this particular problem, for example assuming the existence of a unique solution. However, this involved excessive manual pre-calculations, arbitrary length integer arithmetic, and a root finder for integer polynomials, all implemented by myself without additional third-party libraries.
2024-05-27 03:10:14 +02:00
2023-12-01 23:04:26 +01:00
## License
2024-05-27 03:10:14 +02:00
Copyright (C) 2023-2024 Stefan Müller
2023-12-01 23:04:26 +01:00
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.