-2

I have string like this : hello world new foo.

I need to have array like this:

[
  `helloworld new foo`,
  `hello worldnew foo`,
  `hello world newfoo`,
  `helloworldnew foo`,
  `hello worldnewfoo`,
]

order doesn't matter but i need to have all case that space will be remove in current string.

1
  • 1
    So have you tried anything to create this array from this string? Commented Aug 24, 2014 at 17:43

2 Answers 2

1

You can use recursion to enumerate all the posibilities:

<?php

function combine($words, $acc=array(), $res=array()){
    if(count($words)===0){
        $res[] = join("", $acc);
        return $res;
    }
    if(count($words)===1){
        $res[] = join("", $acc).$words[0];
        return $res;
    }
    $w1 = array_shift($words);
    $res = combine($words,  array_merge($acc, array("$w1")),  $res);
    $res = combine($words,  array_merge($acc, array("$w1 ")), $res);
    return $res;
}

var_dump( combine( explode(' ', 'hello world new foo') ) );

Another possible solution is to represent the N spaces betweeen your words, as bits in a binary number that can be on or off, and then count from 0 to 2^N-1, but I think that in PHP that will be more complex.

NB: the above recursive solution, returns all possible combinations ... so if you have an input array with 4 words, one of the results will have all 4 words joined.

Sign up to request clarification or add additional context in comments.

Comments

1

From what i understood you need all posible combinations with the words given. so:

  1. posible combinations = amountofwords*amountofspaces.
  2. start iteration for amout of posible cominations. -> for(i=0;i<=(words*spaces);i++)
  3. have words in array and spaces found in String so $WordArray = $string.split(" ") and $spaces = substr_count(" ")
  4. start iteration for posible word combinations. for(j=0;j<=words;j++)
  5. start iteration for amount of spaces. for(k=0;k<=spaces;++)
  6. combine all.

but keep in mind that PERMUTATIONS and COMBINATIONS for computer science is what you need to learn first, so the answer above has a lot of sence.

here is a link to get you started. http://cpsc.ualr.edu/srini/DM/chapters/review3.4.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.