如何将随机范围从1到5变为1到7
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 = { { 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; } return result;}
欢迎拍砖。
页:
[1]