본문 바로가기

Computer Science/Algorithm with Code

[HackerRank] Preparation_Kit (03. Jumping on the Clouds)

There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud. It is always possible to win the game.

For each game, you will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided.

 

Example

c = [0, 1, 0, 0, 0, 1]

Index the array from 0...6. The number on each cloud is its index in the list so the player must avoid the clouds at indices 1 and 5. They could follow these two paths: 0246 or 02346. The first path takes 3 jumps while the second takes 4. Return 3.

Function Description

Complete the jumpingOnClouds function in the editor below.

jumpingOnClouds has the following parameter(s):

  • int c[n]: an array of binary integers

Returns

  • int: the minimum number of jumps required

Input Format

The first line contains an integer n, the total number of clouds. The second line contains n space-separated binary integers describing clouds c[i] where 0 <= i < n.

Constraints

  • 2 <= n <=100 // 최소 출발지, 도착지
  • c[i]  {0,1}
  • c[0] = c[n-1] = 0

Output Format

Print the minimum number of jumps needed to win the game.

Sample Input 0

7
0 0 1 0 0 1 0

Sample Output 0

4

Explanation 0:
The player must avoid c[2] and c[5]. The game can be won with a minimum of 4 jumps:

import Foundation

/*
 * Complete the 'jumpingOnClouds' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts INTEGER_ARRAY c as parameter.
 */

func jumpingOnClouds(c: [Int]) -> Int {
    
    var stages = 0
    var steps = 0
    
    while (stages < c.count) {
    	if stages + 1 == c.count {
            break    
        }
        steps += 1
        if stages + 2 == c.count {
            break
        }

        if c[stages+2] == 0 {
            stages += 2
        } else {
            stages += 1
        }
        //steps += 1
    }
    return steps
} 

let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

guard let cTemp = readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) else { fatalError("Bad input") }

let c: [Int] = cTemp.split(separator: " ").map {
    if let cItem = Int($0) {
        return cItem
    } else { fatalError("Bad input") }
}

guard c.count == n else { fatalError("Bad input") }

let result = jumpingOnClouds(c: c)

fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

 

[Tips]

// 몇 바퀴 돌았는지 / 단계

// 출발지와 도착지는 무조건 0

// 총 Step(답) 수: 홀수의 경우 - Stage 이동 수와 일치, 짝수의 경우 - 딱 떨어지므로, Stage 보다 하나 적은 수만큼 이동

(조건문에서도 조절 가능) ~ *요소에 따른 조건문 변화(For < While)


 

https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup