fork(7) download
  1. #include <vector>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. #define SET_SIZE 5
  7.  
  8. int set[] = {1, 2, 3, 4, 5};
  9. vector<vector<int> > all_combinations;
  10. const int tuple_size = 3;
  11.  
  12. void recursive_comb(int step_val, int array_index, std::vector<int> tuple)
  13. {
  14. if (step_val == 0)
  15. {
  16. all_combinations.push_back(tuple); //<==We have the final combination
  17. return;
  18. }
  19.  
  20. for (int i = array_index; i < SET_SIZE; i++)
  21. {
  22. tuple.push_back(set[i]);
  23. recursive_comb(step_val - 1, i + 1, tuple);
  24. tuple.pop_back();
  25. }
  26.  
  27. return;
  28. }
  29.  
  30. void init_combinations()
  31. {
  32. std::vector<int> tuple;
  33. tuple.reserve(tuple_size); //avoids needless allocations
  34. recursive_comb(tuple_size, 0, tuple);
  35. }
  36.  
  37. int main()
  38. {
  39. init_combinations();
  40. cout << "Total Combinations: " << all_combinations.size() << endl;
  41.  
  42. for (int i=0; i < all_combinations.size(); i++)
  43. {
  44. cout << "{";
  45. for (int j=0; j < tuple_size; j++)
  46. {
  47. cout << all_combinations[i][j] << " ";
  48. }
  49. cout << "}" << endl;
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
Total Combinations: 10
{1 2 3 }
{1 2 4 }
{1 2 5 }
{1 3 4 }
{1 3 5 }
{1 4 5 }
{2 3 4 }
{2 3 5 }
{2 4 5 }
{3 4 5 }