java - 将JAVA程序转换为PHP代码

标签 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 编写这一行?

最佳答案

我刚刚把你原来的Java代码1:1翻译成PHP,大部分都可以按原样使用,几乎没有什么变化,看这个例子:

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

运行

关于java - 将JAVA程序转换为PHP代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45751127/

相关文章:

java - 在 'finally' 语句中返回

php - 如何使用 php 拆分字符串中的负值和正值?

php - 如何仅通过 Key => Value 更新设置表

php - JavaScript 与 PHP 组合

php - 不同的用户可以访问数据库中的同一个表并且对每个人有不同的值吗?

java - 在Java中计算闰年

Java,将可序列化对象转换(转换)为其他对象

java - 在 Java 中自定义排序的最佳方式?

Java无法访问payara服务器上的servlet

php - 如果是 index.php,则显示 "this",如果不是,则显示 "this"