Created
November 20, 2014 09:04
-
-
Save i-van/7239117a329bfe114fbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* get random event | |
* | |
* format: array('event1' => 'chance1', 'event2' => 'chance2', ...) | |
* | |
* @param array $events | |
* @return string | |
*/ | |
public function randomEvent(array $events) | |
{ | |
/** sort events according chance */ | |
asort($events); | |
if (!array_filter($events)) { | |
throw new \Core\Exception(sprintf('events(%s) are empty', json_encode($events))); | |
} | |
/** | |
* transformation to the range, like | |
* 0 .. 0.1 .. 0.3 .. 1 | |
*/ | |
$range = array(); | |
$total = 0; | |
foreach ($events as $event => $chance) { | |
$total += $chance; | |
$range[$event] = $total; | |
} | |
/** normalization */ | |
if ($total != 1) { | |
$ratio = 1 / $total; | |
$range = array_map(function($value) use ($ratio) { | |
return $value * $ratio; | |
}, $range); | |
} | |
/** select range */ | |
$random = $this->random(); | |
$previous = 0; | |
foreach ($range as $event => $current) { | |
if ($random > $previous && $random <= $current) { | |
break; | |
} else { | |
$previous = $current; | |
} | |
} | |
$this->log(sprintf('random event from %s: %s', json_encode($events), $event)); | |
return $event; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment