progressive word combination of a string

一个人想着一个人 提交于 2019-12-07 19:36:31

问题


I need to obtain a progressive word combination of a string.

E.g. "this is string" Output: "this is string" "this is" "this string" "is string" "this" "is" "string"

Do you know similar algorithm? (I need it in php language) Thanks ;)


回答1:


This is a simple code solution to your problem. I concatenate each string recoursively to the remaining ones in the array.

$string = "this is a string";  
$strings = explode(' ', $string);

// print result
print_r(concat($strings, ""));

// delivers result as array
function concat(array $array, $base_string) {

    $results = array();
    $count = count($array);
    $b = 0;
    foreach ($array as $key => $elem){
        $new_string = $base_string . " " . $elem;
        $results[] = $new_string;
        $new_array = $array;

        unset($new_array[$key]);

        $results = array_merge($results, concat ($new_array, $new_string));

    }
    return $results;
}



回答2:


Check out eg. http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations for an algorithm description.



来源:https://stackoverflow.com/questions/5065286/progressive-word-combination-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!