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 ;)
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;
}
Check out eg. http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations for an algorithm description.
精彩评论