A quick method for listing all possible combinations of numbers that add up to the number of constants

Suppose we need to list four numbers A, B, C and D. The sum of A + B + C + D is 10, and the value of each number is in the range from [0, 10].

Find all possible combinations.

The brute force method is as follows:

for (int A = 0; A <=10; ++A)
  for (int B = 0; B <=10-A; ++B)
  {
   if (A + B > 10) break;    
   for (int C = 0; C <=10-A-B; ++C)
   {
    if (A + B + C > 10) break;
    for (int D = 0; D <=10-A-B-C; ++D)
    {
       if (A + B + C + D == 10)
       {
         cout << "A: " << A << ",B: " << B << ",C: " << C << ",D: " << D << endl;
         break;
       }
       else if (A + B + C + D > 10)
         break;
    }
   }
  }

Q> Is there a better solution?

FYI: code is updated based on the offer from @rici

+2
source share
2 answers

You are requesting a method for listing integer sections . The related wikipedia page describes several ways to do this.

0
source

Something like that:

void print4Partitions(int num) {
    for (int A=1; A<num-3; A++) {
        for (int B=A+1; B<num-A-2; B++) {
            for (int C=B+1; C<num-(A+B)-1; C++) {
                int D = num-A-B-C;
                printf("%d %d %d %d\n", A, B, C, D);
            }
        }
    }
}

Key ideas here:

  • : , @nci , A, B, C, , , D.
  • break, .
0

All Articles