Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fundamental coding help
#18
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;
Then compare the remaining total to the number of small chocolates you have available.
Code:
// return the number of small chocolates necessary to make up the total
if (small >= total)
  return total;
else
  return -1;
By doing it this way I've also reduced your 4 if conditions to 2.
Reply


Messages In This Thread
Fundamental coding help - by Kalovale - 2010-10-28, 04:38 AM
Fundamental coding help - by Fiel - 2010-10-28, 08:24 AM
Fundamental coding help - by Kalovale - 2010-10-28, 10:07 AM
Fundamental coding help - by Eos - 2010-10-28, 10:22 AM
Fundamental coding help - by Fiel - 2010-10-28, 10:38 AM
Fundamental coding help - by Kalovale - 2010-10-28, 12:16 PM
Fundamental coding help - by Nikkey - 2010-10-28, 12:49 PM
Fundamental coding help - by Kalovale - 2010-10-28, 12:59 PM
Fundamental coding help - by Nikkey - 2010-10-28, 01:06 PM
Fundamental coding help - by Kalovale - 2010-10-28, 01:09 PM
Fundamental coding help - by XTOTHEL - 2010-10-28, 02:47 PM
Fundamental coding help - by Nikkey - 2010-10-28, 03:06 PM
Fundamental coding help - by Dusk - 2010-10-28, 03:17 PM
Fundamental coding help - by Stereo - 2010-10-28, 03:45 PM
Fundamental coding help - by Kalovale - 2010-10-29, 10:50 AM
Fundamental coding help - by Spaz - 2010-10-29, 02:41 PM
Fundamental coding help - by Fiel - 2010-10-29, 04:07 PM
Fundamental coding help - by Stereo - 2010-10-30, 09:46 AM
Fundamental coding help - by Russt - 2010-10-30, 10:34 AM
Fundamental coding help - by Kalovale - 2010-11-03, 12:50 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)