-2

Hi there I was wondering if I could create an array that accept a sentence and turns it into an array for example

$sentence = 'my name is john'

then the array will be:

$arr = {my name is john, 
my name is, my name john, my is john, name is john, 
my name, my is, my john, name is, name john, is john, 
my, name, is, john}

anyone could help me with the implementation in any kind of loop that would be great because im currently creating a simple search engine algorithm thx :D

4
  • You're wanting to just repeat the sentence a bunch of times inside an array? Commented Jul 20, 2016 at 5:14
  • yes @user866762 but in different length tho as you can see from the above, the first loop is the whole sentence, then partial sentence with the length of length - 1, then partial sentence with the length of length - 2, up to single word Commented Jul 20, 2016 at 5:25
  • 1
    Think of it as a n-bit integer, with each bit corresponding to whether a word is included or not. Loop from 1 to (1 << n) - 1, which in this case is 1 to 15, to get your 15 sentences (you only have 14, because you missed out "my name john"). Commented Jul 20, 2016 at 11:37
  • 1
    Same thing asked only yesterday; possible duplicate of Permutation programming challenge (Java) Commented Jul 20, 2016 at 19:47

1 Answer 1

1

Think of it as a n-bit integer, with each bit corresponding to whether a word is included or not in a given string in your array. Loop from 1 to (1 << n) - 1, which in this case is 1 to 15, to get your 15 word lists, and for each one, check each of the bits in the integer and add the corresponding word if the corresponding bit is set:

function getCombinations($sentence)
{
    $words = explode(" ", $sentence);
    $combinations = array();
    for($i = 1; $i < (1 << count($words)); $i++)
    {
        $wordlist = "";
        for($j = 0; $j < count($words); $j++)
        {
            if($i & (1 << $j))
            {
                $wordlist = $wordlist . " " . $words[$j];
            }
        }
        array_push($combinations, substr($wordlist, 1));
    }
    return $combinations;
}

$a = "my name is john";
print_r(getCombinations($a));

If you want your strings to be sorted by the number of words, add an extra loop for the word counts:

for($wordcount = count($words); $wordcount >= 1; $wordcount--)
{
    for($i = 1; $i < (1 << count($words)); $i++)
    {
        if(NumberOfSetBits($i) == $wordcount)
        {               
            $wordlist = "";
            // generate word list..
        }
    }
}

NumbeOfSetBits function from here

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

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.