10-Digit non-repetitive randon generator

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.

can you post your code?
Most of the time you have to have srand(time(0));
Really good random number generators are available as well.

Google "Mersenne Twister," for example.
Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
unsigned long long random10()
{
    static std::string digits = "0123456789" ;
    static std::mt19937 rng( std::random_device{}() ) ;

    std::shuffle( digits.begin(), digits.end(), rng ) ;
    return std::stoull(digits) ;
}

unsigned long long unique_random10()
{
    static const std::size_t MAX_NUMBERS = 1'000'000 ; // adjust as required
    static std::unordered_set< unsigned long long > history ;

    if( history.size() == MAX_NUMBERS ) throw std::domain_error( "limit exceeded" ) ;

    while(true)
    {
        unsigned long long n = random10() ;
        if( history.insert(n).second ) return n ;
    }
}

http://coliru.stacked-crooked.com/a/8bad333890a58524
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
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
Topic archived. No new replies allowed.