Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,237 questions

56,140 answers

573 users

How to generate 3 integers between 100 and 999 each with unique digits in C++

1 Answer

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

/*
    Function: has_all_unique_digits
    Purpose:  Check whether an integer contains only distinct digits.
              Example: 123 → true, 112 → false.
*/
bool has_all_unique_digits(int n) {
    std::unordered_set<int> seen;
    while (n > 0) {
        int d = n % 10;
        if (seen.count(d)) return false;   // digit already seen → not unique
        seen.insert(d);
        n /= 10;
    }
    return true;
}

/*
    Function: generate_unique_digit_int
    Purpose:  Generate a random integer with all digits distinct.
              Uses C++'s <random> for high‑quality randomness.
*/
int generate_unique_digit_int(int min_val, int max_val, std::mt19937 &rng) {
    std::uniform_int_distribution<int> dist(min_val, max_val);

    while (true) {
        int candidate = dist(rng);
        if (has_all_unique_digits(candidate)) {
            return candidate;  // return only when digits are distinct
        }
    }
}

/*
    Function: generate_three_unique_digit_integers
    Purpose:  Produce exactly three integers, each with distinct digits.
              Ensures they are also distinct from each other.
*/
std::vector<int> generate_three_unique_digit_integers(int min_val, int max_val) {
    std::random_device rd;
    std::mt19937 rng(rd());

    std::unordered_set<int> results;

    while (results.size() < 3) {
        int val = generate_unique_digit_int(min_val, max_val, rng);
        results.insert(val);   // set ensures no duplicates
    }

    return std::vector<int>(results.begin(), results.end());
}

int main() {
    // Generate three integers between 100 and 999 (all 3-digit numbers)
    auto nums = generate_three_unique_digit_integers(100, 999);

    std::cout << "Generated integers with distinct digits:\n";
    for (int n : nums) {
        std::cout << n << "\n";
    }
}


/*
run:

Generated integers with distinct digits:
783
948
938

*/

 



answered Jul 16 by avibootz

Related questions

...