/*
Goal:
- Select N random values that appear exactly once in the array.
- The array includes duplicates, but only values with frequency = 1
are eligible for selection.
Approach:
1. Count frequencies using array_count_values().
2. Collect values that appear exactly once.
3. Shuffle the unique list.
4. Take the first N values.
5. Return them and print them.
Notes:
- Uses built-in PHP functions for clarity and efficiency.
- Uses expressive, structured functions.
*/
#---------------------------------------------------------------
# Build a frequency map: value -> count
#---------------------------------------------------------------
function buildFrequencyMap(array $data): array {
// array_count_values returns an associative array: value => count
return array_count_values($data);
}
#---------------------------------------------------------------
# Collect values that appear exactly once
#---------------------------------------------------------------
function collectGloballyUniqueValues(array $data, array $freq): array {
$unique = [];
foreach ($data as $value) {
if ($freq[$value] === 1) {
$unique[] = $value;
}
}
return $unique;
}
#---------------------------------------------------------------
# Randomly select N values from the unique list
#---------------------------------------------------------------
function selectRandomUnique(array $unique, int $N): array {
if ($N > count($unique)) {
$N = count($unique); // clamp
}
// Shuffle the list to randomize order
$temp = $unique;
shuffle($temp);
// Take first N elements
return array_slice($temp, 0, $N);
}
#---------------------------------------------------------------
# Print helper
#---------------------------------------------------------------
function printList(array $list): void {
foreach ($list as $v) {
echo $v . " ";
}
echo PHP_EOL;
}
#---------------------------------------------------------------
# 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 = buildFrequencyMap($data);
# Step 2: Collect values that appear exactly once
$uniqueValues = collectGloballyUniqueValues($data, $freq);
# Step 3: Choose how many unique random values to select
$N = 5;
# Step 4: Select N random unique values
$randomSelection = selectRandomUnique($uniqueValues, $N);
# Step 5: Print results
echo "Values that appear exactly once:\n";
printList($uniqueValues);
echo "\nRandom selection ($N values):\n";
printList($randomSelection);
/*
run:
Values that appear exactly once:
12 33 59 61 17 74 83 90 1
Random selection (5 values):
1 74 83 90 59
*/