微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 可能的单词分组

这不是作业:在工作时遇到这种情况
PHP String Differences and Dynamic Restrictions

给定一串n个单词如何在不改变单词序列的情况下将它们分配到m个组中?

Example 1:
String: "My name is SparKot"
Groups: 2 (string is split in to two strings)

Possible groups will be:
('My', 'name is SparKot'), 
('My name', 'is SparKot'),
('My name is', 'SparKot')

用相同的字符串

Example 2:
String: "My name is SparKot"
Groups: 3 (string will be split in to three strings)

Possible groups will be:
('My', 'name', 'is SparKot'),
('My', 'name is', 'SparKot'),
('My name', 'is', 'SparKot')

我的PHP函数()没有方向(假设返回多维组):

function get_possible_groups ($orgWords, $groupCount, &$status) {

    $words = explode (' ', $orgWords);
    $wordCount = count($words);

    if ($wordCount < $groupCount) {
        $status = -1;
        return;
    } else if ($wordCount === $groupCount) {
        $status = 0;
        return (array_chunk($words, 1));
    }

    for ($idx =0; $idx < $wordCount; $idx) {
        for ($jdx =0; $jdx < $groupCount; $jdx++) {

        }
    }
//  append all arrays to form multidimension array
//  return groupings[][] array
}
$status =0;

$groupings = get_possible_groups('My name is SparKot', 4, $status);

var_dump($groupings);

对于上面的示例-2函数应该返回:

$groupings = array (
        array ('My', 'name', 'is SparKot'),
        array ('My', 'name is', 'SparKot'),
        array ('My name', 'is', 'SparKot'));

任何提示解决这个问题都将非常感激.

进展:

> case:当wordCount = groupCount [已解决]

解决方法:

好吧,所以,我花了很长时间,但我认为我设法做到了这一点.老实说,我真的很自豪,因为我通常不会很好地使用算法.无论如何,我们走了:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐