Search code examples
androidkotlinrandommutablelist

How to remove a random element after being printed


fun main() {
    val oda1 = mutableListOf("kadir", "talha", "oğuz")
    println("first winner is ${oda1.random()}") 
}

I can print a random name with this method, but I want to continue to get a second random name too(rather than a selected one). My question is; How can I remove the printed string element, and get a random name with remained names?


Solution

  • You need to save the current random name to remove it from the list after print it

    fun main() {
        val oda1 = mutableListOf("kadir", "talha", "oğuz")
        val winner = oda1.random()
        println("first winner is $winner")
        oda1.remove(winner)
        println("Other winners $oda1")
    }
    

    output

    first winner is kadir

    Other winners [talha, oğuz]