Home > Software engineering >  How to prevent duplicate numbers when trying to find combinations for something?
How to prevent duplicate numbers when trying to find combinations for something?

Time:11-21

I am trying to make a program that will the count of all multiple combinations of length, height and width of an object's volume.

I have created some loops that loop over all possible combinations but I don't know how to prevent multiples from appearing? For example, if 1x1x2 has already been found, I don't want to count 1x2x1. Here is my code so far:

#include <stdio.h>
#include <math.h>

int main(){
    int v, m = 0, k = 0;
    scanf("%d", &v); // a is length b is width c is height and v is volume
    for(int a=1;a<=v;a  ){
        for(int b=1;b<v;b  ){
            for(int c=1;c<v;c  ){
                m = a*b*c;
                if(m == v){
                    k = k   1; //k is the number of combinations
                }
            }
        }
    }
    printf("The number of combinations was: %d", k);
    return 0;
}

CodePudding user response:

You just said in a comment that you don't want to actually go through all these combinations; you just want their count.

That's even easier, because it's basic combinatorics: That's just the number of k-combination with repetitions; the number of such combinations is the multiset coefficient, which can be represented by a binomial coefficient, easy to compute, by

( n k - 1) over k

Here, n is the number of elements to choose from (that's v in your case!), and k is how many you choose, so that's 3.

So, all you need to do is write a C function that takes two numbers, n and k, and calculates (n k-1 k)! / (n!·(n k-1-k)!). I'm sure you can write a faculty function.

CodePudding user response:

Note that the problem is basically a factorization of a whole number, so that you can save a lot of iterations:

int combinations(int volume)
{
    int k = 0;
    for ( int a = 1; a <= volume / a;   a )
    { //             ^^^^^^^^^^^^^^^ Up to the square root of volume
        if ( volume % a == 0 )
        { // ^^^^^^^^^^^^^^^   Consider only the factors
            const int area = volume / a;
            for( int b = a; b <= area / b;   b )
            {
                if ( area % b == 0 )
                {
                    const int length = area / b;               
                    printf("%d = %d * %d * %d\n", a * b * length, a, b, length);
                      k;
                }
            }
        }
    }
    return k;
}
  • Related