我有一个元素的数组列表,我需要配对组合。
例如。[A, B, C]
将转换为[[A, B], [A, C], [B, C]]
我目前使用正常方法来实现此
for(i in 0 until arr.size-1)
for(j in i+1 until arr.size)
//do stuff with arr[i], arr[j]
,如果我需要两个以上元素的组合,我可能会编写递归功能以执行相同的操作。我关心的是,这种方法仍然是老式的&可能不像
那样功能性kotlin有一种更好的方法来实现这一目标&还可以在不进入递归的情况下组合更多元素?
您可以做的一件事使它更有用,就是将对夫人的消费脱离。
这些对生成器可以用函数sequence
写入:
fun <T> elementPairs(arr: List<T>): Sequence<Pair<T, T>> = sequence {
for(i in 0 until arr.size-1)
for(j in i+1 until arr.size)
yield(arr[i] to arr[j])
}
然后,您可以使用该序列并以不同的方式处理对,例如
fun main() {
elementPairs(listOf('A', 'B', 'C', 'D')).forEach {
println(it)
}
elementPairs(listOf("apple", "desk", "arc", "density", "array"))
.filter { (a, b) -> a.first() == b.first() }
.forEach { println("Starting with the same letter: $it") }
}
您可以在这里尝试:https://pl.kotl.in/dj9maiatc
val arr = arrayListOf("A", "B", "C", "D")
val list= mutableListOf<Pair<String, String>>()
arr.indices.forEach() {
i -> arr.indices.minus(0..i).forEach() {
j -> list.add(arr[i] to arr[j]) }
}
println(list)
输出
[(A, B), (A, C), (A, D), (B, C), (B, D), (C, D)]
,因此被接受的答案创建对。我创建了一个可在任何长度组合到项目的对象。Size-1
class CombinationGenerator<T>(private val items: List<T>, choose: Int = 1) : Iterator<List<T>>, Iterable<List<T>> {
private val indices = Array(choose) { it }
private var first = true
init {
if (items.isEmpty() || choose > items.size || choose < 1)
error("list must have more than 'choose' items and 'choose' min is 1")
}
override fun hasNext(): Boolean = indices.filterIndexed { index, it ->
when (index) {
indices.lastIndex -> items.lastIndex > it
else -> indices[index + 1] - 1 > it
}
}.any()
override fun next(): List<T> {
if (!hasNext()) error("AINT NO MORE WHA HAPPEN")
if (!first) {
incrementAndCarry()
} else
first = false
return List(indices.size) { items[indices[it]] }
}
private fun incrementAndCarry() {
var carry = false
var place = indices.lastIndex
do {
carry = if ((place == indices.lastIndex && indices[place] < items.lastIndex)
|| (place != indices.lastIndex && indices[place] < indices[place + 1] - 1)) {
indices[place]++
(place + 1..indices.lastIndex).forEachIndexed { index, i ->
indices[i] = indices[place] + index + 1
}
false
} else
true
place--
} while (carry && place > -1)
}
override fun iterator(): Iterator<List<T>> = this
}
fun main() {
val combGen = CombinationGenerator(listOf(1, 2, 3, 4), 3)
combGen.map { println(it.joinToString()) }
}
上面的答案对于Kotlin标准来说确实是详细的。可以使用更简洁的IMO来解决这:
fun main() {
val letters = "ABC".toList();
val pairs = letters
.flatMap {first -> letters
.filter{second -> !first.equals(second)} // if you want to exclude "identity" pairs
.map{second->first to second }};
println(pairs)
}
val arr = intArrayOf(1, 2, 3, 4) //test array
arr.indices.forEach() {
i -> arr.indices.minus(0..i).forEach() {
j -> println("${arr[i]} ${arr[j]}") } }
输出
1 3
1 4
2 3
2 4
3 4