user6747084
user6747084

Reputation:

How to write js code with minimal number of jumps required to reach target with less time complexity

I wrote like below. But how to make it more efficient. Need suggestions!!

For example, given:
      X = 10
      Y = 85
      D = 30

Y is the target, D is the jumpcount , X is the current position .

function solution(X, Y, D) {

   for(var i =1; X<=Y; i++){
       X = X+D;
       if( X >= Y ){
           return i;
       }
   }
}

The above code works fine, but how to write efficiently?

Thanks in advance!

Upvotes: 0

Views: 113

Answers (2)

Emeeus
Emeeus

Reputation: 5250

Based on the question (minimal number of jumps required), as I understand, when x==y should be 0 steps, then:

Math.ceil(Math.abs((Y-X)/D))

works when Y<0 and/or X<0

Upvotes: 0

Roman Hocke
Roman Hocke

Reputation: 4239

You don't need to simulate jumping, You can just use maths:

(X >= Y) ? 1 : Math.ceil((Y-X)/D)

EDIT: Updated for x >= y according to Patrick Robert's suggestion.

Upvotes: 3

Related Questions