These are my solutions to Advent of Code 2021, a series of 25 programming puzzles.
You can install adventofcode21 from GitHub with:
# install.packages("devtools")
devtools::install_github("tjmahr/adventofcode21")
But you probably shouldn't do that.
The package infrastructure was automatically generated for each day using
my aoc package and its use_day(day, year)
function.
The /R
folder contains the R functions I wrote for each day. I used
some light test-driven development for the puzzles. That is, each puzzle
description provides some example inputs and outputs. Before tackling
the main test input, I write a unit-test in /tests
that confirms that
my solution can correctly reproduce the examples. The /inst
directory
contains the code to handle the main test input for each day.
I limited the amount of package dependencies used for these puzzles to maximize future compatibility and to make sure that it is mostly my code that solves the problems. For example, if a puzzle requires answering questions about the data in a tree-like structure, it would be kind of cheating for me to find a library for building and traversing trees to tackle the problem. It’s advent of code, not advent of load.
I have allowed myself to use:
In the past I have allowed myself to use magrittr, rlang and stringr, but
the native pipe |>
eliminates the need for magrittr and some grit
eliminates the need for the others.
I’ve put my R source code under a GPL-3 license. It should not apply to the puzzle descriptions in the code comments at the top of each file. I did not write those descriptions.
Here are the programming tasks and techniques I used for the various puzzles.
00a/b Write puzzle description like this: Period separated strategies. Enumerated.
16a/b Decode packets and run code inside of them: Recursion (parsing). Creating and evaluating R code.
23a/b Solve a tile sliding game: No code. Solved by hand (see inst/notes-day-22b-moves.R).
Book-keeping: basic programming where I keep track of some changing state like a position in a vector.
Math: Studying the problem and using math to find a shortcut that lets me skip some computations.
Creating and evaluating R code: Constructing R function calls from the input and evaluating them in R. Converting the problem into running an R script.
Here are some functions that have I discovered, rediscovered, or otherwise appreciate somewhat more from these exercises:
which()
but with arr.ind = TRUE
for easier matrix subsettingsimplify2Array()
for combining a list of vectors into a matrix..1
, ..2
for creating functions like v_eq <- function(...) as.numeric(..1 == ..2)
complete.cases()
intersect()
lengths()
modifyList()
outer()
prod()
strtoi()
chartr()
Find() and Position()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.