#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont=false;
string str;
int num,num2;
cin >> str >> num;
int arr[10];
int a = pow(10,num);
int b= pow(10,(num-1));
srand(static_cast<int>(time(NULL)));
do{
num2=rand()%(a-b)+b;
int r;
int i=0;
int cpy=num2;
while(cpy!=0){
r=cpy%10;
arr[i]=r;
i++;
cpy=cpy/10;
}
for (int m=0; m<num; m++)
{
for (int j=0; j<m; j++){
if(m != j){
if (arr[m] == arr[j]){
break;
}
else{
cont=true;
}
}
}
}
cout<<num2<<endl;
}while(!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique, but I get an error.How can I solve the problem?
Aucun commentaire:
Enregistrer un commentaire