手掌心
不要将每个附加组件视为特殊情况,而是一般地识别每个附加组件。如果您使用面向对象的结构,这可能看起来像一个AddOn接口或基类,其中有一个方法返回其成本和所需的任何其他属性。然后,您只需从基本价格开始,然后循环遍历乘数(如果没有乘数,则为 1)。该解决方案的关键部分是使用递归和迭代的组合来确定附加组件的所有可能的排列。像这样的东西:class AddOn{ private $price, $description; public function __construct(float $price, string $description){ $this->price=$price; $this->description=$description; } public function getPrice(): float{ return $this->price; } public function getDescription(): string{ return $this->description; }}class ProductConfiguration{ private $basePrice, $multiplier, $addOns; public function __construct(float $basePrice, int $multiplier, array $addOns){ $this->basePrice=$basePrice; $this->multiplier=$multiplier; $this->addOns=$addOns; } public function getPrice(): float{ $price=$this->basePrice*$this->multiplier; foreach($this->addOns as $addOn) $price+=$addOn->getPrice(); return $price; } public function getMultiplier(): int{ return $this->multiplier; } public function getAddOns(): array{ return $this->addOns; }}$basePrice=10;$addOns=[ new AddOn(5, "AddOn A"), new AddOn(1, "AddOn B"), new AddOn(20, "AddOn C")];$permutations=[[]]; //Include an empty set as a possible option//This recursive function accepts the base set of add-ons, a reference to an array to which to add any permutations, and a base parameter that will be used only internally to pass the parent permutationsfunction getPermutations(array $addOns, array &$permutations, array $base=[]): void{ //array_unshift removes the first item from the array, since this is done first, it will prevent duplicate combinations that differ only in order while(($current=array_shift($addOns))!==null){ //Combine the parent permutation($base) with the next value in the array to create this permutation $permutation=array_merge($base, [$current]); $permutations[]=$permutation; //Push to the referenced array getPermutations($addOns, $permutations, $permutation); //Recursively compute all permutations that begin with the current one } //Subsequent iterations of the while loop will handle each value in the array as the initial value without each other value}getPermutations($addOns, $permutations);$multipliers=[ 1, 3, 6, 12];$configurations=[];foreach($multipliers as $m){ foreach($permutations as $p){ $configurations[]=new ProductConfiguration($basePrice, $m, $p); }}//$configurations now contains the set of (de-duplicated) product configurations(each possible combination)