1

I am trying to add array list values in dynamic manner of all combinations using for loop . For example adding two elements combination in an array can be done by nested loop. Similarly 3,4,5,6,7,8 like that combination addition is need dynamic for loop generation. What can I do?

static int birthday(List<Integer> s, int d, int m) {

    int l=s.size();
    int count=0;
    int a[]=new int[l];
    for (int x=0; x<l; x++){
        a[x]=s.get(x);
    }
    if(m==2){
        for (int i=0; i<l; i++){
            for (int j=i+1; i<l; i++){
                if(a[i]+a[j]==d){
                    count++;
                }
            }
        }
    }
    else if(m==1){
        count++;
    }
    return count;
}

Above code is for 1 and 2 combinations and for all the 3,4,...10. I want to generate dynamic for loop. Please give solution.

3
  • 4
    Think about another approach. The dynamic nested loop will slow down your code. Think of 300 nested loops created dynamically. Your code complexity will be O(n^300) Commented Jun 14, 2019 at 6:52
  • you can solve this using mathematical calculation. However if you must need dynamic loops try recursion. Commented Jun 14, 2019 at 7:01
  • Does this answer your question? Is there any way to do n-level nested loops in Java? Commented Mar 3, 2020 at 0:12

1 Answer 1

3

You could use recursion:

static int birthday(List<Integer> s, int d, int m) {
    int l=s.size();
    int a[]=new int[l];
    for (int x=0; x<l; x++){
        a[x]=s.get(x);
    }
    return birthday(a, d, m, 0, 0);
}

private static int birthday(int[] a, int d, int m, int start, int sum) {
    if (m == 0) {
        return sum == d ? 1 : 0;
    }
    int count=0;
    for (int i = start; i <= a.length-m; ++i) {
        count += birthday(a, d, m-1, i+1, sum+a[i]);
    }
    return count;
}

Some optimisations are possible, if you sort the array and if you can assume that all the elements of the list are positive.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.