How to select N unique random indices from an existing array in Kotlin

1 Answer

0 votes
/*
    Select N unique random indices from an existing array in Kotlin.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Build a list of indices: 0, 1, 2, ..., size-1.
    - Shuffle the list using shuffled() (Fisher–Yates internally).
    - Take the first N shuffled indices — guaranteed unique.
    - Return those indices to the caller.
*/

/** Return N unique random indices */
fun pickUniqueIndices(arraySize: Int, count: Int): List<Int> {
    if (count > arraySize) {
        throw IllegalArgumentException("Cannot pick more unique indices than array size.")
    }

    // Build index list
    val indices: List<Int> = (0 until arraySize).toList()

    // Shuffle and take first N
    return indices.shuffled().take(count)
}

fun main() {
    // Example array
    val data: IntArray = intArrayOf(
        5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6
    )

    val n: Int = 6 // number of unique indices to pick

    // Get unique random indices
    val indices: List<Int> = pickUniqueIndices(data.size, n)

    // Print results
    println("Random unique indices and their values:")
    for (idx in indices) {
        println("index $idx -> value ${data[idx]}")
    }
}


/*
run:

Random unique indices and their values:
index 8 -> value 58
index 9 -> value 61
index 12 -> value 5
index 15 -> value 90
index 7 -> value 5
index 14 -> value 83

*/

 



answered Sep 12 by avibootz

Related questions

...