显示字符串的可能组合

发布于 2024-09-09 05:34:16 字数 193 浏览 1 评论 0原文

我试图获取一个字符串并显示它的可能组合(在 PHP 中),但同时按每个单词的顺序说出。例如:“你好吗”将返回(一个数组)

How are you
How are
are you
how
you
are

我现在的代码显示所有组合,但我希望它保持它们的顺序而不是翻转单词。有人有任何想法或片段愿意分享吗?谢谢

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 array)

How are you
How are
are you
how
you
are

The code I have now displays all combinations but I am wanting it to keep them in order and not flip words. Any one have any ideas or snippets they care to share? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦幻之岛 2024-09-16 05:34:16

设置两个迭代器并打印它们之间的所有内容。所以像这样:

<?
$str = "How are you";
$words = explode(" ",$str);
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
  for ($j = $i; $j < $num_words; $j++) {
    for ($k = $i; $k <= $j; $k++) {
       print $words[$k] . " ";
    }
    print "\n";
  }
}
?>

输出


How 
How are 
How are you 
are 
are you 
you 

Set two iterators and print everything between them. So something like this:

<?
$str = "How are you";
$words = explode(" ",$str);
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
  for ($j = $i; $j < $num_words; $j++) {
    for ($k = $i; $k <= $j; $k++) {
       print $words[$k] . " ";
    }
    print "\n";
  }
}
?>

Output


How 
How are 
How are you 
are 
are you 
you 
我不会写诗 2024-09-16 05:34:16

我知道这是一篇非常旧的帖子,但另一个答案不是很灵活,所以我想我会带来一个新的答案。

解释

所以你正在寻找所有组合:

(2n) - 1

在您的具体示例中将是:

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

那么我现在如何获得所有组合呢?我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($results = [[]];)),对于每个组合,我们都会遍历我们的数组中的下一个单词,并将每个组合与每个新单词组合成一个新组合。

示例

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

正如您所看到的,总共有: (2^n)-1 组合。另外,从这个方法中,组合数组中留下了一个空数组,因此在返回数组之前,我只使用 array_filter() 删除所有空数组和 array_values() 重新索引整个数组。

代码

<?php

    $str = "how are you";


    function getCombinations($array) {

        //initalize array
        $results = [[]];

        //get all combinations
        foreach ($array as $k => $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) . "<br />";


?>

输出:

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

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

<?php

    $str = "how are you";


    function getCombinations($array) {

        //initalize array
        $results = [[]];

        //get all combinations
        foreach ($array as $k => $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) . "<br />";


?>

output:

how
are
how are
you
how you
are you
how are you
怪我入戏太深 2024-09-16 05:34:16

回答问题不带缺货订单的 PHP 数组组合。在那里,有必要获得数组元素的所有可能组合并存储以下内容。

<?php

$alphabet = array('a','b','c');
$result = array();
$arrResult = array();

// recursively create all possible combinations {
combine($alphabet, $result, $arrResult);

function combine($shiftedAlphabet, &$result, &$arrResult) {
    global $alphabet;

    $currentElementStr = '';
    $currentElementArr = array();
    for($i = 0; $i < count($shiftedAlphabet); ++$i) {
        $newElement = $shiftedAlphabet[$i];
        $currentElementStr .= $newElement;
        $currentElementArr[] = $newElement;

        if(!in_array($currentElementStr, $result)) { // if not duplicated => push it to result
            // find right position {
            $thisCount = count($currentElementArr);
            $indexFrom = 0;
            $indexToInsert = 0;

            // find range of indexes with current count of elements {
            foreach ($arrResult as $arrResultKey => $arrResultValue) {
                $indexToInsert = $arrResultKey + 1;
                if ($thisCount > count($arrResultValue)) {
                    $indexFrom = $indexToInsert;
                }
                if ($thisCount < count($arrResultValue)) {
                    --$indexToInsert;
                    break;
                }
            }
            // find range of indexes with current count of elements }

            // find true index inside true range {
            $trueIndex = $indexToInsert;
            $break = false;
            for($j = $indexFrom; $j < $indexToInsert; ++$j) {
                $trueIndex = $j + 1;
                foreach($arrResult[$j] as $key => $value) {
                    if (array_search($value, $alphabet) > array_search($currentElementArr[$key], $alphabet)) {
                        $break = true;
                        break;
                    }
                }
                if($break) {
                    --$trueIndex;
                    break;
                }
            }
            // find true index inside true range }

            array_splice($result, $trueIndex, 0, $currentElementStr);
            array_splice($arrResult, $trueIndex, 0, array($currentElementArr));
        }
    }

    for($i = 0; $i < count($shiftedAlphabet) - 1; ++$i) {
        $tmpShiftedAlphabet = $shiftedAlphabet; // for combining all possible subcombinations
        array_splice($tmpShiftedAlphabet, $i, 1);
        combine($tmpShiftedAlphabet, $result, $arrResult);
    }
}
// recursively create all possible combinations }
var_dump($result); 

?>

结果示例此处

Answer for question PHP array combination with out back order. There it was necessary to obtain all possible combinations of array elements and store the following.

<?php

$alphabet = array('a','b','c');
$result = array();
$arrResult = array();

// recursively create all possible combinations {
combine($alphabet, $result, $arrResult);

function combine($shiftedAlphabet, &$result, &$arrResult) {
    global $alphabet;

    $currentElementStr = '';
    $currentElementArr = array();
    for($i = 0; $i < count($shiftedAlphabet); ++$i) {
        $newElement = $shiftedAlphabet[$i];
        $currentElementStr .= $newElement;
        $currentElementArr[] = $newElement;

        if(!in_array($currentElementStr, $result)) { // if not duplicated => push it to result
            // find right position {
            $thisCount = count($currentElementArr);
            $indexFrom = 0;
            $indexToInsert = 0;

            // find range of indexes with current count of elements {
            foreach ($arrResult as $arrResultKey => $arrResultValue) {
                $indexToInsert = $arrResultKey + 1;
                if ($thisCount > count($arrResultValue)) {
                    $indexFrom = $indexToInsert;
                }
                if ($thisCount < count($arrResultValue)) {
                    --$indexToInsert;
                    break;
                }
            }
            // find range of indexes with current count of elements }

            // find true index inside true range {
            $trueIndex = $indexToInsert;
            $break = false;
            for($j = $indexFrom; $j < $indexToInsert; ++$j) {
                $trueIndex = $j + 1;
                foreach($arrResult[$j] as $key => $value) {
                    if (array_search($value, $alphabet) > array_search($currentElementArr[$key], $alphabet)) {
                        $break = true;
                        break;
                    }
                }
                if($break) {
                    --$trueIndex;
                    break;
                }
            }
            // find true index inside true range }

            array_splice($result, $trueIndex, 0, $currentElementStr);
            array_splice($arrResult, $trueIndex, 0, array($currentElementArr));
        }
    }

    for($i = 0; $i < count($shiftedAlphabet) - 1; ++$i) {
        $tmpShiftedAlphabet = $shiftedAlphabet; // for combining all possible subcombinations
        array_splice($tmpShiftedAlphabet, $i, 1);
        combine($tmpShiftedAlphabet, $result, $arrResult);
    }
}
// recursively create all possible combinations }
var_dump($result); 

?>

Example result here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文