Generate all contiguous sequences from an array
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();
}
}