How do I make random groups from a list in Kotlin?

Viewed 218

This is my first time using Kotlin so really unfamiliar with syntax. I'm attempting to make a program that will read a list of names from the user and the number of groups and then produce a randomized grouping of those names. If the number of names is not divisible exactly by the number of the groups, some groups will be shorter. Right now, I'm stuck on trying to divide my list into even groups. I was thinking that I should make a subList, but 1) Not sure how to go about this and 2) Not sure if that's the right method

This is all that I have right now:

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
}``
2 Answers

if you want uniform distribution by groups you can write something like that:

val groups = Array(groupsNum) { mutableListOf<String>() }
for ((i, name) in shuffledNames.withIndex()) {
    groups[i % groupsNum].add(name)
}

I think you can use chunked

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