Daniele B
10/11/2020, 12:17 AMval numbers = listOf(1,2,4,8,11,14)
I would like to create a new list with the differences between a number and the one that is 2 indexes before it. In this case the results would be:
val differencesTwoIndexesApart = listOf(3,6,7,6)
is there an easy way to do that with Kotlin high-order functions?
or is an imperative for loop the best way?akatkov
10/11/2020, 12:28 AMval differencesTwoIndexesApart = numbers.windowed(3).map { it.last() - it.first() }
ephemient
10/11/2020, 4:38 AMnumbers.zip(numbers.drop(2)) { a, b -> b - a }
Vampire
10/11/2020, 9:30 AMephemient
10/11/2020, 9:45 PMephemient
10/11/2020, 9:47 PMVampire
10/11/2020, 10:08 PMzipWithNext
, you are totally right of courseDaniele B
10/12/2020, 3:37 AMephemient
10/12/2020, 5:39 AM.windowed()
creates a new list for every window, while .drop()
creates a copy of the trailing listephemient
10/12/2020, 5:40 AMList<T>
specifically, that could be optimized to .slice(2 until size)
which returns a view of the trailing list instead of a copyephemient
10/12/2020, 5:42 AMList(numbers.size - 2) { numbers[it + 2] - numbers[it] }
Daniele B
10/16/2020, 2:02 AMwindowed()
create a new list for every window or is it also a view?ephemient
10/16/2020, 2:11 AMephemient
10/16/2020, 2:18 AMDaniele B
10/16/2020, 2:19 AMephemient
10/16/2020, 2:25 AM