FrogJmp – Codility – Solution

Java solution to Codility FrogJmp problem (Lesson 3 – Time Complexity) which scored 100%. The problem is to count the minimum number of jumps from position X to Y. The main strategy is to use division and modulus (remainder) to calculate jumps required.


1
2
3
4
5
6
7
8
9
10
11
12
package com.codility.lesson03.timecomplexity;

public class FrogJump {
  public int solution(int X, int Y, int D) {
    int distanceToJump = Y - X;
    int jumpsRequired = distanceToJump / D;
    if(distanceToJump % D != 0) {
      jumpsRequired++; //only add extra jump if remainder exists
    }
    return jumpsRequired;
  }
}

TestNG test cases for this problem which all passed:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package test.com.codility.lesson03.timecomplexity;

import org.testng.Assert;
import org.testng.annotations.*;

import com.codility.lesson03.timecomplexity.FrogJump;

public class FrogJumpTests {
  private FrogJump solution;
 
  @BeforeTest
  public void setUp() {
    solution = new FrogJump();
  }
 
  @DataProvider(name = "test1")
  public Object [][] createData1() {
    return new Object [][] {
      new Object [] { new int [] {    10,      85,     30 },   3 },
      new Object [] { new int [] {     1,      14,      3 },   5 },
      new Object [] { new int [] {   100,    1001,    100 },  10 },
      new Object [] { new int [] {150000,  999999,  10000 },  85 },
      new Object [] { new int [] {150000, 1000000,  10000 },  85 },
     
      //X and Y are the same - no jumps required
      new Object [] { new int [] {     14,      14,      3 },   0 },
    };
  }

  @Test(dataProvider = "test1")
  public void verifySolution(int [] pArgs, int pExpectedJumps) {
    Assert.assertEquals(solution.solution(pArgs[0], pArgs[1], pArgs[2]), pExpectedJumps);
  }
}