我给出了一个整数列表。我需要始终映射以下两个元素以进一步推进。如果输入列表包含无效的元素计数,则应删除最后的元素。下面是一个例子:
[1, 2, 3, 4, 5, 6, 7] //Input
[(1, 2), (3, 4), (5, 6)] //Output
Run Code Online (Sandbox Code Playgroud)
我写信给函数以获得想要的输出,但我认为它们都是低效的。
首先,我用函数式方法尝试了它。但是它需要两个过滤器调用和一个对结果列表的 zip 调用。所以它在entier列表上迭代2.5次。
Two imrpove this I tried a iterative approach. It only iterates once over the list and is possibly the fastest version. But it uses multiple mutable variables/lists. Also it is not as easy to understand as the functinal approach. (And it breaks the cleaness of the rest of the code)
fun main(args: Array<String>) {
mapFunctional()
mapIterative()
}
fun mapFunctional() {
val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val output: List<Pair<Int, Int>> = list.filterIndexed { index, _ ->
index % 2 == 0
}.zip(list.filterIndexed {
index, _ -> index % 2 == 1
})
println(output)
}
fun mapIterative() {
val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val output: MutableList<Pair<Int, Int>> = mutableListOf()
var index = 0
while (index < list.size - 1) {
output.add(list[index++] to list[index++])
}
println(output)
}
Run Code Online (Sandbox Code Playgroud)
Is their a good (efficient) way to achieve this in a functinal aprroach or is it only possible with a classic loop?
如果你想要一个List<Pair>,你可以使用标准库调用来调用这个被调用的windowed.
val myList = listOf(1, 2, 3, 4, 5, 6, 7)
val listOfPairs = myList.windowed(2, 2).map { Pair(it[0], it[1]) }
// [(1, 2), (3, 4), (5, 6)]
Run Code Online (Sandbox Code Playgroud)
该windowed函数将返回 a List<List<Int>>,因此您必须将内部映射List<Int>到 a Pair<Int, Int>。windowed默认情况下,该功能将删除部分窗口。
| 归档时间: |
|
| 查看次数: |
2701 次 |
| 最近记录: |