unique random number generator code...need help!!!!!

I am trying to generate a unique random numbers plzz help I need this for a project :/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  int main()
{   srand(time(0));
	int term;
	cin>>term;
	int a[term];
	int b;
	for(int i=0;i<term;i++)
	{
		int count=0;
		b=(rand()%term);
		for(int k=0;k<100;k++)
		{
			if(count<term)
			{
				if(b!=a[k])
				{
					a[i]=b;
					count++;
				}
				
			}
		}
	
	
	}
		for(int k=0;k<4;k++)
		{
		cout<<a[k]<<endl;
	    }
}Put the code you need help with here.
closed account (48T7M4Gy)
What do u need help with?
From you code, you want a
-unqiue number width "term" number of digits. (line 5)
-Also, you want the max digit of the unique number to be < term. (line 10).
Hence, you are simply generating a random "term-1" digit number from [0 to term-1].
e.g When "term" is 4, you could get [0123] or [2310] etc...

If this is really what you want, you can just fill an array with digits from 0 to term -1 and do a random shuffle.
1
2
3
4
int a[term];
for(int i = 0; i < term; i++)
    a[i] = i;
std::random_shuffle(a,a+term);


If you need more control and customization..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;

bool found(int * a, int n, int key)
{
	sort(a, a + n);
	return binary_search(a, a + n, key);
}
int main()
{
	int term;
	cout << "Enter the length: ";
	cin >> term;

	int* unique = new int[term];
	fill(unique, unique + term, term);

	srand(static_cast<unsigned>(time(NULL)));
	int count = 0;

	for (int i = 0; i < term; i++)
	{
		int x = rand() % term;
		if (!found(unique, term, x))
			unique[count++] = x;
		else
			i--;
	}
	for (int i = 0; i < term; i++)
		cout << unique[i]<<" ";
	cout << endl;
	system("pause");
        
        delete[] unique;
	return 0;
}


Hope this solves you issue.
Last edited on
@shadowCODE you sir ... saved my life :D thanks :D
Topic archived. No new replies allowed.