gpt4 book ai didi

kotlin - 两个列表的所有可能组合

转载 作者:IT老高 更新时间:2023-10-28 13:46:58 24 4
gpt4 key购买 nike

鉴于我有两个列表:

val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")

我想要它们元素的所有可能组合

0a、1a、2a、0b

有没有比这样更优雅的方式:

ints.forEach { int -> 

strings.forEach { string ->


println("$int $string")

}

}

最佳答案

您可以基于 flatMap stdlib 函数编写这些扩展函数:

// Extensions
fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> {
return cartesianProduct(other, { first, second -> first to second })
}

fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> {
return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } }
}

// Example
fun main(args: Array<String>) {
val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")

// So you could use extension with creating custom transformer
strings.cartesianProduct(ints) { string, int ->
"$int $string"
}.forEach(::println)

// Or use more generic one
strings.cartesianProduct(ints)
.map { (string, int) ->
"$int $string"
}
.forEach(::println)
}

关于kotlin - 两个列表的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com