Display possible combinations of string

前端 未结 3 1421
谎友^
谎友^ 2020-11-28 13:54

I am trying to take a string and display the possible combinations of it (in PHP), but while saying in order of each word. For example: \"how are you\" would return (an arra

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 14:54

    I know this is a very old post, but the other answer isn't very flexible, so I thought I would bring a new answer in.


    Explanation

    So you are looking for all combinations which would be:

    (2n) - 1

    Which in your specific example would be:

    (23) - 1 = (8) - 1 = 7

    So how do I get all combinations now? We loop through all our combinations, which we already have(Starting off with one combination, an "empty combination" ($results = [[]];)), and for each combination we go through our next word from the array and combine each combination with each new word to a new combination.

    Example

    Array with the words/numbers (Empty array is '[]'):
    [1, 2, 3]
    

                                   //↓new combinations for the next iteration
                                   │
    iteration 0:
    
        Combinations:
                      - []         │  -> []
                                      │
    iteration 1:        ┌─────────────┤
                        │             │
        Combinations:   v             v
                      - []    + 1  │  -> [1]    
                                      │
    iteration 2:        ┌─────────────┤
                        │             │
        Combinations:   v             v
                      - []    + 2  │  -> [2]
                      - [1]   + 2  │  -> [1,2]    
                                      │
    iteration 3:        ┌─────────────┤
                        │             │
        Combinations:   v             v
                      - []    + 3  │  -> [3]
                      - [1]   + 3  │  -> [1,3]
                      - [2]   + 3  │  -> [2,3]         
                      - [1,2] + 3  │  -> [1,2,3]    
                                   //^ All combinations here
    

    So as you can see there is always: (2^n)-1 combinations in total. Also from this method there is an empty array left in the combination array, so before I return the array I just use array_filter() to remove all empty arrays and array_values() to reindex the entire array.

    Code

     $element) {
                foreach ($results as $combination)
                    $results[] =  $combination + [$k => $element];
            }
    
            //return filtered array
            return array_values(array_filter($results));
    
        }
    
    
        $arr = getCombinations(explode(" ", $str));
    
        foreach($arr as $v)
            echo implode(" ", $v) . "
    "; ?>

    output:

    how
    are
    how are
    you
    how you
    are you
    how are you
    

提交回复
热议问题