샘성의 iOS 개발 일지

[Implementation] Number Line Jumps 본문

Algorithm/HackerRank

[Implementation] Number Line Jumps

SamusesApple 2023. 5. 12. 14:27
728x90

문제 설명:

  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 x1 and moves at a rate of v1 meters per jump.
  • The second kangaroo starts at location x2 and moves at a rate of v2 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.

Example

x1 = 2
x2 = 1
v1 = 1
v2 = 2


After one jump, they are both at x=3, (x1 + v1 = 2+1, x2+v2 = 1+2), so the answer is YES.

Function Description

Complete the function kangaroo in the editor below.

kangaroo has the following parameter(s):

  • int x1, int v1: starting position and jump distance for kangaroo 1
  • int x2, int v2: starting position and jump distance for kangaroo 2

Returns

  • string: either YES or NO

Input Format

A single line of four space-separated integers denoting the respective values of x1, v1, x2, and v2.

Constraints

  • 0 <= x1 < x2 < 10000
  • 1 <= v1 <= 10000
  • 1 <= v2 <= 10000
 

 

 

 

내 풀이:

func kangaroo(x1: Int, v1: Int, x2: Int, v2: Int) -> String {
	// x1이 x2보다 작기에, v1(첫번째 캥거루 속력)이 v2(두번째 캥거루 속력)보다 적으면 무조건 "NO"
        if v2 >= v1   {
            return "NO"
        }

	// (두번째와 첫번째 캥거루의 시작점 차이) % (첫번째 캥거루 속력 - 두번째 캥거루 속력)
        let result = (x2 - x1) % (v1 - v2)
        // 나누어 떨어지면 "YES" 아니면 "NO"
        return result == 0 ? "YES" : "NO"
}

 

728x90

'Algorithm > HackerRank' 카테고리의 다른 글

[Implementation] Breaking the Records  (0) 2023.05.14
[Implementation] Between Two Sets  (0) 2023.05.14
[Implementation] Apple and Orange  (0) 2023.05.12
[Implementation] Grading Students  (0) 2023.05.12
[Warm Up] Time Conversion  (0) 2023.05.11