gpt4 book ai didi

kotlin - 什么功能方法可以帮助我实现速度返回算法?

转载 作者:行者123 更新时间:2023-12-02 12:07:50 25 4
gpt4 key购买 nike

Speedback is the merging of speed-dating with feedback: a 2 min. 1-on-1 talk with all members of a group of people.

I've made a similar question in Computer Science获得有关算法的一些线索,但很难将其转换为函数式编程。

考虑输入:

val team = setOf("alexandre", "sergiu", "joana", "tiago", "susana", "david")

我想做一个循环赛,所有团队成员都必须互相提供反馈。
我想以最大化同时配对数量的方式对人进行分组,以便我们减少总轮数。

所需的输出是:
1st round:
"alexandre" to "sergiu"
"joana" to "tiago"
"susana" to "david"

2nd round:
"alexandre" to "david"
"sergiu" to "tiago"
"susana" to "joana"

3rd round:
...

直到每个人都“约会”每个人。

我有这个:
fun main() {
val team = setOf("alexandre", "sergiu", "joana", "tiago", "susana", "david")

println(team.combinations(2))
}

the output so far is the 15 possible pairs (combinations).然后我不确定使用哪种功能方法来获得上面的输出。我看了 groupBy , associateBy , partition但似乎没有一个合适的 - 或者我在 FP 中太新手了。

最佳答案

我刚转了answer你通过计算机科学堆栈交换进入 Kotlin。

fun <T> roundRobin(list: List<T>): List<List<Pair<T, T>>> {
val n = list.size
return (if (n % 2.0 == 0.0) roundRobinEven(n) else roundRobinOdd(n)).map {
round -> round.map {
(first, second) -> Pair(list[first], list[second])
}
}
}

//For each round (i), (i, n-1) and then Pair((j+i)%(n-1), (n-1−j+i)%(n-1) for the rest
fun roundRobinEven(n: Int): List<List<Pair<Int, Int>>> =
List(n-1) { i -> (1..(n/2-1)).map{ j -> Pair((j+i)%(n-1), (n-1-j+i)%(n-1)) }.plusElement(Pair(i, n-1)) }

//For each round (i), Pair((j+i)%(n), (n−j+i)%(n)) where 1<=j<=(n-1)/2
fun roundRobinOdd(n: Int): List<List<Pair<Int, Int>>> =
List(n) { i -> (1..(n-1)/2).map { j -> Pair((j+i)%n, (n-j+i)%n) } }
你可以像这样使用它。里面的每个列表代表一个回合
val team = listOf("alexandre", "sergiu", "joana", "tiago", "susana", "david")
val rounds = roundRobin(team2)
for (round in rounds) {
println(round)
}
输出:
[(sergiu, susana), (joana, tiago), (alexandre, david)]
[(joana, alexandre), (tiago, susana), (sergiu, david)]
[(tiago, sergiu), (susana, alexandre), (joana, david)]
[(susana, joana), (alexandre, sergiu), (tiago, david)]
[(alexandre, tiago), (sergiu, joana), (susana, david)]
Link to Kotlin playground

关于kotlin - 什么功能方法可以帮助我实现速度返回算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61964447/

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