这是不是功课:在整个这个场景来到同时处理 PHP串差异和动态限制
This is not homework: Came across this scenario while working on PHP String Differences and Dynamic Restrictions
鉴于字符串 N
的话如何将它们分配到 M
组不改变单词序列?
Given a string of n
words how to distribute them into m
groups without altering the word sequence?
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函数(),无方向(这是假设返回群体多维):
My PHP function() with no direction(it is suppose to return Multi-dimension of groups):
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的功能应该返回:
for above example-2 function is supposed to return:
$groupings = array (
array ('My', 'name', 'is SparKot'),
array ('My', 'name is', 'SparKot'),
array ('My name', 'is', 'SparKot'));
任何提示,以解决这个问题将更加AP preciated。
Any hints to approach this problem will be much appreciated.
进展:
案例:当 =的wordCount groupCount
[解决]
case: when wordCount = groupCount
[solved]
推荐答案
好了,所以,我花了相当长一段时间,但我认为我设法得到这个权利。我真的很自豪,说实话,因为我通常不会做的很好用的算法。总之,在这里我们去:
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;
}
相关推荐
最新文章