fork download
  1. #include <iostream>
  2. using std::cout;
  3.  
  4. // C(n, r) and provide the current combination set a of size r.
  5. bool nextCombination(int n, int r, int *a);
  6. void printArray(int *a, int n);
  7.  
  8. int main() {
  9. int a[] = {1,2,3};
  10. int length = sizeof(a)/sizeof(*a);
  11. int count = 0;
  12. // The following example is C(7,3), start at {1,2,3}
  13. do {
  14. printArray(a, length);
  15. count++;
  16. } while (nextCombination(7, length, a));
  17. cout << "Total: " << count << '\n';
  18. return 0;
  19. }
  20.  
  21. bool nextCombination(int n, int r, int *a) {
  22. int lastNotEqualOffset = r-1;
  23. while (a[lastNotEqualOffset] == n-r+(lastNotEqualOffset+1)) {
  24. lastNotEqualOffset--;
  25. }
  26. if (lastNotEqualOffset < 0) {
  27. cout << "the end\n";
  28. return false;
  29. }
  30. a[lastNotEqualOffset]++;
  31. for (int i = lastNotEqualOffset+1; i<r; i++) {
  32. a[i] = a[lastNotEqualOffset]+(i-lastNotEqualOffset);
  33. }
  34. return true;
  35. }
  36.  
  37. void printArray(int *a, int n) {
  38. for (int i = 0; i < n; i++) {
  39. cout << a[i] << " ";
  40. }
  41. cout << '\n';
  42. }
  43.  
  44.  
  45.  
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
1 2 3 
1 2 4 
1 2 5 
1 2 6 
1 2 7 
1 3 4 
1 3 5 
1 3 6 
1 3 7 
1 4 5 
1 4 6 
1 4 7 
1 5 6 
1 5 7 
1 6 7 
2 3 4 
2 3 5 
2 3 6 
2 3 7 
2 4 5 
2 4 6 
2 4 7 
2 5 6 
2 5 7 
2 6 7 
3 4 5 
3 4 6 
3 4 7 
3 5 6 
3 5 7 
3 6 7 
4 5 6 
4 5 7 
4 6 7 
5 6 7 
the end
Total: 35