六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 50|回复: 0

如何将随机范围从1到5变为1到7

[复制链接]

升级  30%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
15
 楼主| 发表于 2013-1-26 15:00:44 | 显示全部楼层 |阅读模式
stackoverflow上有个经典的面试题讨论,如何将随机范围从1到5变为1到7。

先提供两个算法参考:

int i;do{  i = 5 * (rand5() - 1) + rand5();  // i is now uniformly random between 1 and 25} while(i > 21);// i is now uniformly random between 1 and 21return i % 7 + 1;  // result is now uniformly random between 1 and 7

int rand7(){    int vals[5][5] = {        { 1, 2, 3, 4, 5 },        { 6, 7, 1, 2, 3 },        { 4, 5, 6, 7, 1 },        { 2, 3, 4, 5, 6 },        { 7, 0, 0, 0, 0 }    };    int result = 0;    while (result == 0)    {        int i = rand5();        int j = rand5();        result = vals[i-1][j-1];    }    return result;}

欢迎拍砖。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表