Last active
March 20, 2017 10:42
-
-
Save ben182/dd1ccbf3cf45855dcc99578c3b68a371 to your computer and use it in GitHub Desktop.
Gives the possibility to perform actions according to a certain probability
This file contains hidden or 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
| class Chance | |
| { | |
| private $_aData; | |
| public function addData($sName, $fPercentage) | |
| { | |
| $fPercentage = (float) $fPercentage; | |
| if ($fPercentage < 1 && $fPercentage > 0) { | |
| $fPercentage = $fPercentage * 100; | |
| } | |
| $this->_aData[] = array( | |
| 'percentage' => $fPercentage, | |
| 'name' => $sName | |
| ); | |
| } | |
| public function calculate() | |
| { | |
| uasort($this->_aData, function ($a, $b) { | |
| return $a['percentage'] <=> $b['percentage']; | |
| }); | |
| $iCounter = 0; | |
| foreach ($this->_aData as $aData) { | |
| $iCounter = $iCounter + $aData['percentage']; | |
| } | |
| if ($iCounter != 100) { | |
| return; | |
| } | |
| for ($i=0; $i < count($this->_aData); $i++) { | |
| if ($i == 0) { | |
| $this->_aData[$i]['min'] = 0; | |
| $this->_aData[$i]['max'] = $this->_aData[$i]['percentage']; | |
| continue; | |
| } | |
| $this->_aData[$i]['min'] = $this->_aData[$i - 1]['max']; | |
| $this->_aData[$i]['max'] = $this->_aData[$i - 1]['max'] + $this->_aData[$i]['percentage']; | |
| } | |
| $iRand = mt_rand(1, 100); | |
| foreach ($this->_aData as $aData) { | |
| if ($iRand > $aData['min'] && $iRand <= $aData['max']) { | |
| return $aData['name']; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment