Home > Back-end >  In kotlin, Is there a way to 'roll a die' each time an array is shuffled?
In kotlin, Is there a way to 'roll a die' each time an array is shuffled?

Time:03-11

here is some sample code and what I'm trying to do.... I want to cycle through his list until each of the array items have been displayed, you display by clicking the issue is that the variables d6, d62 and d63 are only 'rolled' once when opening the program even if I put those variables into the shuffle function it still won't roll them again inside the list because the list is just copied into a new list at the program start... how can I roll the dice each time the list is shuffled?

    var countW = 0
    var d6 = Random().nextInt(6)   1
    var d62 = Random().nextInt(6)   1
    var d63 = Random().nextInt(6)   1
    
    var testList = arrayListOf(
    "test $d6",
    "test $d62",
    "test $d63")
    
    var shuffledList = testList.shuffled()
    fun shuf() { shuffledList = testList.shuffled() }
    
        listButton.setOnClickListener {
        if (countW < 1) { shuf() }
        wResult.text = shuffledList.elementAt(countW)
        countW  
        if (countW >= shuffledList.count()) { countW = 0 }
    }
    

CodePudding user response:

I am quite uncertain of what you want exactly. But one thing is clear : the elements of your list are set one time at :

var testList = arrayListOf(
    "test $d6",
    "test $d62",
    "test $d63")

Changing d6, d62 and d63 doesn't update every string element of your ArrayList testList.

I don't know if knowing that resolves your problem, but here is a small (pretty simplistic) code snippet which can make you understand, would that be your problem.

/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
import java.util.Random

fun main() {
    // var countW = 0
    var d6 = Random().nextInt(6)   1
    var d62 = Random().nextInt(6)   1
    var d63 = Random().nextInt(6)   1


    var testList = arrayListOf(
        "test $d6",
        "test $d62",
        "test $d63");

    fun reRand(){
        d6 = Random().nextInt(6)   1
        d62 = Random().nextInt(6)   1
        d63 = Random().nextInt(6)   1
        testList = arrayListOf(
        "test $d6",
        "test $d62",
        "test $d63");
    }


    var shuffledList = testList.shuffled();

    fun shuf() { shuffledList = testList.shuffled() }

    shuf()
    reRand()
    println(shuffledList)
    shuf()
    reRand()
    println(shuffledList)
    shuf()
    reRand()
    println(shuffledList)
    shuf()
    reRand()
    println(shuffledList)
}

You need to regenerate your list everytime, if that's how you want to do it. There are more efficient ways of doing it.

Edit : here is link to the Kotlin playground : https://pl.kotl.in/xRdGELkDb

  • Related