Home > Mobile >  How do I build an array recursively?
How do I build an array recursively?

Time:01-28

For one of my recursive practice questions, I have to build an integer array by comparing two arrays at the index, and add the greater value to a third array. the method has to follow this format: public static int[] compare(int[] left, int[] right);

The way I did my method gives me a stack overflow error, and I genuinely have no clue what to do anymore. If someone could help guide me to the right direction that would be great.

public class RecursiveMethod {
    public static void main(String[] args) {

        int[] left = {1, 2, 4, 8, 11};
        int[] right = {1, 3, 2, 9, 10};
        int[] comparedArray = new int[5];

        comparedArray = compare(left, right, comparedArray, 0);

        for(int i : comparedArray) {
            System.out.print(i   " ");
        }

    }

    public static int[] compare(int[] left, int[] right, int[] comparedArray, int index) {
        if(index >= comparedArray.length) {
            return comparedArray;
        }

        else {
            int greater = 0;
            if(left[index] > right[index]) greater = left[index];
            else if(left[index] < right[index]) greater = right[index];
            comparedArray[index] = greater;
        }

        return compare(left, right, comparedArray, index  );
    }


}

CodePudding user response:

Look at your example, you have return compare(left, right, comparedArray, index );

i means use then increment. It means that you pass the i itself to the next step.

You should use i, what means increment then use.

My personal reccomentation is to use i 1 instead. This is simple and super clear. And no side effects.

public static void main(String[] args) {
    int[] one = { 1, 2, 4, 8, 11 };
    int[] two = { 1, 3, 2, 9, 10 };
    int[] res = compare(one, two);

    System.out.println(Arrays.stream(res)
                             .mapToObj(String::valueOf)
                             .collect(Collectors.joining(" ")));
}

public static int[] compare(int[] one, int[] two) {
    int[] res = new int[Math.min(one.length, two.length)];
    compare(one, two, res, 0);
    return res;
}

private static void compare(int[] one, int[] two, int[] res, int i) {
    if (i < Math.min(one.length, two.length)) {
        res[i] = Math.max(one[i], two[i]);
        compare(one, two, res, i   1);
    }
}
  • Related