[Codility] 3. Time Complexity | FrogJmp ๐ธ
โ Task
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:
class Solution { public int solution(int X, int Y, int 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.
๐ก Solution
๋ฌธ์ ๋ ๊ธธ~๊ฒ ์ค๋ช ๋์ด์์ง๋ง ์์ฃผ ๊ฐ๋จํ 1์ฐจ ๋ถ๋ฑ์์ผ๋ก ์ ๋ฆฌ๊ฐ ๊ฐ๋ฅํฉ๋๋ค.
a = ์ ํ์ Y โค X+aD โด a โฅ (Y-X)/D
์ ๋ถ๋ฑ์์ ํ์ฉํ๋ฉด ์์ฃผ ๊ฐ๋จํ ์ฝ๋๊ฐ ์์ฑ๋ฉ๋๋ค!
class Solution {
public int solution (int X, int Y, int D){
return (int) Math.ceil((Y-X)/(D*1.0));
}
}
๐ฌ Note
- ๊ณ์ฐ ๊ฒฐ๊ณผ์ ์์์ ์ ๋ณด์กดํ๊ธฐ ์ํด double๋ก ๋ณํํ๊ณ ์ 1.0์ ๊ณฑํด์ฃผ์์ต๋๋ค. ๋ช ์์ ํ๋ณํ์ ํ ์๋ ์์ต๋๋ค.
Math.ceil((Y-X)/(D * 1.0)); //๋ฌต์์ ํ๋ณํ
Math.ceil((Y-X)/(double) D); //๋ช
์์ ํ๋ณํ
- Y ์ด์์ ๊ฐ์ ์ฐพ๊ธฐ ์ํด Math class์ ์ด๋ฆผ ํจ์ ์ค ์ฌ๋ฆผ์ ์ฌ์ฉํ์์ต๋๋ค.
Function Description Example Math.around() ๋ฐ์ฌ๋ฆผ Math.around(1.1) => 1.0
Math.around(1.9) => 2.0Math.ceil() ์ฌ๋ฆผ Math.ceil(1.1) => 2.0 Math.floor() ๋ด๋ฆผ Math.floor(1.9) => 1.0
Author And Source
์ด ๋ฌธ์ ์ ๊ดํ์ฌ([Codility] 3. Time Complexity | FrogJmp ๐ธ), ์ฐ๋ฆฌ๋ ์ด๊ณณ์์ ๋ ๋ง์ ์๋ฃ๋ฅผ ๋ฐ๊ฒฌํ๊ณ ๋งํฌ๋ฅผ ํด๋ฆญํ์ฌ ๋ณด์๋ค https://velog.io/@nche/Codility-3.-Time-Complexity-FrogJmp์ ์ ๊ท์: ์์์ ์ ๋ณด๊ฐ ์์์ URL์ ํฌํจ๋์ด ์์ผ๋ฉฐ ์ ์๊ถ์ ์์์ ์์ ์ ๋๋ค.
์ฐ์ํ ๊ฐ๋ฐ์ ์ฝํ ์ธ ๋ฐ๊ฒฌ์ ์ ๋ (Collection and Share based on the CC Protocol.)
์ข์ ์นํ์ด์ง ์ฆ๊ฒจ์ฐพ๊ธฐ
๊ฐ๋ฐ์ ์ฐ์ ์ฌ์ดํธ ์์ง
๊ฐ๋ฐ์๊ฐ ์์์ผ ํ ํ์ ์ฌ์ดํธ 100์ ์ถ์ฒ ์ฐ๋ฆฌ๋ ๋น์ ์ ์ํด 100๊ฐ์ ์์ฃผ ์ฌ์ฉํ๋ ๊ฐ๋ฐ์ ํ์ต ์ฌ์ดํธ๋ฅผ ์ ๋ฆฌํ์ต๋๋ค