views:

153

answers:

2

i was told to write program which generate unique 5 digit number ( for example 12345 is unique and 11234 not)
i have write following code

#include <iostream>
#include <stdlib.h>
#include <map>
using namespace std;
using std::rand;
const int k=99999-10234;
bool  unique(int t){

    map<int,int>my;
    map<int,int>::iterator it;
    while (t!=0){
        ++my[t%10];
    t/=10;
}
    for (it=my.begin();it!=my.end();it++){

        if ( it->second>0) {
             return false;
        }
    }

       return true;
}
int main(){
    int m=0;
     m= 10234+ rand()%k;
    if (unique(m)){
         cout<<" unique number was generated =:"<<m<<" ";
    }
    else{

        do{


             m=10234+rand()%k;
               if (unique(m)){
                   cout<<"unique  number was generated"<<m<<" ";
                break;
               }

    }   while(!unique(m));


    }


     return 0;
}

but it does not show me any output please help me what is bad in my code?

+5  A: 

I think the line:

if ( it->second>0) {

Should be:

if ( it->second>1) {

Since when you find the first instance of a digit and put it in the map it'll have the value 1 for that digit in the map, not 0.

ho1
oi yes sorry thanks ho1
+3  A: 

I guess there're easier ways to generate number you need, e.g.

std::vector<int> digs;
for (int i = 0; i < 10;++i)
    digs.push_back(i); // Init digits

std::random_shuffle(digs.begin(), digs.end()); // Get random 10-digits number
int result = 0;
int i = 0;
while (result < 10000) { // Get 5-digit number from it
    result*=10;
    result += digs[i];             
    ++i;
}

cout << result << endl;
Vladimir
MSalters
Those redundant(?) lines are just to handle the case when 1st digit is '0' - so technically first 5 digits won't produce 5-digit number.
Vladimir