将JAVA程序转换为PHP代码

时间:2017-08-18 07:40:37

标签: java php

我在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;
    }

我想用PHP转换。 直到现在我所做的是

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);

上面的程序应该返回3.但是在我将程序转换为PHP语言后,它没有返回预期的值。

我确信我已经做了一切正确的事情,除了转换下面的行

boolean[] leafArray = new boolean[postion+1];

如何用PHP编写这一行?

1 个答案:

答案 0 :(得分:1)

我刚刚将您原来的Java代码翻译成PHP 1:1,大部分内容都可以按原样使用,只需稍加修改,请看这个例子:

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));输出2

我还编译了Java代码,输出也是2,所以对我来说似乎是正确的?使用System.out.println(frogJump(new int[]{3,2,1}, 1));

运行