A slightly more challenging one compared to my previous challenge. Given a list of positive integers (>0) and the positive integer m
, output a list of positive integers that are capped values of the input values so that the sum of the capped values equals m
. Cap the highest values first. And keep the same order.
Cases
(Given 'list' and 'sum' output 'list')
- Given
4, 2
and6
output4, 2
no capping needed (ncn), keep order (ko) - Given
2, 4
and6
output2, 4
ncn, ko - Given
3, 3
and6
output3, 3
ncn - Given
3, 3
and7
output3, 3
ncn
Then this:
- Given
4, 2
and5
output3, 2
cap the highest (cth), ko - Given
2, 4
and5
output2, 3
cth, ko - Given
3, 3
and5
output3, 2
or2, 3
cap any of the highest (cath)
Then this:
- Given
5, 4, 2
and10
output4, 4, 2
cth, ko - Given
2, 4, 5
and10
output2, 4, 4
cth, ko - Given
4, 4, 2
and7
output3, 2, 2
or2, 3, 2
cth, cath, ko - Given
4, 2, 4
and7
output3, 2, 2
or2, 2, 3
cth, cath, ko
Then this:
- Given
4, 4, 2
and5
output2, 2, 1
or any permutation (oap) - Given
2, 4, 4
and5
output1, 2, 2
oap - Given
4, 4, 2
and4
output1, 2, 1
oap - Given
2, 4, 4
and4
output1, 1, 2
oap - Given
70, 80, 90
and10
output3, 3, 4
oap
Then this:
- Given
4, 2, 4
and2
output an error or a falsy value, because the sum of 3 positive integers cannot be 2.
Rules
- Both input and output are all about positive integers (>0)
- The number of values in the input and output list are equal.
- The sum of the output values is exactly equal to
m
or less thanm
only if the sum of the input values was already lower. - If the sum of the values in the input list is already lower then or equal to
m
, no capping is needed. (ncn) - Cap the highest values first (cth)
- When multiple values are the highest value and equally high, it doesn't matter which you cap. (cath)
- The capped values in the output list have to be in the same order as their original values in the input list. (ko)
- When at some point (thinking iteratively) all values are equally high, it stops being important which you cap.
- If there's no solution output an error or a falsy value.
The winner
The shortest valid answer - measured in bytes - wins.
Apart form the rules, I'm interested to see a program that keeps a value intact as long as possible. Consider the input values a plant each with the heights 10,2,10
and the maximum m
=5, it would be a waste to cap the baby plant in the middle.
3, 2
and3
? \$\endgroup\$m
is greater than the total? \$\endgroup\$4,4,2
and5
case are you capping the2
to1
or are you capping one of the4
s to a1
and then rearranging the items to match the input in some way? (note that if it is done iteratively we reach2,2,2
at which point we can cath and yield1,2,2
following all the other rules). \$\endgroup\$