Part 1

Problem

In this first part, we are talking about counting the number of times a depth measurement increases from the previous measurement.

First, we will have to parse the list of received measurements and transform it into an array of integers. To do this feel free to look at how it is done in the Utils.kt file.

Then, we use the zipWithNext function whose role is to pair the elements of our list. Let's take the example proposed for today:

[199, 200, 208, ..., 269, 260, 263]

After calling the function, we get:

[
    [199, 200],
    [200, 208],
    ...
    [269, 260],
    [260, 263]
]

Finally, we need to count how many of them match the criterion (a measure of depth increases from the previous measure) using the count function. The count function takes a predicate and if it returns true, the counter is incremented. In our case, we compare if the second element of the pair is greater than the first element of the pair.

Solution

fun part1(input: List<Int>) = input.zipWithNext().count {
    (next, previous) -> next > previous
}

Part 2

Problem

The second part is really similar to the first one, except that instead of taking the values one by one, we group them by three.

For that, we can call the windowed function which create a sliding windowof a given size. Let's take the example proposed for today:

[199, 200, 208, 210, ..., 240, 269, 260, 263]

After calling the function, we get:

[
    [199, 200, 208],
    [200, 208, 210],
    ...
    [240, 269, 260],
    [269, 260, 263]
]

Now we want to sum each new list, fortunately Kotlin have a sum method that can called on iterators. So from the previous list, we now have:

[
    607,
    618,
    ...
    769,
    792
]

And that's awesome because we can reuse our previous function to count how many groups of measures increase from the previous group of measures.

Solution

fun part2(input: List<Int>) = part1(input.windowed(3) { it.sum() })

Conclusion

It was a great first puzzle! Besides being easy to understand, it reminded me how complete the standard Kotlin library was (in addition to being a great language).

+ 2 ⭐️ !!!


Cédric Boirard

Read more posts by this author.