如果有人能帮我做循环编码的话,可以用顺序排列算法


Permutation in order algorithm if anyone could help me with the loop coding

嗨,我想知道是否可以创建一个接受句子的数组,并将其转换为数组,例如

$sentence = 'my name is john'

那么阵列将是:

$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}

任何人都可以帮助我在任何类型的循环中实现,这将是非常棒的,因为我目前正在创建一个简单的搜索引擎算法thx:D

将其视为一个n位整数,每个位对应于一个单词是否包含在数组中的给定字符串中。从1循环到(1<<n)-1,在这种情况下是1到15,以获得15个单词列表,对于每个单词,检查整数中的每个位,如果设置了相应的位,则添加相应的单词:

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

如果您希望字符串按字数排序,请为字数添加一个额外的循环:

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

NumbeOfSetBits函数从这里