Advent of Code’s inputs are usually provided in a standardised format where the input file can be processed line by line. The last few years I’ve used a custom built function that reads the input file and transforms its lines into a usable format. This allows me to focus on solving the puzzle and not worry about how to read the input each morning.
My read_input
function takes in two three arguments:
day
is the number of the day which is used to define which input file is read. A side effect of this is that it documents at the start of the code file which day’s solution it is.map_fn
is a function (defaulting tostr
which is effectively a no-op) that accepts a line of input as a string and returns a desired data format.example
is a flag that allows me to easily switch between reading the provided example input and the actual puzzle input.
For example, if the input for day 1 is a list of numbers per line like this:
I would read it in as
I can use built-in functions or write my own as long. I often use named tuples as my data structure in these puzzles so for a more complex example, I could do the following:
Writing these input mapper functions as the first thing of the day gives me structure in designing how to map the input and puzzle description into a data structure that would work best. I often go back and change things around as I learn more about the solution once I actually start writing the code.