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

1 Answer

0 votes
import scala.util.Random

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

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

// Return N unique random indices
def pickUniqueIndices(arraySize: Int, count: Int): Seq[Int] = {
  if (count > arraySize)
    throw new IllegalArgumentException("Cannot pick more unique indices than array size.")

  // Build index list
  val indices: Seq[Int] = 0 until arraySize

  // Shuffle and take first N
  Random.shuffle(indices).take(count)
}

@main def main(): Unit = {
  // Example array
  val data: Array[Int] = Array(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: Seq[Int] = pickUniqueIndices(data.length, N)

  // Print results
  println("Random unique indices and their values:")
  indices.foreach { idx =>
    println(s"index $idx -> value ${data(idx)}")
  }
}



/*
run:

Random unique indices and their values:
index 5 -> value 33
index 4 -> value 5
index 0 -> value 5
index 3 -> value 19
index 11 -> value 3
index 14 -> value 83

*/

 



answered Sep 12 by avibootz

Related questions

...