Generate all contiguous sequences from an array

15,475

Solution 1

You only have to make 2 changes. The outer loop iterates as much times as the array has elements, this is correct. The first inner loop should use the index of the outer loop as start index (int j = i), otherwise you always start with the first element. And then change the inner loop break conditon to k <= j, otherwise i does not print the last element.

// i is the start index
for (int i = 0; i < items.length; i++)
{
    // j is the number of elements which should be printed
    for (int j = i; j < items.length; j++)
    {
        // print the array from i to j
        for (int k = i; k <= j; k++)
        {
            System.out.print(items[k]);
        }
        System.out.println();
    }
}

Solution 2

Tested and working! Try this algorithm.

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

        for(int j=i;j<items.length;j++) {

            for(int k=i;k<=j;k++) {

                System.out.print(items[k]);
            }
            System.out.println();
        }
}
Share:
15,475
shubham gupta
Author by

shubham gupta

Updated on July 25, 2022

Comments

  • shubham gupta
    shubham gupta almost 2 years

    There's an array say [1,2,4,5,1]. I need to print all the contiguous sub-arrays from this.

    Input: [1,2,4,5,1]

    Output:

     1
     1,2
     1,2,4
     1,2,4,5
     1,2,4,5,1
     2
     2,4
     2,4,5
     2,4,5,1
     4
     4,5
     4,5,1
     5
     5,1
     1
    

    I tried but couldn't get the complete series.

    //items is the main array
    for(int i = 0; i < items.length; i++) {
        int num = 0;
        for(int j = 0; j < items.length - i; j++) {
            for(int k = i; k < j; k++) {
                System.out.print(items[k]);
            }
            System.out.println();
        }
    }
    
  • kai
    kai over 8 years
    No it does not work. It prints the whole array, then only the last four elements, then the last three elements and so on...
  • kai
    kai over 8 years
    The output is correct, but with much extra spaces between the lines :)
  • Young Song
    Young Song almost 5 years
    Using loop twice. To get just sum, I suggested using pattern of the subarrays.
  • Ali Akram
    Ali Akram over 4 years
    is it possible to do in less than 3 loops?
  • kai
    kai over 4 years
    @AliAkram This algorithm has a runtime complexity of O(n²) so you need at least two loops. My code uses only two loops for generating the sequences. The third loop is only for printing. You can replace the inner loop with System.out.println(Arrays.toString(Arrays.copyOfRange(items, i, j + 1)));
  • chirag soni
    chirag soni over 2 years
    @AliAkram yes possible to use less than 3 loops. Look here: stackoverflow.com/a/70754152/11421611