Box of chocolates
You work at a chocolate shop that makes two sizes of chocolates:
- Small (2 grams each)
- Large (5 grams each)
When someone orders a box of chocolates, they order by total mass. It's your job to figure out how to fulfill the order using a combination of small and large chocolates to exactly hit the total mass ordered.
Your task is to write a function that takes three arguments:
smalls
- The number of small chocolates available in the inventory.larges
- The number of large chocolates available in the inventory.mass
- The total mass of the ordered box.
Your function should return a map containing:
{:small ;; the number of small chocolates
:large ;; the number of large chocolates
}
Or nil
if the total mass is not possible.
One other constraint is you should strive to have the fewest number of chocolates that total to the target mass. That means you should prefer large chocolates over small chocolates if you have the choice.
Examples
(assemble 100 100 2) ;=> {:small 1 :large 0}
(assemble 100 100 1) ;=> nil
(assemble 100 100 10) ;=> {:small 0 :large 2}
(assemble 10 2 20) ;=> {:large 2 :small 5}
Thanks to this site for the problem idea, where it is rated Expert in Ruby. The problem has been modified.
Please submit your solutions as comments on this gist.
To subscribe: https://ericnormand.me/newsletter