|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Stu\Module\Control; |
|
4
|
|
|
|
|
5
|
|
|
use RuntimeException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* This class adds the possibility to inject a random generator |
|
9
|
|
|
*/ |
|
10
|
|
|
class StuRandom |
|
11
|
|
|
{ |
|
12
|
1 |
|
public function rand(int $min, int $max, bool $useStandardNormalDistribution = false, int $mean = null): int |
|
13
|
|
|
{ |
|
14
|
1 |
|
if ($useStandardNormalDistribution) { |
|
15
|
1 |
|
return $this->generateRandomValueStandardNormalDistribution($min, $max, $mean); |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
return random_int($min, $max); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function array_rand(array $array): string|int |
|
22
|
|
|
{ |
|
23
|
|
|
return array_rand($array); |
|
|
|
|
|
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** @param array<int, int> $probabilities */ |
|
27
|
|
|
public function randomKeyOfProbabilities(array $probabilities): int |
|
28
|
|
|
{ |
|
29
|
|
|
$totalProbability = array_sum($probabilities); |
|
30
|
|
|
|
|
31
|
|
|
$randomNumber = random_int(1, $totalProbability); |
|
|
|
|
|
|
32
|
|
|
$cumulativeProbability = 0; |
|
33
|
|
|
|
|
34
|
|
|
foreach ($probabilities as $key => $prob) { |
|
35
|
|
|
$cumulativeProbability += $prob; |
|
36
|
|
|
if ($randomNumber <= $cumulativeProbability) { |
|
37
|
|
|
return $key; |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
throw new RuntimeException('this should not happen'); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
1 |
|
private function generateRandomValueStandardNormalDistribution(int $min, int $max, ?int $mean): int |
|
45
|
|
|
{ |
|
46
|
1 |
|
$usedMean = $mean === null ? (($min + $max) / 2) : $mean; // MW |
|
47
|
1 |
|
$stdDeviation = $usedMean / 2.5; // FWHM |
|
48
|
|
|
|
|
49
|
|
|
do { |
|
50
|
1 |
|
$value = random_int($min, $max); |
|
51
|
1 |
|
$probability = exp(-0.5 * (($value - $usedMean) / $stdDeviation) ** 2); // normal distribution |
|
52
|
1 |
|
$randomProbability = random_int(0, mt_getrandmax()) / mt_getrandmax(); |
|
53
|
|
|
|
|
54
|
1 |
|
if ($randomProbability <= $probability) { |
|
55
|
1 |
|
return $value; |
|
56
|
|
|
} |
|
57
|
1 |
|
} while (true); |
|
|
|
|
|
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|