【发布时间】:2017-10-05 08:49:03
【问题描述】:
每个人都知道在给定大小为 n 的数组中找到 r 个元素的可能组合,但我需要更进一步。
我有一系列项目。这些项目是数组,有id、name、group_id bla bla bla。
我必须计算不同 group_id 的可能组合。如果 Item 具有相同的 group_id,则它们不能创建组合。
这是我计算所有可能组合的函数;
private function calculateComb(array $temp, int $start, int $end, int $index, int $size)
{
try {
if ($index === $size) {
$this->groups[$size]['combinations'][] = $temp;
return;
}
for ($i = $start; $i < $end; $i++) {
$temp[$index] = $this->combinationItems[$i];
$this->calculateComb($temp, $i + 1, $end, $index + 1, $size);
}
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
我尝试创建一个新函数来计算与 group_id 的可能组合;
private function calculateCombinations(array $temp, int $start, int $end, int $size, int $index, array &$groupIds)
{
try {
if ($index === $size) {
$this->groups[$size]['combinations'][] = $temp;
unset($groupIds[$index]);
return;
}
for ($i = $start; $i < $end; $i++) {
if (in_array($this->combinationItems[$i]['group_id'], $groupIds)) {
$this->calculateCombinations($temp, $i + 1, $end, $size, $index, $groupIds);
} else {
$temp[$index] = $this->combinationItems[$i];
$groupIds[$index] = $this->combinationItems[$i]['group_id'];
$this->calculateCombinations($temp, $i + 1, $end, $size, $index + 1, $groupIds);
}
}
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
但这不起作用。你有什么想法吗?
数组示例;
[
[
'id': 1,
'name': 'Test',
'group_id': 1
], [
'id': 2,
'name': 'Test2',
'group_id': 1
], [
'id': 3,
'name': 'Test3',
'group_id': 2
],
.
.
.
.
.
]
谢谢。
【问题讨论】:
标签: php