/*
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 Foundation
// ---------------------------------------------------------------
// Build a frequency map: value -> count
// ---------------------------------------------------------------
func buildFrequencyMap(_ data: [Int]) -> [Int: Int] {
var freq: [Int: Int] = [:]
// Count occurrences
for value in data {
freq[value, default: 0] += 1
}
return freq
}
// ---------------------------------------------------------------
// Collect values that appear exactly once
// ---------------------------------------------------------------
func collectUniqueValues(_ data: [Int], freq: [Int: Int]) -> [Int] {
data.filter { value in freq[value] == 1 }
}
// ---------------------------------------------------------------
// Randomly select N values from the unique array
// ---------------------------------------------------------------
func selectRandomUnique(_ unique: [Int], n: Int) -> [Int] {
let limit = min(n, unique.count) // clamp N
return Array(unique.shuffled().prefix(limit))
}
// ---------------------------------------------------------------
// Print helper
// ---------------------------------------------------------------
func printValues(_ values: [Int]) {
print(values.map(String.init).joined(separator: " "))
}
// ---------------------------------------------------------------
// Main program
// ---------------------------------------------------------------
let data: [Int] = [
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
let freq = buildFrequencyMap(data)
// Step 2: Collect values that appear exactly once
let uniqueValues = collectUniqueValues(data, freq: freq)
// Step 3: Choose how many unique random values to select
let n = 5
// Step 4: Select N random unique values
let randomSelection = selectRandomUnique(uniqueValues, n: n)
// Step 5: Print results
print("Values that appear exactly once:")
printValues(uniqueValues)
print("\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):
83 61 12 1 33
*/