gschauer / advent-of-code-2022

my solutions for https://adventofcode.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

My Advent of Code Solutions

Why Bash?

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

Test-Driven Development (TDD)

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.

Status

About

my solutions for https://adventofcode.com/

License:Apache License 2.0


Languages

Language:Shell 84.8%Language:Go 15.2%