๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โŒจ๏ธ Language/swift

[Swift] Codility Lesson 3 - FrogJmp

by hyebin (Helia) 2022. 7. 23.
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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:

public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int

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.

 

๋งํฌ

 

FrogJmp coding task - Learn to Code - Codility

Count minimal number of jumps from position X to Y.

app.codility.com

 

๋ฌธ์ œ ๋ถ„์„

  • ํ˜„์žฌ ๊ฐœ๊ตฌ๋ฆฌ์˜ ์œ„์น˜ X์—์„œ Y์ด์ƒ๊นŒ์ง€ ๊ฐ€๊ธฐ ์œ„ํ•ด ๋ช‡ ๋ฒˆ์„ ์›€์ง์—ฌ์•ผ ํ•˜๋Š”์ง€ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋‹ค.
  • ๊ฐœ๊ตฌ๋ฆฌ๊ฐ€ ํ•œ ๋ฒˆ์— ๋›ธ ์ˆ˜ ์žˆ๋Š” ๊ฑฐ๋ฆฌ๋Š” D๋งŒํผ์ด๋‹ค.
ex) X: 10, Y: 85, D: 30

1. 10 + 30 = 40
2. 40 + 30 = 70
3. 70 + 30 = 100

3๋ฒˆ์˜ ์ ํ”„๋กœ 100๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค (>= 85)

 

ํ•ด๊ฒฐ๋ฐฉ์•ˆ

  1. ๊ฐ€๊ณ  ์‹ถ์€ ์œ„์น˜์—์„œ ํ˜„์žฌ ์œ„์น˜๋ฅผ ๋นผ๋ฉด ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.
  2. ๊ตฌํ•œ ๊ฑฐ๋ฆฌ๋ฅผ ํ•œ ๋ฒˆ์— ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ๊ฑฐ๋ฆฌ๋กœ ๋‚˜๋ˆ„๋ฉด ์ด๋™ํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.
  3. ๊ณ„์‚ฐํ•œ ์ด๋™ ํšŸ์ˆ˜๋งŒํผ ์ด๋™ํ–ˆ์„ ๋•Œ, ๊ฐ€๊ณ  ์‹ถ์€ ์œ„์น˜์— ๋„์ฐฉํ•˜์ง€ ๋ชปํ–ˆ๋‹ค๋ฉด 1์„ ๋”ํ•ด์ค€๋‹ค.
count = (Y-X)/D

// ๊ฐ€๊ณ  ์‹ถ์€ ์œ„์น˜์— ๋„์ฐฉํ•˜์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ
๋งŒ์•ฝ (Y-X)% D ๊ฐ€ 0์ด ์•„๋‹ˆ๋ผ๋ฉด {
    count = count + 1
}

 

Solution

public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
    return (Y-X)%D == 0 ? (Y-X)/D : ((Y-X)/D)+1
}

  • ์‹œ๊ฐ„ ๋ณต์žก๋„: O(1)
๋ฐ˜์‘ํ˜•

'โŒจ๏ธ Language > swift' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Swift] Codility Lesson 3 - TapeEquilibrium  (0) 2022.07.23
[Swift] Codility Lesson 3 - PermMissingElem  (0) 2022.07.23
[Swift] Codility Lesson 2 - OddOccurrencesInArray  (0) 2022.07.23
[Swift] Codility Lesson2 - CyclicRotation  (0) 2022.07.23
[Swift] Codility Lesson1 - BinaryGap  (0) 2022.07.23