有没有一种简单的方法可以将数组/列表中的每个元素相互乘以 - Kotlin?

Is there an easy way to multiply each element with each other in array / list - Kotlin?

提问人:Bob Redity 提问时间:7/14/2022 更新时间:7/15/2022 访问量:760

问:

我有/或者它可能是一个有没有一种简单的方法可以将每个元素相互相乘,比如?{1,2,3}list<Int>1*2 , 1*3, 2*3

科特林

评论

1赞 Tenfour04 7/14/2022
生成的列表是否具有六个元素,因此它具有所有排列?对于这样具体的东西,没有内置函数,如果这就是你所说的简单的话。

答:

5赞 hotkey 7/14/2022 #1

这应该有效,因为您可能不想包含像 和 这样的重复项items[i] * items[j]items[j] * items[i]

val items = listOf(1, 2, 3, 4)

val result = items.flatMapIndexed { index, a -> 
    items.subList(index + 1, items.size).map { b -> a * b }
}

println(result) // [2, 3, 4, 6, 8, 12]
  • flatMapIndexed 通过计算索引和项上的 lambda 为每个元素构建一个列表,然后连接这些列表。items
  • subList 是获取特定范围内项的有效方法:从下一个索引开始,直到列表末尾。

评论

2赞 gidds 7/14/2022
您可以通过简单地删除 .+ 1
3赞 deHaar 7/14/2022 #2

你可以尝试老式的方式:嵌套循环

fun main(args: Array<String>) {
    val list = listOf( 1, 2, 3 )
    
    for (i in list.indices) {
        for (j in (i + 1) until list.size) {
            println("${list[i]} * ${list[j]} = ${list[i] * list[j]}")
        }
    }
}

此代码的输出:

1 * 2 = 2
1 * 3 = 3
2 * 3 = 6
0赞 cactustictacs 7/15/2022 #3

如果你确实想要所有的排列(所有可能的排序),你可以做这样的事情:

val result = with(items) {
    flatMapIndexed { i, first ->
        slice(indices - i).map { second -> // combine first and second here }
    }
}

Slice 允许您为要拉取的元素提供索引列表,因此您可以轻松地排除当前索引并获取所有其他元素来组合它。也需要,所以你也可以做来获得组合(每次配对)功能。IntRangeslice(i+1 until size)

不如热键的版本高效(因为它不会复制),但您可以通过这种方式获得两种行为,所以我想我会提到它!但是,如果我要制作一个可重用的函数而不是一个快速的单行函数,我可能会使用嵌套 for 循环的方法,它既高效又容易针对任何一种行为进行调整subListdeHaar