I have products based on different duration. For example, 1-hour booking is $200, 1 hour and 30 minutes is 280 and additional 30 minutes have $90. I have to find the best possible price according to the duration of the booking. [Minimum booking duration is 1 hour]
Product | Duration | Price |
---|---|---|
1 hr | 60 min | $200 |
1 hr 30 m | 90 min | $280 |
30 m | 30 min | $90 |
*$90 for every additional 30 min which is not the perfect sum of 1 and 1hr 30mins hours
My Solution
Best scenario: If there is a product available for the booking duration, return that product.Eg:- 1 Hour booking
Normal Scenario: My solution was to find all unique combinations of products with a duration that has the perfect sum of the total duration. If there are unique combinations, sort the array in ascending order of total sum and the first combination will be the best price. Eg:- 2 Hour booking- We have two possible combinations 1 Hour * 2 = $400 or 1hr 30 min + 30min = $370. Second one best price
Worst Scenario: If there are no unique combinations find all possible combinations with repetition and sort the array to find the lowest price. An example case of the booking will be:- If customer books for 4 Hours there are a lot of possible combination
JS Code from This answer
function f(A, N, r=[], s=N){
if (s == 0)
return [r];
result = [];
for (let a of A)
if (a <= s)
result = result.concat(
f(A, N, r.slice().concat(a), s-a));
return result;
}
PHP Code from above JS Code:- [Edited - code not working as expected as js code]
protected function findCombination($products, $duration, $currentDuration, $resultTracker=[]){
if ($currentDuration == 0)
return $resultTracker;
$result = [];
foreach ($products as $product){
if ($product->duration <= $currentDuration){
array_push($resultTracker,$product);
array_push($result, $this->findCombination($products, $duration, ($currentDuration - $product->duration),$resultTracker) );
}
}
return $result;
}
What is the best way to approach this problem? What is the best way to find combinations in PHP? Thanks in advance
Other StackOverflow questions