How to find all contiguous sub array combinations of an array and print it

Viewed 851

I need to write a program to print all sub arrays of an array in a particular format.

Example-
I/o: 
n = 3
A = (1,2,3) where n is the size of the array and A is the array itself.

O/p:
(1),(2),(3)
(1),(2,3)
(1,2),(3)
(1,2,3)

I am able to get all subarrays using two loops but cannot produce the output in this particular order.I am coding in Java. My code goes is as follows:- a[]→integer Array of n elements

for(int i=0;i<a.length;i++){
  String s = "";
  for(int j=i;j<a.length;j++){
    s = s + a[j] + " ";
  System.out.println(s);
}

This code gives all possible sub arrays but not all contagious sub array combination that can be formed from an array.

2 Answers

This is kind of hard doing without recursion. Even recursion is hard for this one because you have to loop inside the recursive method, which is rather unusual.

class Main {
  static void printGroups(int[] a, int start, String output) {
    output += "(" + a[start];
    for (int i = start + 1; i < a.length; i++) {
      printGroups(a, i, output + "),");
      output += "," + a[i];
    }
    System.out.println(output + ")");
  }

  public static void main(String[] args) {
    printGroups(new int[]{1, 2, 3, 4}, 0, "");
  }
}

This outputs:

(1),(2),(3),(4)
(1),(2),(3,4)
(1),(2,3),(4)
(1),(2,3,4)
(1,2),(3),(4)
(1,2),(3,4)
(1,2,3),(4)
(1,2,3,4)

The solution meets the requirements of the question, but I want to warn that these are not all subset combinations.

Missing combinations are:

(4,2),(3,1)
(4,1),(2,3)
(2),(1,3,4)
(3),(1,2,4)
(2),{4),(1,3)
(1),(3),(2,4)
(2),(3),(1,4)
Related