I have below program in JAVA.
private static int frogJump(int[] arrEl,int postion) {
/** Marker array for the leaf found on the way. */
boolean[] leafArray = new boolean[postion+1];
/** Total step needed for frog. */
int steps = postion;
for(int i = 0; i<arrEl.length; i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if(postion>=arrEl[i] && !leafArray[arrEl[i]]) {
/* Mark leaf found */
leafArray[arrEl[i]] = true;
/** Reduce the step by one(coz one jump found). */
steps--;
}
if(steps == 0 && arrEl[i]==postion) {
return i;
}
}
return -1;
}
Which i want to convert in PHP. Till now what i have done is
function solution ($A = [], $Position) {
$StonesArray = array();
$StonesArray[TRUE] = $Position + 1;
$steps = $Position;
for($i = 0; $i< count($A); $i++) {
echo "<pre>";
print_r($StonesArray);
if($Position >= $A[$i] && !$StonesArray[$A[$i]]) {
$StonesArray[$A[$i]] = true;
$steps--;
}
if($steps == 0 && $A[$i] == $Position) {
return $i;
}
}
return -1;
}
$GetSolution = solution([3,2,1], 1);
echo "<pre>";
print_r($GetSolution);
above program should return 3. but after i have converted the program to PHP language its not returning the expected value.
I am sure I have done everything correct except converting the below line
boolean[] leafArray = new boolean[postion+1];
How to write this line in PHP?
I just translated your original Java code to PHP 1:1, most of it can be used as is with little change, look at this example:
function frogJump(array $arrEl, $postion) {
/** Marker array for the leaf found on the way. */
$leafArray = array_fill(0, $postion+1, false);
/** Total step needed for frog. */
$steps = $postion;
for($i = 0; $i<count($arrEl); $i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if($postion>=$arrEl[$i] && !$leafArray[$arrEl[$i]]) {
/* Mark leaf found */
$leafArray[$arrEl[$i]] = true;
/** Reduce the step by one(coz one jump found). */
$steps--;
}
if($steps == 0 && $arrEl[$i]==$postion) {
return $i;
}
}
return -1;
}
print_r(frogJump([3,2,1], 1));
outputs 2
.
I also compiled the Java code and the output is also 2
, so it seems correct to me? Run with System.out.println(frogJump(new int[]{3,2,1}, 1));