c++ - 生成唯一的 5 位数字

标签 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;
}

但它没有显示任何输出,请帮我看看我的代码有什么问题吗?

最佳答案

我认为行:

if ( it->second>0) {

应该是:

if ( it->second>1) {

因为当您找到数字的第一个实例并将其放入映射中时,映射中该数字的值为 1,而不是 0。

关于c++ - 生成唯一的 5 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413775/

相关文章:

c++ - 我的程序编写每十亿个组合的更有效方法?

c++ - 将私有(private)库静态链接到公共(public)库以隐藏符号

c++ - 升压.X3 : char_ >> char_ discards the characters and behaves like lit

c++ - 从线程抛出异常没有给出预期的结果

algorithm - 非常大的排列列表

c++ - 大数排列 nPr 的最佳程序

c++ - 如何从 3D 点获取屏幕坐标? OpenGL

java - 我将如何计算此递归函数的最坏情况时间复杂度?

algorithm - 如何使用堆栈评估反向抛光符号

algorithm - 将排名排列索引到其他排名排列