Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: min(one, five)?
(Example: nine)

The Note You're Voting On

josh at joshstrike dot com
14 years ago
More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length:

<?php
echo masksOf(3,10);

function
masksOf($n,$bits) {
$u = pow(2,$bits)-1; //start value, full flags on.
$masks = array();
while (
$u>0) {
$z = numflags($u);
if (
$z==$n) array_push($masks,$u);
$u--;
}
return (
$masks);
}

function
numflags($n) {
$k = 0;
while (
$n) {
$k += $n & 1;
$n = $n >> 1;
}
return (
$k);

// alternately:
// $u = 0;
// for ($k=1;$k<=$n;$k*=2) {
// $u+=($n&$k?1:0);
// }
// return ($u);
}
?>

<< Back to user notes page

To Top