FrogJmp

Count minimal number of jumps from position x to y
ℹ️ © Codility, 2009-2018

Problem

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 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.

Assume that:
x, y and d are integers within the range [1 … 1,000,000,000];
xy.

Complexity:
• expected worst-case time complexity is O(1);
• expected worst-case space complexity is O(1).

Solution

C#

using System;
class Solution {
  public int solution(int x, int y, int d) {
    return (int)(Math.Ceiling(((double)y - x) / (d)));
  }
}

Java

import java.lang.Math;
class Solution {
  public int solution(int x, int y, int d) {
    return (int)(Math.ceil(((double)y - x) / (d)));
  }
}

JavaScript

function solution(x, y, d) {
  return Math.ceil((y - x) / d);
}

PHP

function solution($x, $y, $d) {
  return (int)ceil(($y - $x) / $d);
}