查找二维数组的组合



我需要一些帮助来生成组合,特别是在商店里,它们是每种产品的变体,例如尺寸和颜色。

假设我们有3个可自定义的产品属性:颜色、尺寸和类型。

对于此特定产品,每个属性都有以下内容:颜色:[红,绿],尺寸:[10,11,15],类型:[人]

现在根据上面的数据,我需要生成6组合,但是如果我们添加另一种类型,它会增加更多。

我已经在黑板上画了两个小时了,现在我正试图想出一个合理的算法来解决这个问题,这个算法速度很快,可以在几秒钟内处理数千个组合。

举个例子:

$options = ['Color' => ['Red', 'Green'], 'Size' => ['10', '11', '15'], 'Type' => ['person']];
$combinations = generateCombinations($options);

generateCombinations需要生成以下输出:

[
['Color' => 'Red', 'Size' => '10', 'Type' => 'person'],
['Color' => 'Red', 'Size' => '11', 'Type' => 'person'],
['Color' => 'Red', 'Size' => '15', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '10', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '11', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '15', 'Type' => 'person']
];

什么算法可以有效地做到这一点,并且无限制地输入"标题"?(当然,我会早些时候强制执行一个限制,但算法应该能够在世界上所有资源的情况下进行无限制的操作)

扩展我的意思:该函数还需要能够以一个具有100个属性行的数组为例,而不仅仅是3个,它需要能够动态地执行此操作,无论输入行的数量如何。

三个foreach循环足以生成所有组合,无论$options:中有多少条目

function generateCombinations(array $options)
{
// Start with one combination of length zero
$all = array(array());
// On each iteration append all possible values of the new key
// to all items in $all; generate this way all the combinations
// one item longer than before
foreach ($options as $key => $values) {
// Move all combinations of length N from $all to $current
$current = $all;
// Start with an empty list of combinations of length N+1
$all = array();
// Combine each combination of length N 
// with all possible values for the (N+1)th key
foreach ($current as $one) {
foreach ($values as $val) {
// Put each new combination in $all (length N+1)
$all[] = array_merge($one, array($key => $val));
}
}
}
return $all;
}

$options = [
'Color' => ['Red', 'Green'],
'Size' => ['10', '11', '15'],
'Type' => ['person'],
'Answer' => ['Yes', 'No'],
];
$combinations = generateCombinations($options);
echo(count($combinations));
# 12

它可能会略有改进,但总的来说,如果你事先不知道$options的长度,它会进行大量重复迭代。如果你提前知道$options中的项目数(假设它是N),那么N嵌套循环是快速的方法

最新更新