Отображение возможных комбинаций строки

Я пытаюсь взять строку и отобразить ее возможные комбинации (в PHP), но при этом говорю по порядку каждого слова. Например: «как дела?» Вернет (массив)

How are you
How are
are you
how
you
are

Код, который у меня сейчас есть, отображает все комбинации, но я хочу, чтобы он содержал их в порядке, а не переворачивал слова. У кого-нибудь есть идеи или отрывки, которыми они хотят поделиться? Спасибо


person mikelbring    schedule 08.07.2010    source источник
comment
Какой код вы используете?   -  person Sourabh    schedule 17.05.2014


Ответы (3)


Установите два итератора и распечатайте все, что между ними. Так что-то вроде этого:

<?
$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 
person Jamie Wong    schedule 08.07.2010
comment
Неэффективности предостаточно! $ str = Как дела; $ words = взорваться (, $ str); $ total_words = количество ($ слов); for ($ i = 0; $ i ‹$ total_words; $ i ++) {for ($ j = $ i + 1; $ j‹ $ total_words; $ j ++) {for ($ k = $ i; $ k ‹$ j ; $ k ++) {вывести $ words [k]. ; } печать \ п; }} - person Marco Ceppi; 08.07.2010
comment
Если вы не хотите лишнего пространства и хотите, чтобы результат был массивом, просто push $words[$k] в массив, а затем implode, добавив результат в массив, который должен быть возвращен. - person Jamie Wong; 08.07.2010
comment
этот метод не работает, если строка содержит более 4 слов, например: 'a b c d' - не вернет комбинацию 'a c d' - person Илья Алисов; 24.10.2019

Ответ на вопрос Комбинация массива 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); 

?>

Пример результата здесь

person Alexey Rytikov    schedule 21.05.2015

person    schedule
comment
но как вы ошибаетесь, он пропустил слово между ними. Должно быть только слева направо согласно OP - person Carl; 18.09.2019