/*
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 kotlin.random.Random
// ---------------------------------------------------------------
// Build a frequency map: value -> count
// ---------------------------------------------------------------
fun buildFrequencyMap(data: IntArray): Map<Int, Int> {
// groupingBy is defined on Iterable, so we convert IntArray to List<Int>
return data.toList().groupingBy { it }.eachCount()
}
// ---------------------------------------------------------------
// Collect values that appear exactly once
// ---------------------------------------------------------------
fun collectUniqueValues(data: IntArray, freq: Map<Int, Int>): List<Int> {
return data.filter { value -> freq[value] == 1 }
}
// ---------------------------------------------------------------
// Randomly select N values from the unique list
// ---------------------------------------------------------------
fun selectRandomUnique(unique: List<Int>, n: Int): List<Int> {
val limit = minOf(n, unique.size) // clamp N
return unique.shuffled(Random).take(limit)
}
// ---------------------------------------------------------------
// Print helper
// ---------------------------------------------------------------
fun printValues(values: List<Int>) {
println(values.joinToString(" "))
}
// ---------------------------------------------------------------
// Main program
// ---------------------------------------------------------------
fun main() {
val data = intArrayOf(
5, 12, 5, 19, 5, 33, 19, 5, 8, 8, 8, 59, 61, 17, 3, 5, 3, 74, 83, 90, 3, 1
)
// Step 1: Build frequency map
val freq = buildFrequencyMap(data)
// Step 2: Collect values that appear exactly once
val uniqueValues = collectUniqueValues(data, freq)
// Step 3: Choose how many unique random values to select
val n = 5
// Step 4: Select N random unique values
val randomSelection = selectRandomUnique(uniqueValues, n)
// Step 5: Print results
println("Values that appear exactly once:")
printValues(uniqueValues)
println("\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):
17 74 90 1 83
*/