D
D
Dokma2017-02-23 12:30:15
PHP
Dokma, 2017-02-23 12:30:15

How to lower the chance of getting a number?

For example, we have numbers from 0 to 15. I do getrandomint(0.15) and get a random number from this sample. But here, under certain conditions, I need to lower the chance of numbers falling out from 1 to 7. That is, I also need a random number from 0 to 15, but so that the chance of numbers falling out from 1 to 7 is less. The first thing that came to mind was to fill the array with these numbers and make a random selection from there, but this idea did not work very well. Can you suggest your implementation algorithm? It is possible with an array, but what would work)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arekus, 2017-02-23
@Dokma

// set the probabilities of getting a number in each interval. Total prob must be equal to 100

$data = [
  [
    'start' => 0,	// начало промежутка
    'end' => 7,		// окончание промежутка
    'prob' => 20, 	// вероятность попадания, %
  ],
  [
    'start' => 8,	// начало промежутка
    'end' => 15,	// окончание промежутка
    'prob' => 80, 	// понижающий коээффициент на вероятность, %
  ]
];

// call the function to get an arbitrary number, taking into account the probability of falling into the interval
function calcRand($data) {
  $prob = rand(0, 100);
  $pr = 0;
  $out = 0;
  foreach ($data as $info) {
    if ($prob >= $pr && $prob < $pr + $info['prob']) {
      $out = rand($info['start'], $info['end']);
      break;
    }
    $pr += $info['prob'];
  }
  return $out;
}

// verification code to demonstrate distribution
$numbers = [];
for ($i = 0; $i < 10000; $i++) {
  $number = calcRand($data);

  $numbers[$number] = (isset($numbers[$number]) ? $numbers[$number] + 1 : 1);
}
ksort($numbers);

echo '<pre>';
var_export($numbers);
var_export(array_map(function($a) { return round($a / 100); }, $numbers));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question