Non Repeating number generator

Apr 23, 2012 at 6:29pm
Hi I have put up my code now and apologies for not doing it earlier, I was using a different computer and browser over the weekend, didnt have the compiler etc.
I tried to create a program that ask the user for Random numbers and generates non repeating numbers. It also asks for a file to store them in. I stayed up all night but no solution, Please help
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>

using namespace std;

int main()
{
srand(unsigned(time(NULL)));
ifstream inputFile;
string theFile;
int numOfValues;
int values = 1 + rand() % 20; /****this is used to give the range of the
numbers to be generated******/


cout << "Select a file to open with its extension: ";
cin >> theFile;
cout << "How many random numbers do you want to generate: ";
cin >> numOfValues;
inputFile.open(theFile.c_str());

while(numOfValues > 0);
{
ofstream outputFile;
outputFile.open(theFile.c_str());
cout << values << "\t";
numOfValues--;
outputFile.close();
}

cout << "\nNo more numbers to generate.";
system("pause");
return 0;
}
Apr 23, 2012 at 6:50pm
So... what's the problem?

Does your code you posted not work? Do you get a compiler error? If yes, what's the error?

Does it compile but not do what you want? If yes, what do you want and what is it doing differently?
Last edited on Apr 23, 2012 at 6:50pm
Apr 23, 2012 at 7:07pm
You can use either std::bitset<20> or std::set<unsigned int> to check non-repeated random numbers.
Last edited on Apr 23, 2012 at 7:08pm
Apr 23, 2012 at 8:24pm
(Disch)... The problem is that the program repeats the numbers and that's the opposite of what I expect.
(Vlad).... In what way can I use either of it.
Apr 23, 2012 at 9:06pm
For example if you will use std::bitset you can set a corresponding bit for a given random number in the range [ 0, 19 ] or [ 1, 20 ].

for example

1
2
3
4
5
6
7
8
9
10
const int N = 20;

std::bitset<N> b;

do
{
   values = 1 + rand() % N;
} while ( b[values - 1] );

b.set( values - 1 );


Also you should take into acccount that if you will try to get more that 20 random numbers you can get infinite loop because there is no free slot in the bitset. You shall reset it to get the second sequence of unique random numbers.
Last edited on Apr 23, 2012 at 9:12pm
Apr 23, 2012 at 9:26pm
okay I get it now, have to try it
Apr 23, 2012 at 9:44pm
Here is a compiled example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const size_t N = 20;

std::bitset<N> b;

std::srand( ( unsigned ) std::time( 0 ) );

for ( size_t i = 0; i < N; i++ )
{
	size_t number;

	do
	{
		number = std::rand() % N;
	} while ( b[number] );

	b.set( number );

	std::cout << number << ' ';
}

std::cout << std::endl;
Topic archived. No new replies allowed.