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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to generate N unique random numbers between min and max in C++

2 Answers

0 votes
#include <iostream>
#include <cstdlib>
#include <ctime>

#define SIZE 8

int getRandom(const int min, const int max) {
    return (rand() % (max - min + 1)) + min; 
}

void generateUniqueRandomNumbers(int arr[], const int N, const int min, const int max) {
    int count = 0;
    while (count < N) {
        int num = getRandom(min, max); // Generate a random number within the specified range
        bool isUnique = true;
        for (int i = 0; i < count; i++) {
            if (arr[i] == num) {
                isUnique = false;
                break;
            }
        }
        if (isUnique) {
            arr[count] = num;
            count++;
        }
    }
}

int main() {
    srand(static_cast<unsigned int>(time(NULL)));
    const int N = SIZE; // Number of unique random numbers
    int arr[SIZE] = {0};

    generateUniqueRandomNumbers(arr, N, 1, 20);

    for (int i = 0; i < N; i++) {
        std::cout << arr[i] << " ";
    }
}

  
  
/*
run:
    
10 8 20 13 19 2 15 1 
   
*/

 



answered Sep 24, 2024 by avibootz
0 votes
#include <iostream>
#include <random>
#include <set>

std::set<int> generateUniqueRandomNumbers(int N, int min, int max) {
    std::set<int> uniqueNumbers;
    std::random_device rd;  
    std::mt19937 gen(rd()); 
    std::uniform_int_distribution<> dis(min, max);

    while (uniqueNumbers.size() < N) {
        uniqueNumbers.insert(dis(gen));
    }

    return uniqueNumbers;
}


int main() {
    int N = 8; // Number of unique random numbers

    std::set<int> randomNumbers = generateUniqueRandomNumbers(N, 1, 20);

    for (int num : randomNumbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

 
   
/*
run:

run1:  
4 5 9 10 11 14 15 17 

run2:
1 2 6 7 12 15 17 19 
  
*/

 



answered Sep 24, 2024 by avibootz

Related questions

...