I want to return an array in the given format to print all the sub-sequences of an array.
format:
[ [1, 2, 3] [1, 2} [1, 3] [1] [2, 3] [2] [3] [] ]
The code I write :
static ArrayList<Integer> trv(ArrayList<Integer> num, int index, ArrayList<Integer> op, ArrayList<Integer> ans) {
if (index >= num.size()) {
// System.out.print(op);
// System.out.println();
ans.addAll(op);
return ans;
}
// exclude
int ele = num.get(index);
op.add(ele);
trv(num, index + 1, op, ans);
op.remove(op.size() - 1);
// include
trv(num, index + 1, op, ans);
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> n = new ArrayList<>();
int index = 0;
ArrayList<Integer> op = new ArrayList<>();
ArrayList<Integer> ans = new ArrayList<>();
n.add(1);
n.add(2);
n.add(3);
System.out.println(trv(n, index, op, ans));
}
its output
[1, 2, 3, 1, 2, 1, 3, 1, 2, 3, 2, 3]
Thanks for your time
Trivia item: Java arrays are one dimensional. Java doesn't have 2D, 3D, 4D, ... arrays.
But, Java has Arrays of Arrays! Normally, an array of arrays is used as a 2D array. But, Guess what? Arrays of Arrays is the feature you are looking for! That's because arrays of arrays do not require the "inner" arrays to be all of the same length.
For example, if you want a table of distances between cities, you could save space by having rows of different lengths. Suppose you had 30 cities:
The zeroth row cold have 29 elements. The first row, 28, 2nd row 27, and so on. You sometimes see such "triangular" tables in a printed map or road atlas.
But, your sample code isn't using an array of primitives. It's using a
Collectioninstead. Well, just as Java allows "nested arrays", it allows nestedCollectionobjects.You can use nested loops to iterate through all elements:
So far, I've avoided directly giving you code to fix your program. Instead, I've tried to present this material as a lesson or lecture. You should be able adapt the above to your needs.
By the way, for arrays of primitives, Java
Arrayshas a method that can display contents of nested arrays the way you want:Triangular table example (That goes from short to long.)
Java Arrays API