1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Codility Lesson3】FrogJmp

Posted at

Codilityの勧め ~JavaScriptで解くアルゴリズム~の実践編です。

問題

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:

function solution(X, Y, 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.

語彙メモ

  • located at position X 位置Xにあります
  • greater than or equal to Y Y以上
  • must perform to reach its target. ターゲットに到達するために実行しなければならない
  • Write an efficient algorithm for the following assumptions: (:以下の)仮定のための効率的なアルゴリズムを書け

解法

必要知識

  • parseInt()
  • 三項演算子

太字にしているものは初見でした。

function solution(X, Y, D) {
  // write your code in JavaScript (Node.js 8.9.4)
  if (X >= Y) {
    return 0;
  } else if (D >= X + Y) {
    return 1;
  } else {
    let minimalJumps = parseInt((Y - X) / D);
    minimalJumps += (Y - X) % D > 0 ? 1 : 0;
    return minimalJumps;
  }
}

比較的簡単でした。

参考


アルゴリズム図鑑 絵で見てわかる26のアルゴリズム


世界でもっとも強力な9のアルゴリズム


なっとく!アルゴリズム


初めてのJavaScript 第3版 ―ES2015以降の最新ウェブ開発


徹底例解ロイヤル英文法 改訂新版
<

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?