|
|
1
5
您可以分析它两次,然后得到一个随机数并选择一个,这是在同一字符串的第二次传递时收集的。 或者,如果您使用 reservoir sampling . 掌握水库采样将是学习C的一个非常有用的方法,作为学习一些数学的一个侧面!:) |
|
|
2
2
下面的伪代码显示了如何返回在字符串标记中统一选择的候选项: string result = null;
int tokens = 0;
while (true) {
string candidate = next token;
if (candidate does not exist) break;
tokens = tokens + 1;
if ((a random integer selected between 0 and tokens-1) == 0) result = token;
}
return result;
这是一个特例 算法R 摘自Knuth’s第二卷第3.4.2节 计算机程序设计艺术 . |