import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
Select N unique random indices from an existing array in Java.
Return the indices and print both the index and the corresponding value.
Approach:
- Build a list of indices: 0, 1, 2, ..., size-1.
- Shuffle the list using Collections.shuffle (Fisher–Yates under the hood).
- Take the first N shuffled indices — guaranteed unique.
- Return those indices to the caller.
*/
public class UniqueRandomIndices {
// Return N unique random indices
public static List<Integer> pickUniqueIndices(int arraySize, int count) {
if (count > arraySize) {
throw new IllegalArgumentException("Cannot pick more unique indices than array size.");
}
// Build index list
List<Integer> indices = new ArrayList<>(arraySize);
for (int i = 0; i < arraySize; i++) {
indices.add(i);
}
// Shuffle indices
Collections.shuffle(indices);
// Return first N indices
return indices.subList(0, count);
}
public static void main(String[] args) {
// Example array
int[] data = {5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6};
int N = 6; // number of unique indices to pick
// Get unique random indices
List<Integer> indices = pickUniqueIndices(data.length, N);
// Print results
System.out.println("Random unique indices and their values:");
for (int idx : indices) {
System.out.println("index " + idx + " -> value " + data[idx]);
}
}
}
/*
run:
andom unique indices and their values:
index 13 -> value 74
index 0 -> value 5
index 6 -> value 47
index 11 -> value 3
index 10 -> value 17
index 7 -> value 5
*/