https://kotlinlang.org logo
Title
d

Daniel

11/10/2019, 10:44 AM
Might there be a better way to achieve this?
val elementChanges = listOf("a", "b", "b").zipWithNext { a, b ->
            if(b != a) 1 else 0
        }.sum()
I try to get the count of "changes" in a list in relation to one element to the next: Here for example I see that there is a change from "a" to "b", but after that there are no changes anymore "b" to "b"
p

Pavlo Liapota

11/10/2019, 11:28 AM
Looks good to me. Other ways to write it would be:
listOf("a", "b", "b")
    .zipWithNext { a, b -> a != b }
    .count { it }
listOf("a", "b", "b")
    .zipWithNext()
    .count { (a, b) -> a != b }
1
d

Daniel

11/10/2019, 12:29 PM
Thank you for your suggestions! They are also good possibilities
m

Milan Hruban

11/10/2019, 8:54 PM
I would probably do
listOf("a", "b", "b")
    .windowed(size = 2, step = 1)
    .count { it.distinct().size == 2 }
because then the "windowSize" (2 in this case) could be extracted to parameter
d

Daniel

11/11/2019, 7:24 PM
Also a good option, thank you!