vjdj
vjdj

Reputation: 95

Selecting with probability, checking values

Please excuse my language.

I select with probability. The sum of the probabilities is equal to 1. For example: if I have drawn number 0-0,6 it's probability value is 0,6.

My actual code:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Probability</title>
</head>
<body>

<?php
$fruits = array();
$table = array(array('fruit'=>'orange', 'probability'=>0.6), array('fruit'=>'strawberry', 'probability'=>0.3),array('fruit'=>'raspberry', 'probability'=>0.1));

echo '<pre>';
echo print_r($table);
echo '</pre>';

for($i=0; $i<10; $i++){
    $temp = rand(0,10)/10;
    if($temp<=0.6) {
        $fruits[$i]=$table[0]['fruit'];
    }
    else if($temp>0.6 && $temp<=0.9) {
        $fruits[$i]=$table[1]['fruit'];
    }
    else {
        $fruits[$i]=$table[2]['fruit'];
    }
}

echo '<p>Table</p>';
echo '<pre>';
echo print_r($fruits);
echo '</pre>';
?>
</body>
</html>

Now I use if but I don't know how to automate it, because ultimately there will be more fruit. The probability value will change often, but now I must change if expression manually. How do you check between which the random elements of the array is drawn value and display her name?

Upvotes: 0

Views: 159

Answers (1)

ViRuSTriNiTy
ViRuSTriNiTy

Reputation: 5155

From the top of my head:

$fruits = array();
$table = array(
    array('fruit' => 'orange', 'probability' => 60 /* percent */),
    array('fruit' => 'strawberry', 'probability' => 30),
    array('fruit' => 'raspberry', 'probability' => 10)
  );

// append rand_min & rand_max values to table rows
for($i = 0; $i < count($table); $i++)
{
  $row = &$table[$i];

  if ($i > 0)
  {
    $previous_row = $table[$i - 1];

    $row["rand_min"] = $previous_row["rand_max"];
    $row["rand_max"] = $row["rand_min"] + $row["probability"];
  }
  else
  {
    $row["rand_min"] = 0;
    $row["rand_max"] = $row["probability"];
  }

  unset($row); // to avoid side effects when $row is used later
}

// calculate fruits
for($i = 0; $i < 10; $i++)
{
  $rand = rand(0, 100);

  foreach ($table as $row)
  {
    if ($row["rand_min"] <= $rand && $rand <= $row["rand_max"])
    {
      $fruits[$i] = $row["fruit"];

      break;
    }
  }
}

print_r($fruits);

The idea is to loop through all table rows instead using a single if for each fruit.

Upvotes: 1

Related Questions