前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >编程珠玑II C12笔记: rand num generator

编程珠玑II C12笔记: rand num generator

作者头像
刘笑江
发布2018-05-25 09:52:07
4140
发布2018-05-25 09:52:07
举报

Problem:

given m<n, generate random numbers of m within range(0..n).

Solutions:

  • a Knuth’s solution of O(log n) time :
select = m
remaining = n
for i = [0,n)
    if ( bigrand() % remaining ) < select
        print i
        select--
remaining—

But when n was large, it meets bootleneck. Improve with:

  • a solution of O(m log m) time using :
#include <iostream>
#include <cstdlib>
#include <set>
using namespace std;
void gensets(int m, int n){
    set<int> S;
    while(S.size()<m){
        S.insert(std::rand() % n);
        set<int>::iterator i;
        for (i = S.begin(); i!=S.end(); ++i){
            cout<< *i << endl;
        }
    }
}
int main(){
    gensets(1000000, 10000000);
    return 0;
}
  • shuffle solution O():

f

Principles

Understand the Perceived Problem

talk to user

Specify an Abstract Problem

get a clean, crisp problem statement.

Explore the Desgn Space

think for a day and code for a min rather than per contra

Implmnt One Solution

choose the best

Retrospect

Polya’s delightful How to Solve It can help programmer become a better problem solver.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-08-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem:
  • Solutions:
  • Principles
    • Understand the Perceived Problem
      • Specify an Abstract Problem
        • Explore the Desgn Space
          • Implmnt One Solution
            • Retrospect
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档