3

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

Community
  • 1
  • 1
  • Do you mean consecutive in the array, or consecutive as in `i` followed by `i+1`? (If the latter, could you provide a little more interesting example, what should happen for, say, `{1, 3, 4, 1, 2, 1 }`?) – aioobe May 26 '15 at 16:53
  • Then just use two nested for-loops: `for (int start = 0; start < array.length-1; start++) for (int end = start+1; end < array.length; end++) storeResult(subarray(start, end));` (Let me know if this is what you're after and I can repost it as a proper answer.) – aioobe May 26 '15 at 16:58
  • I mean consecutive in the array -- see edited question. {1,3,4,1,2,1} returns {1,3,4,1,2,1},{1,3,4,1,2},{1,3,4,1},{1,3,4},{1,3},{1},{3,4,1,2,1},{4,1,2,1}, etc. –  May 26 '15 at 16:59
  • Got it. I posted an answer. Let me know if I misunderstood the question. – aioobe May 26 '15 at 17:04
  • Yes that's the approach I was writing about. –  May 26 '15 at 17:09

1 Answers1

4

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]
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    We can also compute the number of subsequences as [`(n * (n + 1)) / 2`](http://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF) so it's possible to use an array for the result. – Radiodef May 26 '15 at 17:14
  • Indeed. That would require keeping track of another index though. – aioobe May 26 '15 at 17:14