note 88408 modified in function.shuffle by danbrown

From: Date: Thu, 22 Jan 2009 18:07:36 +0000
Subject: note 88408 modified in function.shuffle by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-149670@lists.php.net to get a copy of this message
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm: <?php /** * Returns the power set of a one dimensional array, * a 2-D array. * array(a,b,c) -> * array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c)) */ function powerSet($in,$minLength = 1) { $count = count($in); $members = pow(2,$count); $return = array(); for ($i = 0; $i < $members; $i++) { $b = sprintf("%0".$count."b",$i); $out = array(); for ($j = 0; $j < $count; $j++) { if ($b{$j} == '1') $out[] = $in[$j]; } if (count($out) >= $minLength) { $return[] = $out; } } return $return; } ?> --was-- If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm: /** * Returns the power set of a one dimensional array, * a 2-D array. * array(a,b,c) -> * array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c)) */ function powerSet($in,$minLength = 1) { $count = count($in); $members = pow(2,$count); $return = array(); for ($i = 0; $i < $members; $i++) { $b = sprintf("%0".$count."b",$i); $out = array(); for ($j = 0; $j < $count; $j++) { if ($b{$j} == '1') $out[] = $in[$j]; } if (count($out) >= $minLength) { $return[] = $out; } } return $return; } http://php.net/manual/en/function.shuffle.php

« previous php.notes (#149670) next »