百科问答小站 logo
百科问答小站 font logo



c++怎么在1到n这些数中随机产生k(k<n)个?当然,k个数互不相等。有什么比较好的写法吗? 第1页

  

user avatar   lz1996 网友的相关建议: 
      

传统的rand()%pool_size方法在一般情况下可以采用,但是实际上这样产生的随机数分布不是完全均匀的。如果对随机数要求较高的话,建议采用下列方法:

       #include <random> #include <iostream>  const int n=10000; const int k=1000; bool taken[n]; int result[k];  int main() {     std::random_device rd;     std::mt19937 gen(rd());     std::uniform_int_distribution<> dis(1, n);      for(int count=0; count<k; ++count)     {         int tmpResult = dis(gen);         while (taken[tmpResult])         {             tmpResult = dis(gen);         }         result[count] = tmpResult;         taken[tmpResult] = true;     }      for(int count=0; count<k; ++count)         std::cout<<result[count]<<std::endl; }      



  

相关话题

  Java中有哪些设计精良的部分(精华),还有哪些是不值得花费很多时间探究的知识点? 
  如何使用 GitHub? 
  为什么现在有这么多人工智能无用论? 
  该如何正确看待c中的字符串常量? 
  为什么C++的 extern "C" 里面可以使用C里面不存在的STL和引用&等C++才有的特性 ? 
  如何看待萧井陌办IT培训班? 
  C#下有什么办法可以实现毫秒级的计划任务? 
  为什么说读代码比写代码难? 
  如何理解 “c++缺少对象级别的消息发送机制” 这句话? 
  如何高效地获得玩家排名? 

前一个讨论
常听到这洗脑那洗脑到底什么是洗脑?又是怎样洗脑?
下一个讨论
如何评价「六小龄童节目被春晚毙掉」这一传言?





© 2025-03-24 - tinynew.org. All Rights Reserved.
© 2025-03-24 - tinynew.org. 保留所有权利