1 回答

TA貢獻1942條經驗 獲得超3個贊
不要將每個附加組件視為特殊情況,而是一般地識別每個附加組件。如果您使用面向對象的結構,這可能看起來像一個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 permutations
function 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)
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報