/*
Goal:
- Select N random values that appear exactly once in the array.
- Values must be globally unique (appear only once in the entire array).
- Return the selected values from a function and print them.
*/
import scala.util.Random
object UniqueRandomSelection {
// ---------------------------------------------------------------
// Build a frequency map: value -> count
// ---------------------------------------------------------------
def buildFrequencyMap(data: Array[Int]): Map[Int, Int] = {
// In Scala 2.13+, mapValues returns a MapView, so we convert to Map explicitly
data
.groupBy(identity) // Map[Int, Array[Int]]
.view // MapView[Int, Array[Int]]
.mapValues(_.length) // MapView[Int, Int]
.toMap // Map[Int, Int]
}
// ---------------------------------------------------------------
// Collect values that appear exactly once
// ---------------------------------------------------------------
def collectUniqueValues(data: Array[Int], freq: Map[Int, Int]): Array[Int] = {
data.filter(value => freq(value) == 1)
}
// ---------------------------------------------------------------
// Randomly select N values from the unique array
// ---------------------------------------------------------------
def selectRandomUnique(unique: Array[Int], n: Int): Array[Int] = {
val count = unique.length
val limit = math.min(n, count) // clamp N
Random.shuffle(unique.toList).take(limit).toArray
}
// ---------------------------------------------------------------
// Print helper
// ---------------------------------------------------------------
def printValues(values: Array[Int]): Unit = {
println(values.mkString(" "))
}
// ---------------------------------------------------------------
// Main program
// ---------------------------------------------------------------
def main(args: Array[String]): Unit = {
val data: Array[Int] = Array(
5, 12, 5, 19, 5, 33, 19, 5, 8, 8, 8, 59, 61, 17, 3, 5, 3, 74, 83, 90, 3, 1
)
val freq = buildFrequencyMap(data)
val uniqueValues = collectUniqueValues(data, freq)
val n = 5
val randomSelection = selectRandomUnique(uniqueValues, n)
println("Values that appear exactly once:")
printValues(uniqueValues)
println(s"\nRandom selection ($n values):")
printValues(randomSelection)
}
}
/*
run:
Values that appear exactly once:
12 33 59 61 17 74 83 90 1
Random selection (5 values):
59 12 61 17 1
*/