Anirudh - 3 months ago 16x

Java Question

The problem here on coding bat java made me stretch a little:

Problem:

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.

makeChocolate(4, 1, 9) → 4

makeChocolate(4, 1, 10) → -1

makeChocolate(4, 1, 7) → 2

http://codingbat.com/prob/p191363

I could come up with this as solution,I am not sure if it's the best way any enthusiasts would like to review, most welcome! I typed this without any compiler or anything so excuse me for the indentations:

ANY BETTER ANSWERS WOULD BE APPRECIATED:

`public int makeChocolate(int small, int big, int goal) {`

if(goal<5&&small>=goal)

{

return goal;

}

if(goal<5&&small<goal)

{

return -1;

}

if(goal>=5)

{

if(5*big>goal)

{

int temp=goal/5;

if(goal-temp*5<=small)

{

return goal-temp*5;

}

if(goal-temp*5>small)

{

return -1;

}

}

if(5*big<goal)

{

if(small<(goal-5*big))

{

return -1;

}

if(small>=(goal-5*big))

{

return goal-5*big;

}

}

}

return 0;

}

Answer

```
private final int BIG_SIZE = 5;
public int makeChocolate(int small, int big, int goal) {
int s = goal - Math.min(big, goal / BIG_SIZE ) * BIG_SIZE ;
return (s <= small) ? s : -1;
}
```

Explanation:

`goal / BIG_SIZE`

calculates the total number of big bars required. Of course, this might be more than we've got, so `Math.min(big, goal / BIG_SIZE)`

will limit that number to `big`

(the number of big bars we've got).

If we now multiply this number by the size of a big bar (5 kilos) and subtract that from `goal`

, we get the number of kilos left to be filled with small bars (`s`

).

The second line just checks, if we have enough small bars. If yes, `s`

is the result, if not, we cannot make this chocolate (`-1`

).

Source (Stackoverflow)

Comments