2010-10-30, 09:46 AM
Kalovale Wrote:I feel more accomplished with this than with #4, but aside from sorting out all the special cases one by one, I can't think of another approach. Any suggestions/evaluations? I don't mean to be studying things I'm not supposed to. I'm just thinking there might be a fundamental technique that I missed from reading the guides.
Also, is it noticeably bad practice to create unnecessary objects? Like the remainder below with is only used once and can easily be substituted by goal%5?
Spoiler
To me, if the question implies an ordering to the process, it's better if the code mimics that process. Start by subtracting as many large chocolate bars as possible from the total, then consider whether the small ones are enough to fit the remainder. If you separate the two steps like that, it makes it easier to read what's happening than if you calculate a few numbers at the start, then compare them and spit out a result.
In this case, you want to subtract either
a) all the large chocolate
b) as many large chocolates as fit in the total
Depends which is smaller.
-- a is easy to calculate, it's just 'big'
-- b is total/5
So,
Code:
// remove as many big chocolates as possible, while leaving total positive
if (total/5 < big)
total = total%5;
else
total = total - 5*big;Code:
// return the number of small chocolates necessary to make up the total
if (small >= total)
return total;
else
return -1;
