2

I want to generate random numbers when clicking a button and every random number only occurs once. Now, I have an array in which I store all the generated numbers so I can check whether or not this number has been previously generated. However, when this is the case I want it to generate another number which has not been previously generated. I have been struggling but can't find the right code for this.

var arraylist = ArrayList<Int>()

nextnumberbutton.setOnClickListener {
    val rand = java.util.Random().nextInt(75)
    if (arraylist.contains(rand)) {
        kotlin.run { nextnumberbutton }
    } else {
        numbertextview.text = rand.toString()
    }
    arraylist.add(rand)
}

1 Answer 1

4

run { nextnumberbutton } doesn't do anything. It's a lambda that will simply return Unit.

Supposing you did call the click listener again when a repeated number is found, you would still be adding the number to the list again, since you don't return from the function early. So you would end up with duplicates in your list.

Your strategy could be done with a while loop instead of calling the whole function again when a duplicate is picked. e.g. you could use while (rand !in arrayList) rand = Random.nextInt(75). However, this has the potential to take longer and longer to pick the number as you approach the limit of values because it is simply guessing numbers and has to try again if the number is already picked.

A better strategy would be to start with a set of all the numbers and remove from this set as you go. You also need to handle the case of when all numbers are picked, perhaps by showing a message to the user.

val unpickedNumbers = (0..75).toMutableSet()

nextnumberbutton.setOnClickListener {
    if (unpickedNumbers.isEmpty()) {
        Toast.makeText(context, "All numbers already picked", Toast.LENGTH_LONG).show()
        return
    }
    val rand = unpickedNumbers.random()
    numbertextview.text = rand.toString()
    unpickedNumbers.remove(rand)
}
4
  • Thanks! However, context seems to be unknown and becomes red.
    – John
    Commented Apr 24, 2020 at 14:31
  • If this is in an Activity rather than a Fragment, you can use this or baseContext instead of context.
    – Tenfour04
    Commented Apr 24, 2020 at 14:33
  • Is there any way I can let it go again? Now it stays in the screen where it says every number is picked.
    – John
    Commented Apr 24, 2020 at 14:58
  • You mean start all over? You could put in the if block: unpickedNumbers.addAll(0..75) to reset it.
    – Tenfour04
    Commented Apr 24, 2020 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.