I am currently working on this problem as a personal project.
Basically:
- Given an array of elements, e.g. E = {1,2,a,b} and
- Given a number, K, e.g. K = 2
- I want to return all Combinations of E of size K (E choose K)
- E.g. {{1,1}, {1,2}, {1,a}, {1,b}, {2,1}, ... , {b,1}, {b,2}, {b,a}, {b,b}}
I have already achieved this recursively using the following function:
char[] pool = new char[]{'1', '2', '3'};
public void buildStringRec(char[] root, int pos, int length){
for(char c : pool){
char[] newRoot = root.clone();
newRoot[pos] = c;
if(pos+1 < length){
buildStringRec(newRoot, pos+1, length);
} else{
System.out.println(String.valueOf(root));
}
}
}
Where pool
is E and length
is K.
So we would call: buildStringRec(new char[2], 0, 2);
and get
11
12
13
21
22
23
31
32
33
Can this be done iteratively? I have been trying to wrap my head around how I would do this with variable lengths.
Any help would be appreciated! If need be, I can post my code as it is, but it changes so frequently due to my retrying that it's almost useless as soon as I post it.
Also, I do not want to do this using Apache or String Builder as I want to understand the CONCEPT of how to do it. I am not simply asking for code. Pseudo-code is just fine as long as it is clearly explained.
Thanks!
EDIT
I am using this site to test out all options presented to me: https://ideone.com/k1WIa6
Feel free to fork it and try it out!
E x E
), so i guess thats just an issue with the terminology. – SelfgovernedE^K
(orExE
for K=2). – Selfgoverned