0

Sorry if this is super basic, I'm just getting started with programming in general.

So I have this list, I've managed to display an object from it randomly when the user clicks on a button.

Here is the code that does this:


val listOfElement = listOf<String>(
"test", "test2", "test 3")

fun generateElement (view: View) {

tvDisplay.text = listOfElement.random()
} 

It works fine but the problem is that an object (e.g "test3") can be displayed twice before it goes through the rest of the list.

So basically I'd like to:

  • Only display each object only once BUT when all the objects have been displayed, then it should start again randomly.

Thanks again and sorry if this not appropriate - it's my first time on stackoverflow!

1
  • Do you need to get each of the elements separately, or could you provide them together? Either way, I'd look at shuffle()ing the list. Commented May 4, 2020 at 21:45

1 Answer 1

1

You can make a copy of your list and them remove the random element, then repopulate the list when it's empty:

val listOfElement = listOf<String>(
    "test", "test2", "test 3")

val copy = mutableListOf<String>()

fun generateElement (view: View) {
    if (copy.isEmpty()) {
        copy.addAll(listOfElement)
    }
    val random = copy.random()
    copy.remove(random)
    tvDisplay.text = random
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much ! It works perfectly. Would you able to explain me why I need to make a copy of my list here? Also, I'm having difficulties grasping the mutable list concept. I've been reading about it but it doesn't make totally sense in my head yet.
You want to be able to restore the list when you have iterated over all elements, so you have to keep the original list around so you can go back to it when you've exhausted the entries. A MutableList allows you to update it (add, remove, sort, ...) while a List is immutable - can't be changed after it's been created.
This might be easier to follow if you renamed copy to availableElements. It is not really a copy of the other list except during the brief moment before it pulls the first item from it.
Thank you both, this is so useful. Everything makes sense now!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.