PHPverse 2025

Voting

: three minus three?
(Example: nine)

The Note You're Voting On

pineappleclock at gmail dot com
16 years ago
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;
}
?>

<< Back to user notes page

To Top