简体   繁体   English

递归函数输出错误

[英]Recursive Function incorrect output

Looking for help on a java assignment from school, I am trying to create a recursive algorithm that solves the following puzzle:寻求学校 Java 作业的帮助,我正在尝试创建一个递归算法来解决以下难题:

Given a starting position and an array of length n consisting n-1 positive numbers with the last position of the array being 0, for example:给定一个起始位置和一个长度为 n 的数组,由 n-1 个正数组成,数组的最后一个位置为 0,例如:

{4 8 5 2 3 5 1 6 4 0}

The rules of the game:游戏规则:

From starting position move to right equal to the value @ starting position, repeat until you can no longer move to the right.从起始位置向右移动等于@起始位置的值,重复直到不能再向右移动。

Once you can no longer move to the right, move left in similar fashion as you moved to the right and stop once you can no longer move to the left.一旦您无法再向右移动,就以与向右移动类似的方式向左移动,一旦无法再向左移动就停止。

Now keep repeating this process.现在继续重复这个过程。

The puzzle will be solved when you have moved the last position of the array holding value of 0.当您移动数组的最后一个位置时,这个谜题将被解决,该数组的值为 0。

Otherwise the puzzle is unsolvable.否则谜题无解。

  1. In the above example if we start @ first position which is '4'在上面的例子中,如果我们从@第一个位置开始,即'4'
  2. We move to the right 4 positions ending up @ position 5 holding value 3我们向右移动 4 个位置,最后在位置 5 持有值 3
  3. We move to the right 3 positions ending up @ position 8 holding value 6我们向右移动 3 个位置,最后在位置 8 持有值 6
  4. We move to the left 6 positions ending up @ position 2 holding value 8我们向左移动 6 个位置,最后在位置 2 持有值 8
  5. We move to the right 8 positions ending up @ last position holding value 0我们向右移动 8 个位置,最后一个位置保持值 0
  6. since we have moved to the last position of the array, the puzzle is solvable.因为我们已经移动到数组的最后一个位置,所以这个谜题是可以解决的。

I have to solve this puzzle using recursion, I have come up with the algorithm but the output I am getting false even though the puzzle is solvable.我必须使用递归来解决这个难题,我已经提出了算法,但是即使这个难题是可以解决的,我的输出也是错误的。

Here is my Algorithm:这是我的算法:

static boolean rightWing(int[] A, int i) //i = starting position
{

    int left=i;
    int right=A.length-i-1;

    if (A[i]<right)
    {
        i=i+A[i];
        rightWing(A, i);
    }
    if (A[i]<left)
    {
        i=i-A[i];
        rightWing(A,i);
    }

    if (right==A[i])
        return true;
    else
        return false; 

}  

try this,尝试这个,

static boolean rightWing(int[] A, int i) //i = starting position
{

    int left=i;
    int right=A.length-i-1;

    if (A[i]<right)
    {
        i=i+A[i];
        return rightWing(A, i);
    }
    if (A[i]<left)
    {
        i=i-A[i];
        return rightWing(A,i);
    }

    if (right==A[i])
        return true;
    else
        return false; 
} 

Notice the return before the recursive calls to rightWing.注意递归调用 rightWing 之前的返回。 You need this otherwise your method will always return the result of right==A[i] of the first call.您需要这个,否则您的方法将始终返回第一次调用的 right==A[i] 的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM