php - 可能的词组

标签 php arrays algorithm multidimensional-array explode

这不是家庭作业:在工作时遇到这种情况 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() 没有方向(假设返回多维组):

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

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

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

任何解决此问题的提示都将不胜感激。

进度:

  • 案例:当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;
}

关于php - 可能的词组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15144811/

相关文章:

algorithm - 最长公共(public)子序列 (LCS) 长度的 Fast(er) 算法

vb.net - 泛化递增嵌套循环算法

java - 比较 2 个列表中的元素时如何避免 O(N^2)?

php - 循环遍历 $_SESSION 变量时搜索字符串

java - 有没有办法在每一行打印出数组中不同数量的元素

php - AJAX:显示不同的 SQL 查询

c - 将固定数量的东西分布到 M*N 的网格中

javascript - 如何在 JavaScript 中将所有数组值填充到单个索引

php - 从 PHP 获取 CSS 样式

php - Wordpress:计算标签使用的总次数