Pages

Search This Blog

Saturday 3 May 2014

Monkey Minimum Number of Jumps Algorithm

<?php

/*
 *
 * Subject : Design & Analysis of Algorithms
 *
 * Question :
 *
  Billo is a monkey trained by our beloved Raju. Billo can perform jumping very eccentrically.
  Given an array of positive integers in which each element represents number of possible hop
  choices that he can jump. Starting with array index=0, design an algorithm that finds the
  minimum number of jumps to reach the end of the array.
  Example:
  Input: A[] = {1, 3, 5, 8, 4, 2, 6, 7, 6, 8, 9}
  Output: 3
  Initially Billo is sitting at index 0. As A[0]=1, he can jump at most 1 hop, i.e., to index 1. At
  index 1, A[1]=3, so he can jump at most 3 hops (to index 2, 3 or 4). Optimally, he can reach
  last position of A in 3 jumps (0 -> 1 -> 3-> 10).
 *
 * @Author: Zuhair Mirza
 * @Date : 4-May-2014
 *
 */

$array = array(1, 3, 5, 8, 4, 2, 6, 7, 6, 8, 9);
//$array = array(1, 4, 3, 8, 5, 6, 2, 9, 7, 8);
//$array = array(1, 4, 3, 2, 5, 6, 2, 9, 7, 8, 9, 8);

$nodeIndex = 0;
$nodeValue = $array[$nodeIndex] + $nodeIndex;

echo $nodeIndex . "->";
$maxKey = runAlgo($array, $nodeIndex, $nodeValue);

function runAlgo($array, $start, $node) {

    for ($j = $start; $j <= $node; $j++) {
        if (isset($array[$j])):
            $newArray[$j] = $array[$j];
        endif;
    }

    if (end($newArray) >= end($array)):

        $maxsIndex = count($array) - 1;
        echo $maxsIndex;
        exit();

    else:

        $maxsIndex = array_keys($newArray, max($newArray));
        echo $maxsIndex[0] . "->";
        $nodeIndex = $maxsIndex[0];
        $nodeValue = $array[$nodeIndex] + $maxsIndex[0];
        $maxKey3 = runAlgo($array, $nodeIndex, $nodeValue);

    endif;

?>

1 comment: