php - Check if in a set of numbers, a number n is equal to sum of its subset -


i have array :

$permissionvals = array (1,2,4,8,16,32); 

and variable

$effectivepermission = 13; 

i need check whether variable equal sum of subset of given array of numbers in optimized way.

subset sum doesn't seems work me here.

assuming $permissionvals contains powers of 2, can use bit comparison:

$permissionvals = array(1,2,4,8,16,32); $target = 13; $res = array();  foreach ($permissionvals $val) {     if ($target & $val) $res[] = $val; }  if (array_sum($res) == $target)     print_r($res); else      echo 'the message want'; 

a variant stop foreach loop when sum reached. (useful if $permissionvals big):

$sum = 0; $message = 'the message want';  foreach ($permissionvals $val) {     if ($target & $val) {         $res[] = $val;         $sum += $val;     }     if ($sum == $target) {     $message = '';     print_r($res);     break;     } }  echo $message; 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -