gpt4 book ai didi

kotlin - 如何从 Kotlin 的列表中创建随机组?

转载 作者:行者123 更新时间:2023-12-04 08:15:23 25 4
gpt4 key购买 nike

这是我第一次使用 Kotlin,对语法非常陌生。我正在尝试制作一个程序,该程序将从用户那里读取名称列表和组数,然后生成这些名称的随机分组。如果名称的数量不能被组的数量整除,则某些组会更短。现在,我坚持尝试将我的列表分成偶数组。我在想我应该做一个 subList,但是 1) 不知道如何去做 2) 不确定这是否是正确的方法
这就是我现在所拥有的:

fun main(args: Array<String>) {
val number1 = Scanner(System.`in`)
print("Enter how many names will be entered: ")
//nextInt() method used to take the next Int value
//and stores into nameNum
val nameNum:Int = number1.nextInt()

val number2 = Scanner(System.`in`)
print("Enter how many groups you want too divide the names into: ")
//nextInt() method used to take the next Int value
//and stores into nameNum
val groupsNum:Int = number2.nextInt()

//test
println("You entered that you have $nameNum number of names")

println("You entered that you have $groupsNum number of groups")

print("Please input the names of group members separated by *two* spaces: ")
val input: String? = readLine() //reads next input for names
val groupNames: List<String> = input!!.split(" ".toRegex()) //separates the names out using two spaces and puts into list
println("These are the names entered: $groupNames ") //test

val shuffledNames = groupNames.shuffled() //shuffling names of list so that a random grouping can be made
println("These are the names shuffled: $shuffledNames") //test

val namesInGroup = nameNum / groupsNum //by dividing number of names NameNum by number of groups groupsNum
//will determine how many names will go in each group
}``

最佳答案

我想你可以用 chunked

val numItem = nameNum / groupsNum + if (nameNum % groupsNum != 0) 1 else 0
val groups = groupNames.chunked(numItem)
println(groups)

关于kotlin - 如何从 Kotlin 的列表中创建随机组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65731121/

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