My Advent of Code Solutions
Many people claim that Bash is not a good scripting language. Although, it is available on any Unix system and essential for many CI/CD pipelines. Since it is my favorite scripting language, I took the challenge and implemented most Advent of Code exercises in Bash.
As a matter of fact, Bash has some limitations e.g., no floating point numbers, no multi-dimensional arrays and no sets. Moreover, there are countless pitfalls, which can lead to terrible mistakes.
However, there are some aspects, where Bash really shines e.g.,
string manipulation,
command substitution as well as
builtins for reading files to arrays, and more.
Additionally, tools like
grep
,
sed
,
cut
or
paste
enable concise Bash scripts where general purpose programming languages require multiple statements.
For example, the first exercise implemented in Java would be something like:
int max = 0, curr = 0;
for (var l : Files.readAllLines(Paths.get("input.txt"))) {
if (l.isEmpty()) {
max = Math.max(max, curr);
curr = 0;
} else {
curr += Integer.parseInt(l);
}
}
System.out.println(max);
The same can be achieved in Bash with the following code:
paste -sd + input.txt | sed -E 's/\+\+/\n/g' | bc | sort -r | head -n 1
At the first glance, this seems to be a cryptic command. However, it's pretty straightforward if you break it down piece by piece.
paste -sd + input.txt | # concatenate all lines into a single line, replace '\n' with '+'
sed -E 's/\+\+/\n/g' | # occurrences of "++" means there was an empty line => split them again
bc | # now we have lines like "1+2+3", bc sums up the values in each line
sort -r | # sort the resulting sums in descending order
head -n 1 # pick the first one - the maximum value
Besides implementing the exercises, I intended to apply good engineering practices such as TDD. For some exercises, I used bash_unit to write assertions before writing code. You might know bats, which was the most popular test framework for Bash scripts. bash_unit is an amazing framework, which can even fake external commands to provide the desired output. Moreover, bash_unit tests are ordinary shell scripts, which makes it easy to write tests and maintain them.
25 *
Full of Hot Air24
Blizzard Basin23
Unstable Diffusion22
Monkey Map21 **
Monkey Math20 **
Grove Positioning System19
Not Enough Minerals18 **
Boiling Boulders17
Pyroclastic Flow16
Proboscidea Volcanium15
Beacon Exclusion Zone14 **
Regolith Reservoir13 **
Distress Signal12 **
Hill Climbing Algorithm11 **
Monkey in the Middle10 **
Cathode-Ray Tube9 **
Rope Bridge8 **
Treetop Tree House7 **
No Space Left On Device6 **
Tuning Trouble5 **
Supply Stacks4 **
Camp Cleanup3 **
Rucksack Reorganization2 **
Rock Paper Scissors1 **
Calorie Counting