Last active
June 12, 2016 09:17
-
-
Save richjenks/02ae4195ca9ee39158b1049f4cf4cfb4 to your computer and use it in GitHub Desktop.
Deterministically generates an unpredictable number from the input within a given range
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
| <?php | |
| /** | |
| * Deterministically generates an unpredictable number from the input within a given range | |
| * Intended for int|float but will accept anything | |
| * | |
| * Uses MD5 to generate a number between 0–268435455 then "scales" that number into the desired range | |
| * | |
| * @param mixed $input Variable to use as seed | |
| * @param int|float $min Lower range for desired output | |
| * @param int|float $max Upper range for desired output | |
| * @param int $precision Optional number of decimal digits to round to | |
| * | |
| * @return int|float Number determined by $input | |
| */ | |
| function determine($input, $min, $max, $precision = false) { | |
| // Ensure input is usable | |
| if (!is_string($input)) $input = serialize($input); | |
| // Generate seed - hexdec expects 8-bit signed hexadecimal integer | |
| // and it's easier to work with positive ints, so only use first 7 chars | |
| $hash = md5($input); | |
| $seed = hexdec(substr($hash, 0, 7)); | |
| // Determine result within desired range | |
| $range = $max - $min; | |
| $ratio = 268435455 / $range; | |
| $output = $seed / $ratio + $min; | |
| // Round? | |
| if ($precision !== false && $precision >= 0) | |
| $output = round($output, $precision); | |
| // If number has no decimals, convert to int | |
| if (intval($output) == $output) | |
| $output = intval($output); | |
| return $output; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment