Question

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!! :)

Was it helpful?

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++)

OTHER TIPS

This is the sample code which is generating the desired result:

    int[] array = { 1, 2, 3, 4 };
    int size = 2;
    for (int j = 0; j < array.length; j++) {
        for (int i = 0; i <= array.length - size; i++) {
            int[] temp = Arrays.copyOfRange(array, i, i + size);
            for (int x : temp) {
                System.out.print(x + ",");
            }
            System.out.println();
        }
        size++;
        if (size == array.length) {
            break;
        }
    }

Output:

1,2,
2,3,
3,4,
1,2,3,
2,3,4,
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top