Beginners Programs :

Java : Hurdle Race & Jump Solution Hackerrank | Java Programs

Hurdle race & hurdle jump java program Hackerrank solution, Create a function that takes an array of hurdle heights and a jumper’s jump height, and determine whether or not the hurdler can clear all the hurdles.

A hurdler can clear a hurdle if their jump height is greater than or equal to the hurdle height.

Examples:

hurdleJump([1, 2, 3, 4, 5], 5) ➞ true

hurdleJump([5, 5, 3, 4, 5], 3) ➞ false

hurdleJump([5, 4, 5, 6], 10) ➞ true

hurdleJump([1, 2, 1], 1) ➞ false

Hurdle Jump Java Program

To solve this, we initially require the total number of hurdles (n) and the array containing height of each hurdle (a). Along with this, we also need the height of the jumper (hp).

To read all these inputs at runtime, we make use of the Scanner class by creating an object for it and invoking nextInt() method using the object because, all our inputs are of integer type.

Scanner sc=new Scanner(System.in);    //creating object

After entering the total number of hurdles, we’ll first check whether the number of hurdles is not negative because, negative would make it invalid.

Then we create an array (a) of the same size as the number of hurdles (n) and read the values denoting the height of each hurdle. After this, we also read the  height of the jumper (hp).

As we have gathered all the required input values, we now call the static method (HP) containing the main logic of the code.

To this method, we also pass all the input values read as arguments. In this method, we initially assign the count variable (c) the value zero.

We traverse through the array until we reach the end and check for every index value whether the height of the jumper is greater than or equal to the height of the hurdle i.e., hp>=a[i]. If this condition is satisfied, it would mean that the jumper can cross the hurdle so, we increment the count variable (c) by one.

After reaching the end of the array, we come out of the loop and check whether the count variable (c) is equal to the total number of hurdles (n). If it is equal then, it means that the jumper can cross all the hurdles hence, we return true to the main method.

If not then, we return false. This value is printed in the main method which is our desired output of whether the jumper can cross all the hurdles or not.

Output:

Type – 2

Here, the entire logic is the same. The difference is that, in the above method, we have made use of a separate static method in which we wrote the logic whereas, here we write it within the main method only.

In this, instead of invoking the static method and passing inputs as argument, we just directly follow the set of statements after reading our inputs with the help of Scanner class.

As soon as reading of inputs is completed, we check whether each each element in array is lesser than the height of the jumper and if it satisfies then our output is true else, our output is false.

Output: