Generate random number with distinct digits in c++
Answers
Answer:
#include <iostream>
using namespace std;
int main() {
int n1,n2;
cout<<"Enter no. of digits of number you wish to get ";
cin>>n1;
cout<<"Enter how many numbers you want to see ";
cin>>n2;
int arr[n1]={0},index=0;
for(int j=0;j<n2;j++)
{
int arr[n1]={0},index=0,num=0; //array to store randomly generated digit,index contain last digit containing index of array
while(true)
{
int b=rand()%10; //generating random digits less than 10
int check=0; //to check if digit is already found previously
for(int i=0;i<=n1;i++) //looping for n1 digits
{
if(arr[i]==b) //checking if digit is already found previously
check=1;
}
if(check==0) //if it's distinct digit check is 0
{
num=num*10+b; //adding the digit to newly generated number
arr[index++]=b; //incrementing index and storing digit in array to check next time
}
if(index==n1) //now if index(no. of digits found) is equal to input n1 break the loop
break;
}
cout<<num<<endl;
}
return 0;
}
Explanation:
Comments are placed accordingly
You can compile and run.
Try to dry run it to get the logic
Hope it helps :-)