【问题标题】:Get all ordered, contiguous combinations of an array's elements获取数组元素的所有有序、连续的组合
【发布时间】:2019-04-08 05:01:40
【问题描述】:

我想得到一个句子中所有可能的短语(实际存在的)为

$str = 'word1 word2 word3 word4';

$output = array ('word1 word2 word3', 'word1 word2', 
                 'word2 word3 word4', 'word3 word4', 'word2 word3');

为此,我创建了一个单词数组,

$words = explode(' ', $str);

这里有几个问题解释了如何构建数组元素的所有组合,但是如何在保持原始顺序的同时进行所有组合?

如何从$words 中创建$output 的数组?

【问题讨论】:

  • @mayursaptal 通过忽略特定尺寸的顺序,这与我想要的相反。我想要同一订单的不同尺寸。
  • 为什么word1 word3 不是预期输出的可能组合?
  • @MadhurBhaiya 因为它不是按顺序排列的。我想获取句子(字符串)中的所有短语(子字符串)。
  • 为什么word1 word2 word3 word4 不是预期输出之一?

标签: php arrays algorithm


【解决方案1】:
  • 我们可以使用array_slice() 函数从输入数组中取出一个块。它还将确保保持顺序,以及连续值的组合(根据原始数组)。
  • 现在,我们需要使用两个嵌套循环来确定块的$offset 和$length。
  • $offset value 基本上会从头到尾循环; $length 最初是偏移量中剩余值的计数,并且最多会递减 2(我们不希望单个值作为组合)。

尝试以下方法 (Rextester DEMO):

$str = 'word1 word2 word3 word4';
$words = explode(' ', $str);

$combinations = array();

// offset from start to end of the words
for($offset = 0; $offset < count($words); $offset++) {

    // length from available remaining words to 2
    for ($length = count($words) - $offset; $length > 1; $length--) {

        // get the array chunk
        $combinations[] = array_slice($words, $offset, $length);
    }
}

// test output
print_r($combinations);

输出:

Array
(
    [0] => Array
        (
            [0] => word1
            [1] => word2
            [2] => word3
            [3] => word4
        )

    [1] => Array
        (
            [0] => word1
            [1] => word2
            [2] => word3
        )

    [2] => Array
        (
            [0] => word1
            [1] => word2
        )

    [3] => Array
        (
            [0] => word2
            [1] => word3
            [2] => word4
        )

    [4] => Array
        (
            [0] => word2
            [1] => word3
        )

    [5] => Array
        (
            [0] => word3
            [1] => word4
        )

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多