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.
3
u/wubblewobble Oct 25 '22 edited Oct 25 '22
The vague (i.e. might be nonsense) idea that I have in my head is to incrementally calculate a lookup table of best combos; the best combo for 1 user, then 2, then 3...
Then when it comes to 28 users, we have the best combos for 1-27 users. We can try 27 + 1, 26 + 2 etc, but I think we'll be able to exclude answers containing more than 2 factors, such as 23 + 1 + 1 + 1 + 1 + 1 because we'll already have the best answer for 5 (i.e. whether five single user licences, or a single 5-user licence is cheaper to get 5 licences).
Not sure if it'll play out and work in reality, but it's my best idea currently. It may (or may not?) be possible to exclude further combos too?
edit: Another thought - is there another more general programming or algorithms subreddit that might better be able to answer this?