[Codility] FrogJmp (JavaScript)

Sohyeon Bak·2021년 11월 26일
0

Codility

목록 보기
2/19
post-thumbnail

문제

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.

Write a function:

function solution(X, Y, D);

that, 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
Write an efficient algorithm for the following assumptions:

X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.

문제해석

간단한 문제지만 숫자의 범위가 1,000,000,000까지 된다는 것을 명심한다면 크게 어려운 문제는 아니다.
개구리는 X(10)에 위치하고 Y(85)나 Y(+85)보다 더 많은 위치까지 가야한다.

가는 방법은 X에서 오직 D만큼 움직여야하고 Y까지 가기 위해 몇번의 D가 필요한지 구하는 것이다.

문제풀이

X에서 D를 더하는 방법은 범위를 생각하면 좋은 방법은 아니다.
그렇기 때문에 Y를 D로 나눈 값을 찾는게 효율적이다.

  • Y = Y-(X+D)로 초기 값을 설정한다.
  • 처음 이동위치를 제외한 Y에서 D를 나누고 나눈 값의 소수점은 모두 올려준다.

코드

function solution(X, Y, D) {
    let answer = 1;
    let tmp = Y - (X+D)
    tmp = Math.ceil(tmp/D)
    
    return answer + tmp
}

최종결과

출처

https://app.codility.com/programmers/lessons/3-time_complexity/

profile
정리하고 기억하는 곳

0개의 댓글