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();
}
}
Approach: For every element in the array, there are two choices, either to include it in the subsequence or not include it. Apply this for every element in the array starting from index 0 until we reach the last index. Print the subsequence once the last index is reached.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With