简体   繁体   中英

Using recursion in java to find the next double in an array?

Given an array, data[ ], my goal is to find the number of elements followed by a double. (If it was a simple for loop, it'd look something like this)

for(int i = 0; i < data.length - 1; i ++) {
        if(data[i]*2 == data[i+1]) {
            count++;
        }
    }

My issue, however, is finding a certain section of the code recursively, as noted by the question marks. I'm having trouble determining how to compare a value found in the previous method call to the current method call.

public int allDoubles(int[] data) {
    int count = 0;
    //return the total doubles found
    return doubleFinder(data, 0, data.length, count);

}


private int doubleFinder(int data[], int low, int high, int count) {
    if (low == high) {
        return 0;
    } else  {   // low < high
        if( ?(previous value == current value)? ) {
            count++;
        }
        doubleFinder(data, low, high -1, count);
    }
    return count;
}

You are not passing the calculated result back up to the calling method. Since java is call-by-value, this won't work. Also you pass the wrong values to doubleFinder in allDoubles : You should use (data, 0, data.length-1, count) instead of (data, 0, data.length, count) .

Your method could be fixed like this:

private int doubleFinder(int data[], int low, int high, int count) {
    if (low == high) {
        return count;
    } else  {   // low < high
        if(data[high-1]*2 == data[high]) {
            count++;
        }
        // pass the count from the base case to calling method
        return doubleFinder(data, low, high -1, count);
    }
}

but you can even remove count :

private int doubleFinder(int data[], int low, int high) {
    if (low == high) {
        // just 1 value
        return 0;
    } else if (data[low]*2 == data[low+1]) {
        // 1 "double" found -> add 1
        return 1 + doubleFinder(data, low+1, high);
    } else {
        return doubleFinder(data, low+1, high);
    }
}

Here is an implementation of doubleFinder() which recursively compares data[i] == 2*data[ii] , beginning with the highest index in the input array data . It counts 1 for every double (not the type) found, and returns the total count of doubles for the input entered.

private int doubleFinder(int data[], int index) {
    if (index <= 0) {
        return 0; // reached last number in array 'data'
    } else {
        if (data[index] == 2*data[index-1])
            return doubleFinder(data, index-1) + 1;
        else {
            doubleFinder(data, index-1)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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