This is a program I have written to print all possible sub-arrays of given array, But there is some problem in the logic and it is printing wrong output.
Is there any algo to implement this ??
public class SubArray {
static int[][] subArrs;
static int count = 0;
public static void main(String[] args) {
int[] arr = { 1, 2, 3 };
int N = 8;
subArrs = new int[N][];
subArrs[0] = new int[10];
for (int i = 0; i < arr.length; i++) {
subArrs[i] = new int[1];
subArrs[i][0] = arr[i];
}
count = arr.length;
for (int i = 0; i < arr.length; i++) {
sub(arr, i, i);
}
for (int i = 0; i < subArrs.length; i++) {
System.out.print("[ ");
for (int j = 0; j < subArrs[i].length; j++) {
System.out.print(" " + subArrs[i][j]);
}
System.out.println(" ]");
}
}
this is a method to calculate sub-array having more than 1 element.
static void sub(int arr[], int i, int index) {
for (int j = i + 1; j < arr.length; j++) {
while (index <= j) {
subArrs[count] = new int[j + 1];
subArrs[count][0] = arr[i];
for (int k = 1; k < (j + 1); k++) {
subArrs[count][k] = arr[k];
}
count++;
index++;
}
}
}
}
Output I am getting
[ 1 ]
[ 2 ]
[ 3 ]
[ 1 2 ]
[ 1 2 ]
[ 1 2 3 ]
[ 2 2 3 ]
[ 2 2 3 ]
Desired Output
[ 1 ]
[ 2 ]
[ 3 ]
[ 1 2 ]
[ 1 3 ]
[ 2 3 ]
[ 1 2 3 ]