Possible grouping of words

陌路散爱 提交于 2019-12-03 09:50:05

Ok, so, it took me quite a while but I think I managed to get this right. I'm really proud, to be honest, since I don't usually do well with algorithms. Anyway, here we go:

function getPossibleGroups($string, $groups) {
    $words = explode(' ', $string);
    $wordCount = count($words);

    if ($groups === 1) {
        return array(array($string));
    } elseif ($groups > $wordCount) {
        return null;
    } elseif ($groups === $wordCount) {
        return array($words);
    }

    $results = array();
    // We get every possible result for the first group
    for ($i = 1; $i <= $wordCount - $groups + 1; $i++) {
        $firstGroup = implode(' ', array_slice($words, 0, $i));

        // Recursively get all posible results for the other groups
        $otherGroups = getPossibleGroups(implode(' ', array_slice($words, $i)), $groups - 1);

        // Merge both things
        $allGroups = array_map(function($v) use ($firstGroup) {
            return array_merge(array($firstGroup), $v);
        }, $otherGroups);

        // Add that to the results variable
        $results = array_merge($results, $allGroups);
    }

    return $results;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!