Reputation: 63
Hello I am working on a codefights challenge, I have spent a lot of time trying to solve this issue, All of my test cases pass that i am given, I also have 4 hidden test cases that i need to pass, However I am passing all but one of the hidden test cases. My brain is completely racked, I have created all my own test cases i can possibly think of and all of them pass just fine. It is just this one hidden case, i have tried type checking everything seems to be checking out.
n children have got m pieces of candy. They want to eat as much candy as
they can, but each child must eat exactly the same amount of candy as any > other child. Determine how many pieces of candy will be eaten by all the
children together. Individual pieces of candy cannot be split.Example
For n = 3 and m = 10, the output should be candies(n, m) = 9.
Each child will eat 3 pieces. So the answer is 9.
Input/Output
[time limit] 4000ms (js)
[input] integer n
The number of children.
Constraints: 1 ≤ n ≤ 10.
[input] integer m
The number of pieces of candy.
Constraints: 2 ≤ m ≤ 100.
[output] integer
The total number of pieces of candy the children will eat provided they eat as much as they can and all children eat the same amount.
Code
function candies(n, m) {
if ((n > 10 || n < 1) || (m > 100 || m < 2)) {
return 0;
} else if (n > m) {
return 0;
} else if (n === m) {
return m;
} else if (n < m) {
var candyKids = Math.round(m / n);
return candyKids * n;
};
};
Upvotes: 0
Views: 763
Reputation: 141897
Here are some test cases that will fail with your code:
candies( 2, 3 ) === 2 (Your output: 4)
candies( 2, 5 ) === 4 (Your output: 6)
candies( 3, 5 ) === 3 (Your output: 6)
candies( 4, 7 ) === 4 (Your output: 8)
Where was the error?
You are using Math.round
instead of Math.floor
, what that means is that you will round up partial candies that are greater than half after dividing amongst the children, so for candies( 2, 3 )
, you determine that that are m/n = 1.5
candies per child, then you round it and allocate 2
candies to each child, but that creates more candy than you have to begin with. In cases like this you need to floor instead (always round partial candies down) and only give 1
candy to each child.
Upvotes: 1