Home > Back-end >  Android studio random item always same values
Android studio random item always same values

Time:11-01

I am codding a quiz application in android studio. But when i run the app, I see always same values. I tried more times. But it doesn't work. (I am using Kotlin Language)

My code:

fun  two_click(view: View)
{
    val list1 = mutableListOf<String>("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
    var list2 = mutableListOf<String>()
    var random_item : String? = null
    while(true)
    {
        random_item = list1.random().toString()
        if(list2.contains(random_item))
        {
            continue
        }
        else
        {
            list2.add(random_item)
        }

        if(list2.size == 4)
        {
            break
        }
    }
    println(list2)
}

When I run the app, my outputs always same:

Go outputs

I am trying random item when i run the app without same outputs. How can i fix this code ?

CodePudding user response:

I am not sure that I understood your goals correctly but...

The random numbers generator is pseudo-random. It means that for each start of the program it will generate the same values. To fix that, you can use seed, based on which numbers will be generated.

val rand = Random(1) // it will be your seed
random_item = list1.random(rand).toString()

If you always want to provide different outputs and therefore different seeds, you can create seed like this

val rand = Random(System.currentTimeMillis())
  • Related