-2

I have two arrays a1 = {1, 2, 3, 4, 5} and a2 = {2, 4, 6, 8} with an integer n = 3. What I need to do is, using recursion, return a new array of the product of each element until reaching position marked by n. Final result should be a3 = {2, 8, 18}.

public class Product {

    public static int[] arrayProd(int [] v1, int [] v2, int n) {
        if(n >= 0){
            return a1[n] * a2[n];
        }
    }

    public static void main(String [] args) {
        int[] v1 = {1, 2, 3, 4, 5};
        int[] v2 = {2, 4, 6, 8};
        int n = 3;
    }
}

It is also suggested that we should use an auxiliary method like:

private static void auxArrayProd(int [] v1, int [] v2, int [] result, int n) {
    return null;
}

But I don't know how to return an array formed with integers

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Daniel
  • 9
  • 3

2 Answers2

2

Here is a recursive approach :)

public static void arrayProd(int [] v1, int [] v2, int upperBound, int curIndex, int[] prod) {
    if(curIndex == upperBound) {
        return;
    }
    prod[curIndex] = v1[curIndex] * v2[curIndex];
    arrayProd(v1, v2, upperBound, curIndex+1, prod);
}

public static void main(String [] args) {
    int[] v1 = {1, 2, 3, 4, 5};
    int[] v2 = {2, 4, 6, 8};
    int n = 3;
    // array size cant be greater than 3 as per your example
    int[] prod = new int[n];
    arrayProd(v1, v2, n, 0, prod);
    System.out.println(Arrays.toString(prod));    // [2, 8, 18]
}
Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
1

The auxiliary method is a good suggestion, but with a different method signature than that you listed in your code.

Reason being is that you need to keep track of the index less than n, then your base-case for the recursion is when that index is greater than n.

On the first call to the auxiliary method, you start the index at 0, then you recurse inside the auxiliary method much like a for-loop to increment the index.

This code will print your desired result of [2, 8, 18]

import java.util.Arrays;

public class Product {

    // auxiliary method
    private static void _arrayProd(int[] v1, int[] v2, int[] result, int n, int i) {
        if(i < n){
            result[i] = v1[i] * v2[i];
             _arrayProd(v1, v2, result, n, i+1);
        }
    }

    public static int[] arrayProd(int[] v1, int[] v2, int n) {
        int[] result = null;
        if(n >= 0){
            result = new int[n];
            _arrayProd(v1, v2, result, n, 0);
        }
        return result;
    }


    public static void main(String [] args) {
        int[] v1 = {1, 2, 3, 4, 5};
        int[] v2 = {2, 4, 6, 8};
        int n = 3;

        int[] v3 = arrayProd(v1, v2, n);

        System.out.println(Arrays.toString(v3));
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245