Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active August 28, 2020 13:57
Show Gist options
  • Save drupol/0a16a0ee545395e05f55c306b9d8e7e2 to your computer and use it in GitHub Desktop.
Save drupol/0a16a0ee545395e05f55c306b9d8e7e2 to your computer and use it in GitHub Desktop.
Random number distribution
<?php
declare(strict_types=1);
include 'vendor/autoload.php';
use loophp\collection\Collection;
use loophp\collection\Contract\Operation\Sortable;
$min = 0;
$max = 1000;
$groups = 100;
$randomGenerator = static function () use ($min, $max): int {
return random_int($min, $max);
};
$distribution = Collection::iterate($randomGenerator)
->limit($max * $max)
->associate(
static function ($key, $value) use ($max, $groups): string {
for ($i = 0; $i < ($max/$groups); ++$i) {
if ($i * $groups <= $value && ($i + 1) * $groups >= $value) {
return sprintf('%s <= x <= %s', $i * $groups, ($i + 1) * $groups);
}
}
}
)
->group()
->map(
static function ($value): int {
return \count($value);
}
)
->sort(
Sortable::BY_KEYS,
static function (string $left, string $right): int
{
[$left_min_limit] = explode(' ', $left);
[$right_min_limit] = explode(' ', $right);
return $left_min_limit <=> $right_min_limit;
}
);
print_r($distribution->all());
/*
Array
(
[0 <= x <= 100] => 100750
[100 <= x <= 200] => 99689
[200 <= x <= 300] => 100292
[300 <= x <= 400] => 99933
[400 <= x <= 500] => 99506
[500 <= x <= 600] => 100076
[600 <= x <= 700] => 99934
[700 <= x <= 800] => 100162
[800 <= x <= 900] => 99743
[900 <= x <= 1000] => 99915
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment