私のスクリプトでは、特定のコードを特定の割合で実行したいので、StackOverflowを調べて、以下のコードを見つけました。コードは33%の時間実行されますが、55%と70%の時間実行するには、何を変更する必要がありますか?
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
私のスクリプトでは、特定のコードを特定の割合で実行したいので、StackOverflowを調べて、以下のコードを見つけました。コードは33%の時間実行されますが、55%と70%の時間実行するには、何を変更する必要がありますか?
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
最も簡単な方法は、乱数ジェネレーターを使用して、その結果がターゲットの量より少ない(または多い、問題ではない)ことをテストすることです。
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
}
選択する量は一定でなければならないため、次のように実行できます。
$max = 27;
$num_selections = round(27 * (55 / 100));
$keys = array_rand($max, $num_selections);
for ($keys as $key) {
// Do something with the chosen key
}