Created
December 2, 2016 11:27
-
-
Save jlis/c8312cdca0cf4d6eb7bf103c6fcd543b to your computer and use it in GitHub Desktop.
Calculate a feature percentage with numeric (incremented) user id
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 | |
| $feature = 'test'; | |
| $limit = 100; | |
| $percentage = 0.5; // ie. 0,5 | |
| function calculatePercentage($id) { | |
| $hex = hash('sha256', $id); | |
| $len = min(40, strlen($hex)); | |
| $vMax = 1 << $len; | |
| $v = 0; | |
| for ($i = 0; $i < $len; $i++) { | |
| $bit = hexdec($hex[$i]) < 8 ? 0 : 1; | |
| $v = ($v << 1) + $bit; | |
| } | |
| $w = $v / $vMax; | |
| return $w; | |
| } | |
| $numOn = 0; | |
| $numOff = 0; | |
| for ($i = 0; $i < $limit; $i++) { | |
| if (calculatePercentage(sprintf('%s.%d', $feature, $i)) < $percentage) { | |
| $numOn++; | |
| } else { | |
| $numOff++; | |
| } | |
| } | |
| echo sprintf('On: [%d] | Off: [%d]', $numOn, $numOff); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
crc32(sprintf('%s.%d', $feature, $i)) % 100 < $percentageworks also when$percentage = 50