Unique Random Numbers!

I need some help! i create a program to give me 20 numbers from 1-90 interval but i want to implement more things.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stdafx.h"

#include <cstdlib>
#include <ctime>
#include <iostream> 
#include <fstream>
#include <conio.h>

using namespace std; 
int main() 
{     
	for(int i=0; i<90; i++)
	{cout<<" "<<i<<endl;}
srand((unsigned)time(NULL));     
int random_integer;     
for(int i=0; i<20; i++)
{        
	
   random_integer = (rand()%90)+1; 
    cout <<" "<< random_integer;    
  
} 
 getch();
}



1. I wan't here
1
2
random_integer = (rand()%90)+1; 
    cout <<" "<< random_integer;
to give me after 10 seconds the next number.

2.and i want the numbers that was given randomly to insert them into .txt file

someone can help me?

and the program dont give unique numbers some numbers are repeatble

Thank You!
Last edited on
1. You could do
1
2
intl t = clock();
while(clock()-t < 10*1000);
10 seconds is kind of a lot..

2. http://www.cplusplus.com/doc/tutorial/files/

and the program don't give unique numbers some numbers are repeatable
That's how randomness works..If you want no repetitions you have to know which numbers were already generated.

suggestion 1: store every generated number in an array. Then, when you need another number, call rand(), check if it is in array. If it is not, add it and return. If it is, repeat the process.

suggestion 2: have an array with every possible value (1 to 90). Then shuffle it. (you may want to http://www.cplusplus.com/reference/algorithm/random_shuffle/ ). Then to get the n'th random number, get the n'th element of that array.

The second way is better, I believe, unless the range of possible values is too large.
I'm generally against using system-dependent solutions, but for pausing the console, you can use either Windows' Sleep(milliseconds); or UNIX compilant systems' usleep(milliseconds); to create the delay. Or you can use both!
1
2
3
4
5
6
7
8
9
10
#if defined(_WIN32)
    Sleep(10000); //Requires <windows.h>
#elif defined(__unix) || defined(__linux) || defined(__APPLE__) 
    usleep(10000); //Requires <unistd.h>
#else
    clock_t endwait; //Requires <ctime>
    endwait = clock () + 10 * CLOCKS_PER_SEC ; 
    //clock() returns the current number of seconds since the program started.
    while (clock() < endwait) {} //This is a waste of resources.
#endif 


EDIT: Fine, I also gave the ctime solution.

EDIT2: Actually, I'm not sure if usleep() is required in POSIX specifications. To be sure, I changed the predefs.

As for the second problem:
http://cplusplus.com/doc/tutorial/files/

Happy coding!

-Albatross
Last edited on
Solved whit time delay thank you!
Topic archived. No new replies allowed.