Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

progressive word combination of a string

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 ;)

like image 925
Dany Avatar asked Dec 06 '25 22:12

Dany


2 Answers

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;
}
like image 77
Thariama Avatar answered Dec 08 '25 10:12

Thariama


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

like image 45
Shadikka Avatar answered Dec 08 '25 11:12

Shadikka