Skip to content

Commit

Permalink
feat(distributor): adiciona distribuição aleatória com proporções
Browse files Browse the repository at this point in the history
Implementado um método de distribuição aleatória que adere às proporções especificadas. O novo mecanismo garante que as categorias sejam selecionadas de maneira probabilística, alinhando-se com suas porcentagens definidas ao longo do tempo.
  • Loading branch information
dhsananias committed Aug 25, 2023
1 parent 90c94d5 commit 71c6030
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/Distributor/Distributor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,38 @@ public function __construct(CacheInterface $cache, array $categories, array $per

public function distribute(string $item): array
{
$category = $this->getCategoryForDistribution();
$category = $this->getRandomCategoryBasedOnProportions();
$this->cache->increment($category);

return ['item' => $item, 'category' => $category];
}

private function getCategoryForDistribution(): string
private function getRandomCategoryBasedOnProportions(): string
{
$weights = [];

$totalItems = array_sum(array_map(fn($cat) => $this->cache->get($cat), $this->categories));

foreach ($this->categories as $index => $category) {
$desiredCount = $totalItems * ($this->percentages[$index] / 100);
if ($this->cache->get($category) < $desiredCount) {
$weights[$category] = $desiredCount - $this->cache->get($category);
}

return $this->getRandomCategoryWithWeights($weights);
}

private function getRandomCategoryWithWeights(array $weights): string
{
$totalWeight = array_sum($weights);
$randomWeight = mt_rand(1, $totalWeight);

foreach ($weights as $category => $weight) {
if ($randomWeight <= $weight) {
return $category;
}
$randomWeight -= $weight;
}

return $this->categories[0];
return $this->categories[0]; // fallback
}
}

0 comments on commit 71c6030

Please sign in to comment.