2

私のスクリプトでは、特定のコードを特定の割合で実行したいので、StackOverflowを調べて、以下のコードを見つけました。コードは33%の時間実行されますが、55%と70%の時間実行するには、何を変更する必要がありますか?

$max = 27;

for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
        call_function_here();
    }
}
4

2 に答える 2

9

最も簡単な方法は、乱数ジェネレーターを使用して、その結果がターゲットの量より少ない(または多い、問題ではない)ことをテストすることです。

function percentChance($chance){
  // Notice we go from 0-99 - therefore a 100% $chance is always larger
  $randPercent = mt_rand(0,99);
  return $chance > $randPercent;
}

...

if(percentChance(30)){
  // 30% of page loads will enter this block
}

if(percentChance(100)){
  // All page loads will enter this block
}

if(percentChance(0)){
  // No chance this block will ever be entered
}
于 2012-08-18T06:04:39.790 に答える
-1

選択する量は一定でなければならないため、次のように実行できます。

$max = 27;
$num_selections = round(27 * (55 / 100));
$keys = array_rand($max, $num_selections);
for ($keys as $key) {
    // Do something with the chosen key
}
于 2012-08-18T05:10:34.917 に答える