Dec 22, 2016 at 10:26am UTC
Hello
I need help with creating a 10-digit random number generator such that when a number is generated it does not get generated again and that the digit does not repeat in the same number for example: 0123456789 not 0112345567.
I used string and Rand() but got a lot of errors so I need help please.
Dec 22, 2016 at 10:30am UTC
can you post your code?
Most of the time you have to have srand(time(0));
Dec 22, 2016 at 10:36am UTC
Really good random number generators are available as well.
Google "Mersenne Twister," for example.
Dec 22, 2016 at 11:58am UTC
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
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int SIZE = 10;
int main()
{
int r;
int c[SIZE];
bool used[SIZE] = { 0 };
srand( time( 0 ) );
for ( int i = 0; i < SIZE; i++ )
{
bool ok = false ;
while ( !ok )
{
r = rand() % SIZE;
ok = !used[r];
if ( ok ) c[i] = r;
used[r] = true ;
}
}
for ( int i = 0; i < SIZE; i++ ) cout << c[i];
cout << endl;
}
Last edited on Dec 22, 2016 at 12:01pm UTC
Dec 22, 2016 at 12:31pm UTC
Or, with a bit less waste of random numbers:
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
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
const int SIZE = 10;
int main()
{
int i, r;
int c[SIZE];
vector<int > digits; for ( i = 0; i < SIZE; i++ ) digits.push_back( i );
srand( time( 0 ) );
for ( i = 0; i < SIZE; i++ )
{
r = rand() % ( SIZE - i );
c[i] = digits[r];
digits.erase( digits.begin() + r );
}
for ( i = 0; i < SIZE; i++ ) cout << c[i];
cout << endl;
}
Last edited on Dec 22, 2016 at 12:35pm UTC