PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 4.25 Finding All Element Combinations of an Array

4.25.1 Problem

You want to find all combinations of sets containing some or all of the elements in an array, also called the power set.

4.25.2 Solution

Use the pc_array_power_set( ) function shown in Example 4-5.

Example 4-5. pc_array_power_set( )
function pc_array_power_set($array) {
    // initialize by adding the empty set
    $results = array(array( ));

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return $results;
}

This returns an array of arrays holding every combination of elements, including the empty set. For example:

$set = array('A', 'B', 'C');
$power_set = pc_array_power_set($set);

$power_set contains eight arrays:

array( );
array('A');
array('B');
array('C');
array('A', 'B');
array('A', 'C');
array('B', 'C');
array('A', 'B', 'C');

4.25.3 Discussion

First, you include the empty set, {} , in the results. After all, one potential combination of a set is to take no elements from it.

The rest of this function relies on the nature of combinations and PHP's implementation of foreach. Each new element added to the array increases the number of combinations. The new combinations are all the old combinations alongside the new element; a two-element array containing A and B generates four possible combinations: {}, {A}, {B}, and {A, B}. Adding C to this set keeps the four previous combinations but also adds four new combinations: {C}, {A, C}, {B, C}, and {A, B, C}.

Therefore, the outer foreach loop moves through every element of the list; the inner foreach loops through every previous combination created by earlier elements. This is the tricky bit; you need to know exactly how PHP behaves during a foreach.

The array_merge( ) function combines the element with the earlier combinations. Note, however, the $results array added to the new array with array_push() is the one that's cycled through in the foreach. Normally, adding entries to $results causes an infinite loop, but not in PHP, because PHP operates over a copy of the original list. But, when you pop back up a level to the outer loop, and reexecute the foreach with the next $element, it's reset. So, you can operate directly on $results in place and use it as a stack to hold your combinations. By keeping everything as arrays, you're given far more flexibility when it comes to printing out or further subdividing the combinations at a later time.

To remove the empty set, replace the opening line of:

// initialize by adding the empty set
$results = array(array( ));

with:

// initialize by adding the first element
$results = array(array(array_pop($array)));

Since a one-element array has only one combination — itself — popping off an element is identical to making the first pass through the loop. The double foreach statements don't know they're really starting their processing with the second element in the array.

To print the results with tabs between elements inside the combination and returns between each combination, use the following:

$array = array('Adam', 'Bret', 'Ceff', 'Dave');

foreach (pc_array_power_set($array) as $combination) {
    print join("\t", $combination) . "\n";
}

Here's how to print only three-element sized combinations:

foreach (pc_array_power_set($set) as $combination) {
    if (3 == count($combination)) {
        print join("\t", $combination) . "\n";
    }
}

Iterating over a large set of elements takes a long time. A set of n elements generates 2n+1 sets. In other words, as n grows by 1, the number of elements doubles.

4.25.4 See Also

Recipe 4.26 for a function that finds all permutation of an array.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    4.1 Introduction
    Recipe 4.2 Specifying an Array Not Beginning at Element 0
    Recipe 4.3 Storing Multiple Elements per Key in an Array
    Recipe 4.4 Initializing an Array to a Range of Integers
    Recipe 4.5 Iterating Through an Array
    Recipe 4.6 Deleting Elements from an Array
    Recipe 4.7 Changing Array Size
    Recipe 4.8 Appending One Array to Another
    Recipe 4.9 Turning an Array into a String
    Recipe 4.10 Printing an Array with Commas
    Recipe 4.11 Checking if a Key Is in an Array
    Recipe 4.12 Checking if an Element Is in an Array
    Recipe 4.13 Finding the Position of an Element in an Array
    Recipe 4.14 Finding Elements That Pass a Certain Test
    Recipe 4.15 Finding the Largest or Smallest Valued Element in an Array
    Recipe 4.16 Reversing an Array
    Recipe 4.17 Sorting an Array
    Recipe 4.18 Sorting an Array by a Computable Field
    Recipe 4.19 Sorting Multiple Arrays
    Recipe 4.20 Sorting an Array Using a Method Instead of a Function
    Recipe 4.21 Randomizing an Array
    Recipe 4.22 Shuffling a Deck of Cards
    Recipe 4.23 Removing Duplicate Elements from an Array
    Recipe 4.24 Finding the Union, Intersection, or Difference of Two Arrays
    Recipe 4.25 Finding All Element Combinations of an Array
    Recipe 4.26 Finding All Permutations of an Array
    Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele