给定一个范围是1到5的随机整数生成器,设计一个范围是1到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; }
但是在最坏情况下,rand7()可能会永远不停的循环下去。事实上,本题不存在常数时间的解法。
把上面的代码简化之后就可以得到下面的代码:
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 21 return i % 7 + 1; // result is now uniformly random between 1 and 7