r/PHPhelp • u/ser_89 • Oct 25 '22
Greedy Algorithm with added functionality.
I have a specific function that I require assistance with. I am busy with a project where licenses need to be allocated based on a specific quantity as per user input. The licenses are bundled as an example 1 user, 5 users, 10 users 20 users and 50 users. If the input is 20 it's easy to determine that the license that needs to be allocated is one for 20 users. If the input is 27 I can use a greedy algorithm to determine the best way to allocate would be 1 x 20 users, 1 x 5 users and 2 x 1 user.
My problem now though is that in most cases there is a threshold where it is actually more cost effective to rather allocate a license that caters for more users compared to the input specified. For example 19 users it is more cost effective to provide a license for 20 compared to 1 x 10 users, 1 x 5 users and 4 x 1 user.
What would be the best approach to approach the above and avoid unnecessary recalculation and comparison. The obvious approach is to run the greedy algorithm and get a total cost and compare the cost of another license where total users > users as per input.
The issue I see is already making me scratch my head. Is for example 28 users. I already know the most cost effective approach is 1 x 20 users and 1 x 10 users. The next license up is 50 users. So it will be too expensive. However the greedy algorithm gives me 1 x 20 user, 1 x 5 user and lastly 3 x 1 user.
Any assistance will be greatly appreciated.
1
u/MateusAzevedo Oct 25 '22
I don't have anything specific to the problem to help, but I want to mention this is a similar problem to when you withdraw money from ATMs. It isn't very advisable to always give the same bills for a given amount of money, or the ATM will likely run out of some of them pretty fast. AFAIK, there's an algorithm to calculate multiple possibilities and decide which to use based on how many of each bills are left.
Maybe that's something you can look for: compute all the possible license combo, use the one that cost less.