FrogJmp – Codility – Solution

Category : Java | Sub Category : Java Programs from Coding Interviews | By Runner Dev Last updated: 2020-12-21 08:57:01 Viewed : 200


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 [] {1500001000000,  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);
  }
}

Search
Related Articles

Leave a Comment:
Sygrouppy
at 2022-04-19 07:39:41
levitra with food https://bestadalafil.com/ - Cialis Hrodkc For petit mal absence seizures ethosuximide and valproic acid are the drugs of choice. <a href="https://bestadalafil.com/">cialis 5mg best price</a> Zhpfbc levitra shipping https://bestadalafil.com/ - Cialis Type A proximal involves the ascending aorta includes retrograde extension from descending aorta. Dxkmok