We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.
Here is my code:
For most of the cases, I'm getting the correct output, but for the following two inputs, I'm not getting the desired output:
makeChocolate(9, 3, 18) (here, the output should be 3, but the actual output is coming to 8)
makeChocolate(1, 2, 7) (here, the output should be -1, my output is coming 2)
Please help me out.
Greg Charles wrote:It seems to me the right answer for makeChocolate(1, 2, 7) is 2. 1 big bar + 2 small bars = 7 kg. In other words, you're done. Why do you think it should be -1?
Because you don't have 2 small bars, you only have 1. The only goals you could meet are 0, 1, 5, 6, 10 and 11.
Normally, I would delete your solution. We don't hand out answers here. Instead, we encourage people to work it out on their own. We suggest, hint, give tips, make minor corrections to code the original person posts...but simply handing out the complete answer is against our policy.
The only reason I'm not going to bother deleting this is that you have replied to a thread that has been inactive for over two years. I doubt they are still looking for an answer.
Which do all the sets without the so called "Other test". Then I decided to do it with loops and I wrote this long code:
which do the job, but as I see there are far simpler solutions.
However, my question is "Is it possible to do it without loops and where did I go wrong in my first try?"
Thank you in advance for your responses
Robert D. Smith wrote:Looking at this, wouldn't the return value of small bars always be the target goal? If that is the case, and I am not misunderstanding the specs, it becomes a simple matter of (large * 5) + small >= targetgoal.
Not always, because you can have a situation like this one - goal = 18, big = 4 and small = 2. 4*5+2>18, but it wouldn't be correct because you haven't the needed 3 small. You have only two.