Introduction
We start with Day 1 for which we can show two really different approaches and the final decision which one could be used in production code should be made depending on the expected inputs for our program and the expected readability of the code in our codebase.
Brute force approach
We start with naive approach to solve the task and see that it’s enough for our input data to get the proper answer in really short time.
|
|
The problem is that the complexity of these approaches is $O(n^2)$ and $O(n^3)$. From my point of view this approach seems to be the most readable despite maybe not being Kotlin idiomatic. We just wrote really concise and readable code that simply solves our problem and get the answer.
Smarter approach
Let’s think about rephrasing our problem statement - maybe we should check if for any of input number $n$ there is some other number that equals $2020 - n$. We can express this approach also with just a few lines of Kotlin code for the first part of the task
|
|
But what is needed for it to work we need to define countOccurrences
function with some pretty simple but really useful DefaultMap
class
which could be used for future tasks too.
|
|
Some similar but less readable approach can also be used to find the solution for 3 numbers - we will skip it anyway as we already got our advent stars, and it’s definitely enough advent coding for today.