/*
Select N unique random indices from an existing array in JavaScript.
Return the indices and print both the index and the corresponding value.
Approach:
- Build an array of indices: 0, 1, 2, ..., size-1.
- Shuffle the indices using a random comparator inside sort().
(This is expressive and fine for moderate-sized arrays.)
- Take the first N shuffled indices — guaranteed unique.
- Return those indices to the caller.
*/
// Return N unique random indices
function pickUniqueIndices(arraySize, count) {
if (count > arraySize) {
throw new Error("Cannot pick more unique indices than array size.");
}
// Build index list
const indices = Array.from({ length: arraySize }, (_, i) => i);
// Shuffle indices
indices.sort(() => Math.random() - 0.5);
// Return first N indices
return indices.slice(0, count);
}
// Example array
const data = [5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6];
const N = 6; // number of unique indices to pick
// Get unique random indices
const indices = pickUniqueIndices(data.length, N);
// Print results
console.log("Random unique indices and their values:");
for (const idx of indices) {
console.log(`index ${idx} -> value ${data[idx]}`);
}
/*
run:
Random unique indices and their values:
index 9 -> value 61
index 3 -> value 19
index 2 -> value 5
index 6 -> value 47
index 5 -> value 33
index 4 -> value 5
*/