How can I remove duplicated consecutive values in ...
# advent-of-code
m
How can I remove duplicated consecutive values in a list by a specific field? [{a,1},{b,1},{c,2},{d,2},{e,1}] -> [{a,1}{c,2},{e,1}]
although if that is exactly your use case, something simple like
Copy code
var previousValue: Int? = null
list.filter { (key, value) ->
    value != previousValue.also { previousValue = value }
}
will work, even if it's "cheating" a bit by using mutable state outside the lambda
m
hum, nothing with reduce or fold that (even if it under the hood might do the same) looks cleaner?
f
don't know about the "looks cleaner" part, but:
Copy code
listOf('a' to 1, 'b' to 1, 'c' to 2, 'd' to 2, 'e' to 1)
            .fold(emptyList<Pair<Char, Int>>()) { acc, el ->
                if (el.second != acc.lastOrNull()?.second) {
                    acc + el
                } else {
                    acc
                }
            }
p
m
Thanks for all the solutions. Never used windowed, so something new to learn.