Advent of Code Day 4 : Kotlin TIL - require, flatMapIndexed!

How I solved Advent of Code day 4, live, and what I learned from it.

Advent of Code Day 4 : Kotlin TIL - require, flatMapIndexed!

As usual, my first quick and dirty attempt at the challenge, followed by a (hopefully) better version with a list of things I learned during the day :)!

See the repository on Github for the code :) and the megathread for all entries.

First version

Full video on Youtube:

Here is a quick giphy for you to enjoy :)

Time : 1h05 minutes

Here is my first version of the code :

Even though I am happy to be going through a Data class, this code is full of string comparisons and repetitions. I am also not happy with the null handling as it is done now.

It is probably OK for a quick and dirty version but we have to do much better!

Final Version

Still on the long side of things, but overal I am pretty happy of the results, because I've learnt lots of stuff again. Keep in mind that this is a solution I created alone, and that I'm happy with. I don't pretend to have the best solution. I am happy if it runs smooth, and if I leverage some capabilities of the language. My solutions are not optimized for processing time :).

I'm still finding that code a bit more convulated than it should, but I like the power we can get out of the language features we use!

Learnings of the day!

Let's go through things, there are quite a lot! In order of when I needed them :

  • I wanted to find a clean way to run through the lines and have each set of data on a single line, nicely sorted by key in order to use regexp later. I found a nice way to do it functionally but someone came up with something better using a combination of flatMapIndexed and windowed Quite neat! Overal though, I still think that the for loop version was actually cleaner and easier to understand. I'd keep that one for production code I think
  • I learnt about the require function. It is very handy to validate the input of data classes, and I leverage it in part 2.
  • Again, regexp destructuring that we discovered during Day 2 proved extremely useful! Using it, we can directly create our neat data classes.
  • Last but not least, this is the first day I'm using my new microphone and I'm happy about the increase in sound quality :)

That's it! See you soon for more! Those articles take me quite some time so I'm a bit late with the competition now :)

See the repository on Github for the code :) and the megathread for all entries.

Do you have remarks? I'm curious, let me know on Twitter!