3

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

Dany
  • 2,290
  • 8
  • 35
  • 56

2 Answers2

4

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;
}
Thariama
  • 50,002
  • 13
  • 138
  • 166
1

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

Shadikka
  • 4,116
  • 2
  • 16
  • 19
  • Thank for your answear. I need to change progressively to the number of words and not just the simple permutation. Eg. ("1 2 3") output ("123","12","13","23","1","2","3") – Dany Feb 21 '11 at 11:35
  • Then just combine the algorithm with another that produces all of the combinations! :) – Shadikka Feb 21 '11 at 11:37
  • this is my question :D. I don't know the algorithm that produces all of the combinations :D – Dany Feb 21 '11 at 11:44