fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <algorithm>
  4.  
  5. namespace so {
  6. using size = std::size_t;
  7. using array_1d = std::vector<size>;
  8. using array_2d = std::vector<array_1d>;
  9.  
  10. array_2d generate_combinations_all(array_1d const & _values_max) {
  11. array_2d values_all_; // arrays of all possible values for each position
  12. size count_combination_{1}; // number of possible combinations
  13.  
  14. for (auto i_ : _values_max) { // generate & fill in 'values_all_'
  15. array_1d values_current_(i_);
  16. size value_current_{0};
  17.  
  18. std::generate(values_current_.begin(), values_current_.end(), [&] {return (value_current_++);});
  19. values_all_.push_back(std::move(values_current_));
  20. count_combination_ *= i_;
  21. }
  22.  
  23. array_2d combinations_all_; // array of arrays of all possible combinations
  24. array_1d indices_(_values_max.size(), 0); // array of current indices
  25.  
  26. for (size i_{0}; i_ < count_combination_; ++i_) {
  27. array_1d combinantion_current_; // current combination
  28.  
  29. for (size j_{0}; j_ < indices_.size(); ++j_) // fill in current combination
  30. combinantion_current_.push_back(values_all_[j_][indices_[j_]]);
  31.  
  32. combinations_all_.push_back(std::move(combinantion_current_)); // append to 'combinations_all_'
  33.  
  34. for (size m_{indices_.size()}; m_-- > 0;) // update current indices
  35. if (indices_[m_] < _values_max[m_] - 1) { // ++index at highest position possible
  36. ++indices_[m_];
  37. break;
  38. }
  39. else indices_[m_] = 0; // reset index if it's alrady at max value
  40. }
  41.  
  42. return (combinations_all_);
  43. }
  44.  
  45. void print_combinations_all(array_2d const & _combinations_all) {
  46. for (auto const & i_ : _combinations_all) { // "fancy" printing
  47. std::cout << "[";
  48. for (size j_{0}; j_ < i_.size(); ++j_)
  49. std::cout << i_[j_] << ((j_ < i_.size() - 1) ? ", " : "]\n");
  50. }
  51. }
  52. } // namespace so
  53.  
  54. int main() {
  55. so::array_1d values_max_a_{3, 2, 2};
  56. so::array_1d values_max_b_{2, 1, 3, 2};
  57.  
  58. so::print_combinations_all(so::generate_combinations_all(values_max_a_));
  59. std::cout << "***************" << std::endl;
  60. so::print_combinations_all(so::generate_combinations_all(values_max_b_));
  61.  
  62. return (0);
  63. }
  64.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]
[2, 0, 0]
[2, 0, 1]
[2, 1, 0]
[2, 1, 1]
***************
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 0, 2, 0]
[0, 0, 2, 1]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 0, 1, 1]
[1, 0, 2, 0]
[1, 0, 2, 1]