kotlinmutablelist

Kotlin. How to fill each line in a list with 5 unique numbers from 1 to 90?


I have a list of 3 lines:

private val line1 = mutableListOf<Int>()
private val line2 = mutableListOf<Int>()
private val line3 = mutableListOf<Int>()
val card = mutableListOf(line1, line2, line3)

I need to fill each line with 5 unique numbers from 1 to 90, how to do it?

I tried flow, but it doesn't work, because numbers in each line are the same. And i need only 5 unique numbers in each line.

class Card {

    private val line1 = mutableListOf<Int>()
    private val line2 = mutableListOf<Int>()
    private val line3 = mutableListOf<Int>()

    val card = mutableListOf(line1, line2, line3)

    init {
        runBlocking {
            launch {
                Generator.flow.collect {
                    card.forEach { line ->
                        line.add(it)
                    }
                }
            }
        }
    }
}

Solution

  • import kotlin.random.Random
    import kotlin.random.nextInt
    
    val result1 = MutableList(3) {
      generateSequence { Random.nextInt(1..90) }
        .distinct()
        .take(5)
        .toMutableList()
    }
    
    val result2 = generateSequence { Random.nextInt(1..90) }
      .distinct()
      .take(15)
      .chunked(5) { it.toMutableList() }
      .toMutableList()
    

    The first version will create 3 lists with each 5 elements unique within the respective list. The second version will create 3 lists with 15 unique elements in 3 lists at each 5 elements.

    Edit: changed both version to return MutableList<MutableList>.