これは宿題ではありません: PHP 文字列の違いと動的制限に取り組んでいるときに、このシナリオに遭遇しました
一連の単語が与えられた場合、単語の順序を変更せずにそれらをグループ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);
上記の example-2 関数の場合、次のように返されます。
$groupings = array (
array ('My', 'name', 'is SparKot'),
array ('My', 'name is', 'SparKot'),
array ('My name', 'is', 'SparKot'));
この問題に取り組むためのヒントは大歓迎です。
進捗:
- ケース:
wordCount = groupCount
[解決済み]