Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all subsequences of an array-like with only consecutive values in Java

The problem I am trying to solve in Java requires dividing an input array into all allowable subsequences, where an allowable subsequence contains only consecutive values. For example, I would like {A,E,D} to return {A,E,D},{A,E},{A},{E,D},{D},{E}

This is different from this question in that (for above example)
1) I have the 'consecutive value' rule that means {A,D} is NOT allowed and
2) I cannot depend on the Python syntax in the answers here.

My question, in particular, is how to implement the 'consecutive value' rule to the more general subsequence problem.

So far, I have come up with one algorithm for the example {1,2,3}:
1. Copy {1,2,3} and store in arr
2. Append {1,2,3} to solutions, peel off 3
3. Append {1,2} to solutions, peel off 2
4. Append {1} to solutions. Cut 1 from arr
5. Append {2,3} to solutions peel off 3
6. Append {2} to solutions. Cut 2 from arr
7. Append {3} to solutions


1 Answers

You should be able to simply use two nested for loops as follows:

// Setup
char[] arr = { 'A', 'E', 'D' };

// Generate all subsequences
List<char[]> result = new ArrayList<>();
for (int start = 0; start < arr.length; start++) {
    for (int end = start + 1; end <= arr.length; end++) {
        result.add(Arrays.copyOfRange(arr, start, end));
    }
}

// Print result
result.forEach(a -> System.out.println(Arrays.toString(a)));

Output:

[A]
[A, E]
[A, E, D]
[E]
[E, D]
[D]
like image 115
aioobe Avatar answered Jul 24 '26 10:07

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!