#
# 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.
#
#---------------------------------------------------------------
# Build a frequency map: value -> count
#---------------------------------------------------------------
def build_frequency_map(data)
# tally returns a Hash: value => count
data.tally
end
#---------------------------------------------------------------
# Collect values that appear exactly once
#---------------------------------------------------------------
def collect_unique_values(data, freq)
# Select only values whose frequency is exactly 1
data.select { |value| freq[value] == 1 }
end
#---------------------------------------------------------------
# Randomly select N values from the unique array
#---------------------------------------------------------------
def select_random_unique(unique, n)
# Clamp n to available unique values
n = [n, unique.length].min
# Shuffle and take first n elements
unique.shuffle.take(n)
end
#---------------------------------------------------------------
# Print helper
#---------------------------------------------------------------
def print_values(values)
puts values.join(" ")
end
#---------------------------------------------------------------
# Main program
#---------------------------------------------------------------
data = [
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
freq = build_frequency_map(data)
# Step 2: Collect values that appear exactly once
unique_values = collect_unique_values(data, freq)
# Step 3: Choose how many unique random values to select
n = 5
# Step 4: Select N random unique values
random_selection = select_random_unique(unique_values, n)
# Step 5: Print results
puts "Values that appear exactly once:"
print_values(unique_values)
puts "\nRandom selection (#{n} values):"
print_values(random_selection)
#
# run:
#
# Values that appear exactly once:
# 12 33 59 61 17 74 83 90 1
#
# Random selection (5 values):
# 90 59 83 12 17
#