Introduction
The Day 2 tasks seems to be pretty straightforward - we only need to check the defined rules for given passwords according to task description. We will try to express the solution in pretty straightforward way by recalling some less known Kotlin functions.
Solution
We can present the whole solution in a few lines of code which use already defined inline fun <reified T> String.value(): T
in order to neatly convert input parts to actual numbers.
|
|
Worth noting
Let’s deep dive into two snippets of this solution to improve our familiarity with Kotlin:
- Keyword
in
can be used not only to iterate over a loop, but also to check if the value belongs to something. Basically, we need to haveoperator fun T.contains(element: U): Boolean
in order to be able to check if some valueu: U
belongs to some other valuet: T
by simply callingu in t
. It’s a great moment to remind the Kotlin’s documentation about operators and their usages - using them in our code can make it not only shorter but also more readable and easier to explain for non-programming people. - Notice the usage of
xor
function in 2nd part of the solution. It’s not common to see it in code from my perspective because it can be expressed e.g. as(b1 && !b2) || (!b1 && b2)
with the standard operators, but we should remember the KISS rule and try to express our thoughts in the most readable way - it can be done with this pretty function in really neat way. Additionally, we can see some other functions predefined forBoolean
likeand
ornot
and revisit the Kotlin’s documentation about infix notation - they allow creating really readable code with almost no extra overhead.