John Davidson

Calculate different permutations of prices using PHP

0 comments
Message:


I'm working on a PHP script that needs to create a JSON file that includes an array of prices made up of a variety of other prices added together.


For example, I might have a base price of 50 and then a series of add-ons at 5, 10, 15, etc.


So my array would be a combination of all the possible ways those numbers can be added together, 50 + 5, 50 + 5 + 10, and so on.


I also then have a series of multipliers, 1, 3, 6, 12 which have to be multiplied by every number created by the previous step, 3 x (50 + 5), 6 x (50 + 5), and so on.


What I have so far (which involves using the Violet PHP streaming JSON encoder) works up to a certain point – about 16 add-ons – but after that, I get memory exhausted or max execution time errors.


I've tried bumping up the limits but that only works for another one or two extra add-ons and then I run into the same problem, and that's on my local version of the site where I can allocate as many resources as I like. I don't have that luxury on the server the site is hosted on.


I'm not sure it's worth posting the code I'm using at the moment because I think it probably has to be started over from scratch.


And I don't really know how to approach the task so that the script can confidently handle any number (within reason) of add-ons without the server running out of resources.



My Answer:
One approach you could take is to use a recursive function to generate all possible permutations of prices. Here's an example of how you could do this:

php
function generatePermutations($basePrice, $addons, $multipliers, $currentPrice = 0, $currentIndex = 0) {
if ($currentIndex == count($addons)) {
foreach ($multipliers as $multiplier) {
$finalPrice = ($currentPrice + $basePrice) * $multiplier;
echo $finalPrice . "\n";
}
return;
}

generatePermutations($basePrice, $addons, $multipliers, $currentPrice, $currentIndex + 1);
generatePermutations($basePrice, $addons, $multipliers, $currentPrice + $addons[$currentIndex], $currentIndex + 1);
}

$basePrice = 50;
$addons = [5, 10, 15];
$multipliers = [1, 3, 6, 12];

generatePermutations($basePrice, $addons, $multipliers);


This function will recursively generate all possible permutations of prices by adding each addon to the current price or skipping it, and then multiplying the final price by each multiplier. This approach should be more memory-efficient than generating all permutations upfront before processing them.

You can adjust the `$addons` array to include more add-ons as needed, and the function should be able to handle a reasonable number of add-ons without running into memory or execution time issues.

Rate this post

5 of 5 based on 5941 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us