How to generate N random integers composed of exactly M distinct digits in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>

/*
    Generate N integers, each with exactly M distinct digits.

    Constraints:
    - Each integer has length M.
    - All digits in a given integer are distinct (no repetition).
    - Leading zero is not allowed.
    - Digits are chosen randomly.
*/

// Generate one integer with exactly M distinct digits
std::string generateOne(int M, std::mt19937& rng) {
    // All possible digits
    std::vector<char> digits;
    digits.reserve(10);
    for (char d = '0'; d <= '9'; ++d)
        digits.push_back(d);

    // Shuffle digits to get randomness
    std::shuffle(digits.begin(), digits.end(), rng);

    // Ensure first digit is not zero:
    // If '0' ended up at the front, swap it with some non-zero digit.
    if (digits[0] == '0') {
        // Find first non-zero digit
        auto it = std::find_if(digits.begin() + 1, digits.end(),
                               [](char c) { return c != '0'; });
        if (it != digits.end())
            std::swap(digits[0], *it);
    }

    // Now take the first M digits as our distinct digits
    std::string result;
    result.reserve(M);
    for (int i = 0; i < M; ++i)
        result.push_back(digits[i]);

    return result;
}

// Generate N integers with exactly M distinct digits
std::vector<std::string> generateMany(int N, int M) {
    std::random_device rd;
    std::mt19937 rng(rd());

    std::vector<std::string> results;
    results.reserve(N);

    for (int i = 0; i < N; ++i)
        results.push_back(generateOne(M, rng));

    return results;
}

int main() {
    int N = 10; // how many integers to generate
    int M = 3;  // how many distinct digits per integer

    std::vector<std::string> results = generateMany(N, M);

    std::cout << "Generated integers:\n";
    for (const auto& num : results)
        std::cout << num << "\n";

    return 0;
}


/*
run:

Generated integers:
973
208
831
708
482
837
403
507
176
317

*/

 



answered 1 day ago by avibootz

Related questions

...