Friday, 5 May 2017

Monkey man algorithm in PHP, who jumps and slip on wall

 

A monkey man caught inside a jail. He can jumps across the wall. He can jump 'X' meters, but due to slippery walls he falls 'Y' meters after each jump. To escape from jail, he has to cross 'N' number of walls, where height of each wall is given in an array.
Write a program to find total number of jumps, he has to make, to escape
Input Format
Your function will take three arguments, where:
Argument 1: An integer depicting X, which he can jump
Argument 2: An integer depicting Y, which he falls
Argument 3: An array of N integers having the height of each wall.
Constraints
1<=X<=109
1<=Y<=105
Output Format
Your program should return total number of jumps required to escape.

Sample Test Case
Test case 1
Sample Input 10 1 1 10
Sample Output 1
Explanation
Here monkey man can jump 10 meters high, but slides down by 1 meter. He has 1 wall to jump and the height of the wall is 10 meters. Since he jumps 10 meters in the first attempt he cross the wall easily in the first attempt only.
Test case 2
Sample Input 5 1 2 9 10
Sample Output 5
Explanation
Here, the monkey man can jump 5 meters high, but slides down by 1 meters. He has 2 walls to jump and the walls are 9 and 10 meters hight respectively.
While crossing the first wall, he takes 2 attempts, because during the first attempt he jumps 5 meters but slides down by 1 meters since he didn't cross the wall. In the next attempt he jumps 5 more meters from that position and this time he doesn't slide because he crossed the wall in this attempt because 4+5=9 and 9 meters is the actual height of the wall.
Similarly, while crossing the second wall, he takes 3 attempts because during his second attempt on this wall, he silides down by 1 meters since 4+5=9 and the height of the wall is 10 meters. During his third attempt, he was able to escape.


Solution
<?php
$x=5;
$y=1;
$z=array(9,10);
function jump($x,$y,$z) {
 $cnt=count($z);
 $cntjump=0;
 for($i=0;$i<$cnt;$i++) {
  $height=$z[$i];
  while($height>$x) {
   $height=$height-($x-$y);
   $cntjump++;   
  }
  $cntjump++;
 }
 return $cntjump;
}
$cnt = jump($x,$y,$z);
echo $cnt;
?>
Find more on http://www.fbchandra.com 







No comments:

Post a Comment