I wanna list all arrangement, the following is my sample code:
const unsigned char item1[] = {'b'};
const unsigned char item2[] = { 'A', 'C' ,'D'};
const unsigned char item3[] = {'1','2'};
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < sizeof(item1) / sizeof(unsigned char); i++){
for (int j = 0; j < sizeof(item2) / sizeof(unsigned char); j++){
for (int k = 0; k < sizeof(item3) / sizeof(unsigned char); k++){
printf("%c%c%c\n",item1[i],item2[j],item3[k]);
}
}
}
return 0;
}
This will print all arrangement, but I am worried about if the array item is from item1 to item99, the code is difficult to maintain. Is there a better solution to print all arrangement? Thanks!
You might store your "iterator" in vector, then you might do something like:
bool increase(const std::vector<std::string>& v, std::vector<std::size_t>& it)
{
for (std::size_t i = 0, size = it.size(); i != size; ++i) {
const std::size_t index = size - 1 - i;
++it[index];
if (it[index] == v[index].size()) {
it[index] = 0;
} else {
return true;
}
}
return false;
}
void do_job(const std::vector<std::string>& v, std::vector<std::size_t>& it)
{
for (std::size_t i = 0, size = v.size(); i != size; ++i) {
std::cout << v[i][it[i]];
}
std::cout << std::endl;
}
void iterate(const std::vector<std::string>& v)
{
std::vector<std::size_t> it(v.size(), 0);
do {
do_job(v, it);
} while (increase(v, it));
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With