The problem is:
Create a function that computes all combinations of an array of arrays of strings, e.g.: { { "red", "wooden", "gate" }, { "lazy", "little", "man" }, { "what", "where", "who", "why" } }
to output: red lazy what, red lazy where, red lazy who, red lazy why, red little what, etc.....
This function will print all combinations of one word from the first array, one word from the second array, one word from the third array, etc.
Your solution may not use recursion
NOTE: the number of arrays and number of elements within each array may vary! Your method needs to be able to handle this.
I'm trying to practice my algorithms and this problem is just driving me crazy. I've tried brainstorming a few things but at this point, have spent hours getting nowhere. I was reworking my thoughts into another nested loop (see below...) when it occurred to me that maybe I just need to create a vector of strings (this would become a very large vector though...for now, lets call this vector endings
). If I traverse backward in the outer vector of the given vector<vector<string>>
and update endings
by attaching each ending to each string in the current outer vector, then by the time I get to the first outer vector, all of my combinations will be in endings
.
I probably didn't think of this immediately because I assumed if I was only printing, I shouldn't be storing so much. Anyway, here is some botched code that I stopped working on to post this. It's not much.
vector<vector<string>> ar = {{"red", "wooden", "gate"},
{"lazy", "little", "man"},
{"what", "where", "who", "why"}};
vector<string> res(ar.size());
for (int i = 0; i < ar.size(); i++) {
res[i]= ar[i][0];
}
int i;
for (i = ar.size()-1; i > 0; i--) {
for (int j = arr.size()-1-i, j > arr.size()-1-i; j--) {
// ...
}
}
Let me know how you suggest solving this problem.