Search code examples
javaarrayssetpowerset

Java: Generating a custom sets of elements


I need a simple java program that can generate me the custom sets for a set,say for {'1','2','3','4'}. The result should be: {'1','2'},{'2','3'},{'3','4'},{'1','2','3'},{'2','3','4'}.

I have tried codes for powerset,but the output isn't desirable. It would be appreciable if the code could be something like:

for(j=2;j<set.size()-1;j++)
{
for(i=0;i<set.size()-1;i++)
{
//a[i],a[i+1] when j=2
//a[i],a[i+1],a[i+2] when j=3
}
} 

I know .size() is for ArrayList and a[i] is for simple array and i've written both as any approach will do!! Thanks In Advance!! :)


Solution

  • This code should print the values you want:

        final int[] values = {1, 2, 3, 4};
        for (int size = 2; size < values.length; size++) {
            for (int i = 0; i + size <= values.length; i++) {
                for (int j = 0; j <= size - 1; j++) {
                    System.out.print(values[i + j]);
                }
                System.out.println();
            }
        }
    

    From the example, we see that you want to print sets of values whose length is greater than 1 and smaller than the total set, so that 's what the following line does:

    for (int size = 2; size < values.length; size++) {

    After that we compute the starting index of the subset, watching not to run into a IndexArrayOutOfBounds exception (see the line below)

    for (int i = 0; i + size <= values.length; i++) {
    

    From there we just print the values starting at i index and with the subset length of size

    for (int j = 0; j <= size - 1; j++)