Skip to content

Instantly share code, notes, and snippets.

@huklee
Last active March 6, 2017 12:02
Show Gist options
  • Save huklee/090aec31437db24c678eace896e922f1 to your computer and use it in GitHub Desktop.
Save huklee/090aec31437db24c678eace896e922f1 to your computer and use it in GitHub Desktop.
print all combinations of 2D string array
// author : huklee
// source : JTD 2017-03-05
// print all combinations of string 2D list
#include <vector>
#include <string>
#include <iostream>
using namespace std;
string print_combination(vector<int> &index_list, vector<vector<string> > &v){
string s = "";
for (int i=0; i < index_list.size(); i++)
s += v[i][index_list[i]];
return s;
}
bool is_equal(vector<int> &index_list, vector<int> &end_cond){
for (int i=0; i < index_list.size(); i++)
if (index_list[i] != end_cond[i])
return false;
return true;
}
void increment(vector<int> &index_list, vector<vector<string> > &v){
for (int i=index_list.size() - 1; i >= 0; i--){
index_list[i]++;
if (index_list[i] == v[i].size()){
index_list[i] = 0;
continue;
}
break;
}
}
void printAll(vector<vector<string> > &v){
vector<int> index_list(v.size(), 0);
vector<int> end_cond;
for (int i=0; i < v.size(); i++)
end_cond.push_back(v[i].size() - 1);
while (true){
// print each combination
cout << print_combination(index_list, v) << endl;
if (is_equal(index_list, end_cond))
break;
// increment the combination index
increment(index_list, v);
}
}
int main(){
vector<vector<string> > vs{{"1","2","3"},{"4","5","6"},{"7","8","9"}};
printAll(vs);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment