How to generate non repeated numbers?

Hello guys, I am new to c++ and I was trying to make a function which generates non repeated numbers.
Would u guys mind helping me have a look on my code?
here is my function:

void generateNumb(int *arr, int size)
{
srand(time(0));
arr[0]=rand()%9+1;
for(int x=1; x<size; x++)
{
arr[x]=rand()%9+1;
for(int i=0; i<x; i++)
{
while(arr[x]==arr[i])
{
arr[x]=rand()%9+1;
}
}
}

}
And i m pretty sorry about the format upfront.
You are not clear on the specs here. Let's assume you want n non-repeating numbers from 0 to N-1. Generate a vector consisting of v = {0,1,2,...,N-1} (std::iota could be used if you want). Then shuffle v using std::shuffle or std::random_shuffle. Then extract the first n elements of the resulting vector.

If N is very large, then instead of shuffling v, then carry out a loop wherein
const int r = std::rand() % v.size();
store v[r] wherever you want your generated numbers to be stored, then remove it from the vector using the erase-remove idiom
std::erase (std::remove(v.begin(), v.end(), v[r]), v.end());
and then repeat until you've done this n times. If v is not consecutive numbers, then construct v however you want (it doesn't even have to be a vector of integers) and do the exact same thing.
Last edited on
I would suggest creating a std::vector of non repeated numbers and std::shuffle it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>

int main() {
    int low = 3;
    int high = 17;
    std::vector<int> nums(high - low + 1);
    std::iota(nums.begin(), nums.end(), low);
    
    std::random_device rd;
    std::shuffle(nums.begin(), nums.end(), rd);
    
    for(int x : nums) {
    	std::cout << x << std::endl;
    }
    
    return 0;
}


Edit: prestokeys said the same thing, I should have refreshed my page. :)
Last edited on
@Duoas: I am going to find a use for a bloom filter sometime this month :)
I know! They're cool!
Thank you so much guys,
I think i have to take a look on vectors frist
Topic archived. No new replies allowed.