It is different from the coin-changing problem link.
Given a dict x=[a:1,b:2,c:1,d:3,e:2]
, I need to calculate all possible combinations of the keys such that the sum of the values associated with those keys just exceeds or equals a given value, say 5. Just exceeding 5 means that if the selected elements are lower than 5, we can add one more element even if it exceeds 5 but once we exceed or equal 5, no more elements can be added.
There are two issues that are complicating my approach -
- Note that some of the values are repeated-e.g. 1 and 2 each occurs twice and they need to be considered separately.
- Ordering matters in this case.
Ordering matters too so [b,c,d], [b,d,c], [c,b,d], [c,d,b], [d,b,c], [d,c,b]
are all included separately. Ideally ordering matters only when we are exceeding 5 and as long as the sum is exactly 5, ordering doesn't matter.
So some of the solution to the above question are [a,b,c,d]
with sum 7, [a,b,c,e]
with sum 6, [b,c,d]
with sum 6, [d,e]
with sum 5 etc.
How do I approach the problem. I was thinking of using the output from coin changing and then adding one element to each of the resulting lists, but that will not cover all the cases.
EDIT 1: A better way of framing the question might be to find all combinations such that the sum (i) equals 5 or (ii) just exceeds 5 as the sum until the second last element was less than 5 and therefore adding the last element made it greater than 5. Once we have 5 or >5, no additional elements will be added.
EDIT 2: Clarifying the ordering issue. To give a bit of context, the keys are devices and the values are the resources it needs. And the total resources available is 5. And the devices are allocated resources as per their keys i.e. the first key-value pair will be serviced first (sorted as per the key alphabetically). For b
, it needs 2 but say only 1 resource is available - it will be assigned 1 and the remaining 1 will be assigned in the next run (spillover). So when the sum is exactly 5, the order doesn't matter as each gets whatever it wanted and there is no spillover to the next slot. E.g. ed
and de
means both get what they wanted so they should both be included.
But for lists that exceed 5 just due to the addition of the last element, ordering matters as spillover will happen only for the last element. E.g. dce
means d and c get 3 and 1 respectively, and e gets only 1 (with 1 spilling into next run). Similarly ced
means c and d get 1 and 3 respectively, with spillover happening for d as it only gets assigned 1.