HR - Number Line Jumps

Goody·2021년 1월 29일
0

알고리즘

목록 보기
21/122

문제

You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity).

  • The first kangaroo starts at location and moves at a rate of meters per jump.
  • The second kangaroo starts at location and moves at a rate of meters per jump.

You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

예시

INPUT

0 3 4 2

OUTPUT

YES

풀이

  • x2x1보다 앞에 있으면서 속도도 빠르면 두 캥거루는 절대 만날 수 없으므로 NO를 반환한다.
  • x1x2 가 같지 않다면, 두 캥거루를 각자만의 속도만큼 계속 앞으로 전진시킨다.
  • 만약 뒤에 있던 x1 캥거루가 x2 캥거루를 앞지르면 둘은 절대 만날 수 없다.

코드

function kangaroo(x1, v1, x2, v2) {

   if((x1 > x2 && v1 >= v2) || (x2 > x1 && v2 >= v1)) return("NO");

    while(x1 !== x2) {
        x1 += v1;
        x2 += v2;
        if(x1 > x2) return "NO";
    }
  
    return("YES");
}

0개의 댓글