0

I'm trying to create a subset of all the possible number combinations of a list of numbers. Here is an example:

List of numbers : 1,2,3,4,5,6

Subsets (3 numbers in a group) :

1,2,3

1,2,4

1,2,5

1,2,6

1,3,4

1,3,5

1,3,6

1,4,5

1,4,6

1,5,6

2,3,4

2,3,5

2,3,6

2,4,5

2,4,6

2,5,6

3,4,5

3,4,6

3,5,6

4,5,6

I'm stumped at trying to determine the looping algorithm to achieve this list. I can see that I will need a nested loop but the logic escapes me. This example contains all the possible 3 number groups but is only an example. I need to be able to scale to larger lists and more groups. Please help!

I'm a Java junkie so I'd appreciate a Java solution but would be happy with an explanation in any language and even pseudo code.

3
  • Do you want permutations or combinations, i.e., does the order of the number matter, or is 2,3,5 the same as 5,2,3? Commented Dec 2, 2014 at 16:41
  • Welcome to stackoverflow! Generally, you'll get better results by trying to get started yourself, then if you get stuck, post the code you have so far. People here generally don't want to write new code for people. Commented Dec 2, 2014 at 16:42
  • Lucky for you, Eric Lippert recently wrote up an excellent series on doing just this! Producing Combinations (Part 1 of 5). He uses C#, but the ideas should carry over to Java. Commented Dec 2, 2014 at 16:44

1 Answer 1

1

I have written a recursive code -

public class SubSetsOfLengthK {
    public static void main(String[] args) {
    int n = 6;
    int k = 3;

    int[] arr = new int[k];
    printSubSets(1,n,k,arr,0);
}

/*
    Method prints all the subsets of length k of set (1.....n)
*/
private static void printSubSets(int start, int n, int k, int[] arr, int pos) {
    if(k==0) {
        for(int a : arr) {
            System.out.print(a+" ");
        }
        System.out.println();
        return;
    }

    for(int j=start;j<= n;j++) {
        arr[pos] = j;
        printSubSets(j+1,n,k-1, arr, pos+1);
    }
  }
}

For quick access, you can have a look here https://coderpad.io/2R9CAG47

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.