dat*_*ili 1 c++ algorithm permutation
我被告知写程序生成唯一的5位数字(例如12345是唯一的,11234不是)
我写了下面的代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
但它没有告诉我任何输出请帮我解决我的代码中哪些不好?
我认为这句话:
if ( it->second>0) {
Run Code Online (Sandbox Code Playgroud)
应该:
if ( it->second>1) {
Run Code Online (Sandbox Code Playgroud)
因为当你找到一个数字的第一个实例并将其放在地图中时,它将在地图中为该数字赋值1,而不是0.