从一个单词数组中创建所有可能的句子

时间:2018-01-27 18:23:33

标签: php arrays

来自这个词汇

$words = ['THIS', 'IS', 'AN', 'EXAMPLE'];

我想把句子写成如下:

$sentences = [
    'THIS IS AN EXAMPLE',
    'THIS IS AN',
    'THIS IS',
    'THIS'
];

此外,我想知道如何扭转它的ORDER

喜欢从THIS开始EXAMPLE,如'THIS IS AN EXAMPLE'

或者从EXAMPLE开始THIS,例如'EXAMPLE AN IS THIS'

或从前进到后退,从后退到前进,所以我得到

$sentences = [
    'THIS IS AN EXAMPLE',
    'THIS IS AN',
    'THIS IS',
    'THIS',
    `EXAMPLE AN IS THIS`,
    `EXAMPLE AN IS`,
    `EXAMPLE AN`,
    `EXAMPLE`
];

我尝试的是

    $sentences = [];
    $words = ['THIS', 'IS', 'AN', 'EXAMPLE'];
    $wordscount = count($words);
    $i = 1;
    while ($i < $wordscount) {
        $newword = '';
        foreach ($words as $word) {
            $newword .= "$word ";
        }
        while (in_array($newword, $sentences)) {
            $newword = explode(' ', $newword);
            $newword = array_pop($newword);
            $newword = implode(' ', $newword);
            echo "$newword <br>";
        }
        $sentences[] = $newword;
        $i++;
    }
print_r($sentences);

并且它不完整因为当我加载页面时,Web浏览器和FastCGI CPU使用率每个跳转到50%并且页面显示了内存使用问题。

1 个答案:

答案 0 :(得分:2)

我就是这样做的:

  1. 创建一个循环,该循环将迭代数组中的项目总数。
  2. 通过迭代值减少数组并将其内插到返回值中 阵列。
  3. 然后再次执行相同操作,但只需使用反向数组并将它们合并。

    例如:

    <?php
    function join_words($words) {
        $return = [];
        for ($i=0; $i < count($words); $i++) {
            $return[] = implode(' ', array_slice($words, 0, $i+1));
        }
        return $return;
    }
    
    $words = ['THIS', 'IS', 'AN', 'EXAMPLE'];
    
    $result = [];
    $result = array_merge($result, join_words($words));
    $result = array_merge($result, join_words(array_reverse($words)));
    
    print_r($result);
    

    https://3v4l.org/vG7tj

    <强>结果:

    Array
    (
        [0] => THIS
        [1] => THIS IS
        [2] => THIS IS AN
        [3] => THIS IS AN EXAMPLE
        [4] => EXAMPLE
        [5] => EXAMPLE AN
        [6] => EXAMPLE AN IS
        [7] => EXAMPLE AN IS THIS
    )
    

    如果你想要如图所示的确切输出,你应该在合并它之前反转它。

    $result = [];
    $result = array_merge($result, array_reverse(join_words($words)));
    $result = array_merge($result, array_reverse(join_words(array_reverse($words))));
    

    https://3v4l.org/R4LDo

    <强>结果:

    Array
    (
        [0] => THIS IS AN EXAMPLE
        [1] => THIS IS AN
        [2] => THIS IS
        [3] => THIS
        [4] => EXAMPLE AN IS THIS
        [5] => EXAMPLE AN IS
        [6] => EXAMPLE AN
        [7] => EXAMPLE
    )