shubham gupta
shubham gupta

Reputation: 331

Generate all contiguous sequences from an array

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();
    }
}

Upvotes: 11

Views: 22165

Answers (11)

Dmitry
Dmitry

Reputation: 1

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);
}

Upvotes: 0

Devjeet Roy
Devjeet Roy

Reputation: 1

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

Upvotes: 0

chirag soni
chirag soni

Reputation: 1026

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

Upvotes: 0

Young Song
Young Song

Reputation: 21

// 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;
}

Upvotes: 2

Sid
Sid

Reputation: 1274

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();
            }
        }
    }
}

Upvotes: 0

Rafiq
Rafiq

Reputation: 750

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();
    }
}

Upvotes: 0

Mohit
Mohit

Reputation: 9

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();
    }
}

Upvotes: 0

kai
kai

Reputation: 6887

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();
    }
}

Upvotes: 14

burglarhobbit
burglarhobbit

Reputation: 2291

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();
        }
}

Upvotes: 1

Ori Lentz
Ori Lentz

Reputation: 3688

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

Upvotes: -1

Andrea Rovinetti
Andrea Rovinetti

Reputation: 25

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.

Upvotes: -2

Related Questions