我正在尝试实现我的处理代码,这样一行代码将不会运行一行代码应该运行的总次数的5%。但关键的附加点是,线路不会运行的实例应该是不可预测的(随机的)。
例如,假设代码要运行20次。我希望代码不会在20个实例中的任何一个实例中运行。这一个实例将是总数的5% (20) 1/20=5%。
这必须是随机的,例如,在20的第一次迭代中,代码不会在第三次试验中运行,而在第二次迭代中,这行代码不会在第10次试验中运行。
如下图所示:
第一次迭代: 1,2,3(不要运行),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20秒迭代: 1,2,3,4,5,6,7,8,9,10 (不要运行),11,12,13,14,15,16,17,18,19,20第三次迭代:。
我写了下面的伪代码,但我想知道是否有更好的方法来做到这一点。
create an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
take a number out of a set randomly and if the number is NOT 1:
println("run")
get rid of the selected number within an array
if the set is empty, get a new set发布于 2020-01-16 10:10:22
您需要问的关键问题是,是否允许代码多次运行失败。在第一次迭代中,您在1上登陆的更改为5%,但如果不删除该数字,则在随后的迭代中,您也有5%的机会在1上登陆。这可以接受吗?如果没有,只需在'catch‘值到达后将其删除即可。
还有一种更简单的方式来说明这样的选择,那就是通过modulo
generate a random number:
divide the number by 20
check that the modulo is equal to 0它看起来像这样:
rand() % 20 == 0使用这种方法,设置一个标志来指示失败的运行条件已经满足,并停止将后续运行视为失败,即使它们落在相同的模上,也会更有效:
generate a random number
if not failed yet:
if random number divided by 20 has a modulo of 0:
denote a failure或者作为代码:
if (not failed_run) {
if (rand() % 20 == 0) {
failed_run = true
}
}另请注意,在检查随机数模数时会出现slight weighting distribution bias。样本大小越小(在本例中为20),这将更有问题,因此可能值得考虑。
https://stackoverflow.com/questions/59761963
复制相似问题