-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

samgak
  • 23,944
  • 4
  • 60
  • 82
Hendry
  • 25
  • 1
  • 6
  • You're wanting to just repeat the sentence a bunch of times inside an array? – Will Jul 20 '16 at 05: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 – Hendry Jul 20 '16 at 05: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"). – samgak Jul 20 '16 at 11:37
  • 1
    Same thing asked only yesterday; possible duplicate of [Permutation programming challenge (Java)](http://stackoverflow.com/questions/38441366/permutation-programming-challenge-java) – m69's been on strike for years Jul 20 '16 at 19:47

1 Answers1

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

Community
  • 1
  • 1
samgak
  • 23,944
  • 4
  • 60
  • 82