2017-08-18 61 views
0

我在JAVA下面有程序。將JAVA程序轉換成PHP代碼

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編寫這條線?

+0

**這不是C **。我無法確定它是什麼(C#?C++?)請確定你自己並更正標記。 –

+0

請查看http://www.codesolution.org/frog-jump-through-leaves-problem/ –

+0

上的代碼。查看源代碼說明它強調的是** java **(它有class'syntaxhighlighter java') –

回答

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

+0

我沒有足夠的代表。訪問聊天。 –

+0

我認爲如果我的答案解決了您的問題,您可以接受它並且問題已關閉。如果您還有其他問題,請在評論中提問或者創建一個新問題。 – xander