lundi 3 mai 2021

Transforming 4 sum problem from non-recursive to recursive function

I need to implement a Recursive Function (which accepts the Array and sum as parameters) to check if it contains four elements having the given sum.

For Example:

int[] intArray = {12, 18, 3, 2, 8, 2, 3, 5};

sum = 35

Output: Quadruplet exists.

I created first non recursive function and then I tried to transform it to recursive function but it didn't work.

Here is my non recursive function:

public class NonRecursive4Sum {

  void FourElementsSum (int arr[], int n, int X)
    {
        // In first step we save first number and search for other 3
        for (int i = 0; i < n - 3; i++)
        {
            // Save 2. number and search for 2
            for (int j = i + 1; j < n - 2; j++)
            {
                // Save 3. and search for last one
                for (int k = j + 1; k < n - 1; k++)
                {
                    // Here we save last number
                    for (int l = k + 1; l < n; l++)
                    {
                        // This is the part I am trying to transform to recursive function
                        if (arr[i] + arr[j] + arr[k] + arr[l] == X){
                            System.out.print("Quadruplets exists");
                        }
                    }
                }
            }
        }
    }
 
    
    public static void main(String[] args)
    {
        NonRecursive4Sum findfour = new NonRecursive4Sum ();
        int[] intArray= {12, 18, 3, 2, 8, 2, 3, 5};
       
        
        findfour.FourElementsSum(intArray, 8, 35);
    }
}

This is modified if statement that I am trying to transform to recursive function:

if (arr[i] + arr[j] + arr[k] + arr[l] != X){
                            FourElementsSum ();
                        }
                        else if(arr[i] + arr[j] + arr[k] + arr[l] == X) {
                            System.out.println("Quadruplets Exist");
                        }

Aucun commentaire:

Enregistrer un commentaire