Home > Enterprise >  kotlin random images without repetition in other imageviews
kotlin random images without repetition in other imageviews

Time:05-29

how can I solve in kotlin, I am about to finish an app but I can't close everything?

the function that I am not good at

the fact is that with three imageviews I would like the image in imageview not to repeat the same figure in imageview 2 and 3 so I would like the list to be one and that there are no duplicates to show between the three imageviews here is the code:

 private lateinit var listId: List<Int>
 
 initializeList()
 
 pickNumber ()

    }

    private fun pickNumber (){
        binding.imageView.setImageResource(listId.random())
        binding.imageView2.setImageResource(listId.random())
        binding.imageView3.setImageResource(listId.random())
        
        
         private fun initializeList() {
        listId = listOf(
            R.drawable.we ,
            R.drawable.wq,
            R.drawable.set,
            R.drawable.opt,
            R.drawable.ups,
        )

with 80 images

CodePudding user response:

As gpunto suggested, you can shuffle the list first and then fetch elements one by one.

private fun pickNumber (){
    val (id1, id2, id3) = list.shuffled()  
    binding.imageView.setImageResource(id1)
    binding.imageView2.setImageResource(id2)
    binding.imageView3.setImageResource(id3)
}

Here I used list destructuring to get first three elements of the list.

Official docs

  • Related