我正在玩耍并试图从笛卡尔产品中获得最佳组合。
对于笛卡尔积的每个部分,您必须定义,如果最高值或最低值是最佳值。
例如,在数据集$ a中,最佳值应该是最低值,在$ b和$ c中,最佳值应该是最高值。
到目前为止,这是我的代码,但现在我卡住了
<?php
class Optimizer {
// define different sets
public $a = [
'from' => 1,
'till' => 10,
'steps' => 0.5,
'best' => 'min',
];
public $b = [
'from' => 20,
'till' => 40,
'steps' => 2,
'best' => 'max',
];
public $c = [
'from' => 300,
'till' => 333,
'steps' => 1,
'best' => 'max',
];
// get source variable names
public function getSource() {
return ['a', 'b', 'c'];
}
// generate input data for cartesian product
public function generateOptions() {
$options = [];
foreach($this->getSource() as $varName) {
$data = $this->$varName;
$options[$varName] = range($data['from'], $data['till'], $data['steps']);
}
return $options;
}
// generate cartesian product
public function cartesianProduct() {
$result = [];
$options = $this->generateOptions();
while (list($key, $values) = each($options)) {
if (empty($values)) {
continue;
}
if (empty($result)) {
foreach($values as $value) {
$result[] = [$key => $value];
}
}
else {
$append = [];
foreach($result as &$product) {
$product[$key] = array_shift($values);
$copy = $product;
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
array_unshift($values, $product[$key]);
}
$result = array_merge($result, $append);
}
}
return $result;
}
// get criteria per set
public function getCriterias() {
$criterias = [];
foreach($this->getSource() as $varName) {
$data = $this->$varName;
$criterias[$varName] = $data['best'];
}
return $criterias;
}
// find best possible combination
public function findOptimum() {
$criterias = $this->getCriterias();
$combinations = $this->cartesianProduct();
// ...
}
}
欢迎任何帮助,所以提前谢谢