How to select N unique random indices from an existing vector in C++

1 Answer

0 votes
#include <algorithm>   // for std::shuffle
#include <iostream>    // for std::cout
#include <random>      // for std::mt19937, std::random_device
#include <vector>      // for std::vector

/*
    Select N unique random indices from an existing vector
    and print both the index and the value.

    Explanation:
    - Build a vector of indices: 0, 1, 2, ..., size-1.
    - Shuffle the indices using a strong random engine.
    - Take the first N shuffled indices — guaranteed unique.
    - Print each selected index and its corresponding value.
*/

// Function that returns N unique random indices
std::vector<std::size_t> pick_unique_indices(std::size_t size, std::size_t count) {
    if (count > size) {
        throw std::runtime_error("Cannot pick more unique indices than the vector contains.");
    }

    // Create a list of all valid indices
    std::vector<std::size_t> indices(size);
    for (std::size_t i = 0; i < size; ++i) {
        indices[i] = i;
    }

    // Random engine seeded with a true random device
    std::random_device rd;
    std::mt19937 gen(rd());

    // Shuffle the indices
    std::shuffle(indices.begin(), indices.end(), gen);

    // Return the first 'count' unique indices
    return std::vector<std::size_t>(indices.begin(), indices.begin() + count);
}

int main() {
    // Example vector
    std::vector<int> data = {5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6};

    // Number of unique indices to pick
    std::size_t N = 6;

    // Get unique random indices
    std::vector<std::size_t> indices = pick_unique_indices(data.size(), N);

    // Print results
    std::cout << "Random unique indices and their values:\n";
    for (std::size_t idx : indices) {
        std::cout << "index " << idx << " -> value " << data[idx] << "\n";
    }
}


/*
run:

Random unique indices and their values:
index 0 -> value 5
index 12 -> value 5
index 8 -> value 58
index 10 -> value 17
index 2 -> value 5
index 3 -> value 19

*/

 



answered Sep 12 by avibootz
edited Sep 12 by avibootz
...