Create all possible combinations

I have an application in which users can customize the product that they are going to purchase by selecting options from the menu. This menu has many sections, and each section can have a list of checkboxes for multitasking or radio buttons when only one parameter can be selected. The user must select at least one option in each section. The menu structure looks something like this:

$sections = array();

$sections[1] = array(
    'multichoice' => true,
    'options' => array('A','B','C')
);

$sections[2] = array(
    'multichoice' => false,
    'options' => array('A','B','C','D')
);

$sections[3] = array(
    'multichoice' => false,
    'options' => array('A','B')
);

$sections[4] = array(
    'multichoice' => true,
    'options' => array('A','B','C','D','E')
);

Example: A sandwich is a product. The type of bread is one "section" of your choice. You may need light bread, dark bread, milk bread, or vegetarian bread. Only one option can be selected in this section. Now in the "Salad" section you can select more than one type of salad to add to the bread.

, , , . ​​:

$combinations = array(
    array(
        1 => array('A','B'),
        2 => 'A',
        3 => 'A',
        4 => array('B','D','E')
    ),
    array(
        1 => array('A'),
        2 => 'B',
        3 => 'A',
        4 => array('A','B')
    )
// etc...
);

, , , . , ( ):

...

function generate(){
    $result = array();
    $ids = array();
    foreach($this->getSections() as $sect){
        $items = $this->getSectionOptions($sect['id']);
        if($sect['multi']=='N'){
            $item = $items[rand(0, count($items)-1)];
            $result[$sect['id']] = $item['id'];
            $ids[] = $item['id'];
        } else {
            $how_many = rand(1,count($items));
            shuffle($items);
            for($i=1;$i<=$how_many;$i++){
                $item = array_shift($items);
                $result[$sect['id']][] = $item['id'];
                $ids[] = $item['id'];
            }
        }
    }
    sort($ids);
    return array(
        'hash' => implode(',',$ids),
        'items' => $result
    );
}

function generateMany($attempts=1000){
    $result = array();
    $hashes = array();
    for($i=1;$i<=$attempts;$i++){
        $combine = $this->generate();
        if(!in_array($combine['hash'],$hashes)){
            $result[] = $combine['items'];
            $hashes[] = $combine['hash'];
        }
    }
    return $result;
}


...

, . , . , (.. E, B, A , B, E, A)

+4
1

, , !

, , : D

-, ! ( )

, , A, B, C. :

A B
A B C
A C
B
B C
C

, , . (A)

B
B C
C
---
B
B C
C

, ... (B)

C
---
C

, .

, script, , , .

! !

, , , 1

!

100000 126 : 14.410287857056

- ping me: D

https://gist.github.com/MLoureiro/a0ecd1ef477e08b6b83a

+3

Source: https://habr.com/ru/post/1610995/


All Articles