Skip to content

Instantly share code, notes, and snippets.

@jlis
Created December 2, 2016 11:27
Show Gist options
  • Select an option

  • Save jlis/c8312cdca0cf4d6eb7bf103c6fcd543b to your computer and use it in GitHub Desktop.

Select an option

Save jlis/c8312cdca0cf4d6eb7bf103c6fcd543b to your computer and use it in GitHub Desktop.
Calculate a feature percentage with numeric (incremented) user id
<?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);
@jlis
Copy link
Copy Markdown
Author

jlis commented Dec 2, 2016

crc32(sprintf('%s.%d', $feature, $i)) % 100 < $percentage works also when $percentage = 50

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment