-3

I am making a program and I need to generate all 9 digits numbers which have each digit different to the other digits, the 0 is not a valid digit in this case so I am only considering digits from 1 to 9.

So far I have this solution using random number generation, but I am facing performance issues

using namespace std;
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string>
#include <map>

int main()
{
    srand (time(NULL));

    int secret;
    string number = "";

    map <string, bool> m;
    int count = 0;

    int nine_permutation = 362880;

    vector <int> v{0,1,2,3,4,5,6,7,8,9};
    int x = 9;

    while(count < nine_permutation)
    {
      for(int i = 0; i < 9; i++)
      {
          secret = rand() % x +1;
          number += to_string(v[secret]);
          v.erase(v.begin() + secret);

          x--;
      }
      x = 9;
      v = {0,1,2,3,4,5,6,7,8,9};
      if(m.count(number) == 0)
      {
        m[number] = true;
        count ++;
      }


      cout << count << endl;
    }


    cout << number;
}
Just Half
  • 1,091
  • 1
  • 9
  • 8

1 Answers1

1

So you have 10 digits 0,1,2,3,4,5,6,7,8,9 and number you want to get numbers with nine digits. I think you can start with 123456789, generate all permutations and then replace each character with '0' which would give set: {023456789, 103456789, 120456789, 123056789, 123406789, 123450789, 123456089, 123456709, 123456780}. And for each element from this set also generate all permutations. Something like this:

void allNumbersWithDistinctDigits() {
    int idxForZero = 0;
    std::string initial("123456789");

    std::string local(initial);
    do {
        while (std::next_permutation(local.begin(), local.end())) {
            if (local[0] != '0') {
                std::cout << local << std::endl;
            }
        }
        local = initial;
        local[idxForZero] = '0';
    } while(++idxForZero <= initial.size());

}

Condition if (local[0] != '0') is optional and it gets rid of numbers starting with 0, like: 012345678 which is in fact 8 digits 12345678 or octal number.

Mateusz Wojtczak
  • 1,621
  • 1
  • 12
  • 28