1

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

1
  • maybe do it the other way round, go from i =0...n, j=0...n, and trying to add go i=0...n, j=i+1....n, and have subarray from 0 to i and from j to n Commented Mar 27, 2014 at 11:01

2 Answers 2

1

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++)
Sign up to request clarification or add additional context in comments.

1 Comment

This code is exactly what i required.. thank you so much!! ^-^
0

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,

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.