Generate all contiguous sequences from an array
Asked Answered
A

11

10

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();
    }
}
Adaadabel answered 31/8, 2015 at 10:23 Comment(2)
so ... what is your actual question? what is it you're stuck with?Sedum
@Sedum i'm not getting the exact series! I'm looking for a proper logic to do this.Adaadabel
F
14

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();
    }
}
Felucca answered 31/8, 2015 at 10:33 Comment(3)
is it possible to do in less than 3 loops?Waterside
@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)));Felucca
@AliAkram yes possible to use less than 3 loops. Look here: https://mcmap.net/q/1075543/-generate-all-contiguous-sequences-from-an-arrayRebeckarebeka
C
2
// Javascript.
// Generate Array and print it.
function subArray(arr) {
    if (arr.length < 1) return 0;
    if (arr.length < 2) return arr[0];

    let result = [];
    for (let i = 0; i < arr.length; i++) {
        const temp = [];
        for (let j = i; j < arr.length; j++) {
            temp.push(arr[j]);
            result.push([...temp]);
            console.log(temp.join(','));
        }
    }
    return result
}

// Calculate only Sum of the subarrays.
function subArrSum(arr) {
  if (arr.length < 1) return 0;
  if (arr.length < 2) return arr[0];

  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
      sum += (arr.length - i) * (i + 1) * arr[i];
  }
  return sum;
}
Cotenant answered 14/6, 2019 at 22:3 Comment(1)
Using loop twice. To get just sum, I suggested using pattern of the subarrays.Cotenant
S
1

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();
        }
}
Strive answered 31/8, 2015 at 10:39 Comment(0)
D
0

Try this way.

int items[]={1,2,4,5,1};
for(int i=0;i<=items.length;i++)//items is the main array 
{
    int num=0;
    for(int j=0;j<items.length;j++)
    {
        for(int k=i;k<=j;k++)
        {
            System.out.print(items[k]);
        }

        System.out.println();
    }
}
Domel answered 31/8, 2015 at 10:36 Comment(1)
The output is correct, but with much extra spaces between the lines :)Felucca
N
0

Use the below code:

import java.io.*;
class stack
{
    public static void main(String args[]) throws IOException
    {
        int items[]={1,2,4,5,1};

        for(int i=0;i<items.length;i++)//items is the main array 
        {
            for(int j=i;j<items.length;j++)
            {
                for(int k=i;k<=j;k++)
                {
                    System.out.print(items[k]);
                    if (k==j)
                        continue;
                    else
                        System.out.print(",");
                }
                System.out.println();
            }
        }
    }
}
Nicolette answered 31/8, 2015 at 10:40 Comment(0)
B
0

I think this may help

for(int i=0;i<=items.length-1;i++)
{
    for(int l=i;l<=items.length;l++)
    {
    int b[]=Arrays.copyOfRange(a, i,l);

        for(int k=0;k<=b.length-1;k++)
        {
            System.out.print(b[k]);
        }

        System.out.println();
    }
}
Bourbon answered 31/8, 2015 at 12:7 Comment(0)
R
0

There is one better approach that takes less time:

Input:

int items[] = {1,2,3,4};

Code:

int j = 0;
StringBuilder sb = new StringBuilder();

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

   sb.setLength(0);
   j = 0;
   sb.append(items[i]+ " ");
   System.out.print(sb.toString()+ " ");
   System.out.println();

   j=i+1;
   
   while(j< items.length){

       sb.append(arr.get(j) + " ");
       System.out.print(sb.toString() +" ");
       System.out.println();

       j = j+1;
   }
   System.out.println();
   }

Output:

  1
  1 2
  1 2 3
  1 2 3 4

  2 
  2 3
  2 3 4
  
  3
  3 4

  4
Rebeckarebeka answered 18/1, 2022 at 10:38 Comment(0)
E
0

def printSubsequences(l, r, arr:list, n):

if(l == n):
    return
while(l<=r):
    print(arr[l:r+1])
    r-=1
printSubsequences(l+1, n-1, arr, n)

if __name__ == "__main__":
arr = list(map(int, input("Enter : ").strip().split()))
printSubsequences(0, len(arr)-1, arr, len(arr))

Excogitate answered 23/4, 2022 at 17:40 Comment(0)
T
0
static void printContiguousSequence(int[] arr, int fromIndex, int toIndex)   {
    if (toIndex > arr.length)
        return;

    for (int i = fromIndex; i < toIndex; i++) {
        System.out.print(arr[i]);
    }

    System.out.println();

    if (toIndex == arr.length) {
        fromIndex++;
        toIndex = fromIndex;
    }
    printContiguousSequence(arr, fromIndex, toIndex + 1);
}

public static void main(String args[]) {
    int[] arr = { 1, 2, 4, 5, 1 };
    printContiguousSequence(arr, 0, 1);
}
Trichotomy answered 7/7, 2023 at 5:39 Comment(0)
S
-1

The problem seems to be with your second loop:

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

You're always running on the first i places. What you want to do is run from i until the end of the array, as such:

for(int j=i;j<items.length;j++)
Saphena answered 31/8, 2015 at 10:30 Comment(0)
G
-2

Try something like this:

for(int i=0; i<items.length; i++)
{
   for(int j=i; j<items.length; j++)
   {
      System.out.print(items[j]);
   }
   System.out.println();
}

I haven't tested yet, but it should work.

Geese answered 31/8, 2015 at 10:30 Comment(1)
No it does not work. It prints the whole array, then only the last four elements, then the last three elements and so on...Felucca

© 2022 - 2025 — McMap. All rights reserved.