How to fix 'Codility FrogJump' Algorithm?

Gamoxion :

On Codility there's this problem of counting the minimal number of jumps a frog has to make to reach Y position.

The problem reads as follow:

A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100

I have "solved" the problem and gotten "3" as result, just like in the example. However when I submit my code, I only get 11% and fail every test aside from the example.

This is my code

int count = 0;

while(X <= Y){
X += D;
count++;
}       

return count;

On my code I basically count the jumps needed to reach Y, which is the position the frog wants to get to. I'm not properly understanding the problem? If so, what I am missing?

Nico Schertler :

You are using the condition

while(X <= Y)

to make a new jump. However, in the case where X == Y, you have already reached your goal and don't want to jump further. Hence, update to

while(X < Y) //as long as we have not reached the goal

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141554&siteId=1