How to (cheaply) calculate all possible length-r combinations of n possible elements

后端 未结 2 792
醉话见心
醉话见心 2020-12-03 16:32

What is the fastest way to calculate all possible length-r combinations of n possible elements without resorting to brute force techniques or anything that requires STL?

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 17:14

    What about this?

    #include 
    
    #define SETSIZE 3
    #define NELEMS  7
    
    #define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
    #define BYTETOBINARY(byte)  \
        (byte & 0x80 ? 1 : 0), \
                (byte & 0x40 ? 1 : 0), \
                (byte & 0x20 ? 1 : 0), \
                (byte & 0x10 ? 1 : 0), \
                (byte & 0x08 ? 1 : 0), \
                (byte & 0x04 ? 1 : 0), \
                (byte & 0x02 ? 1 : 0), \
                (byte & 0x01 ? 1 : 0)
    
    int main()
    {
        unsigned long long x = (1 << SETSIZE) -1;
        unsigned long long N = (1 << NELEMS) -1;
    
        while(x < N)
        {
                printf ("x: "BYTETOBINARYPATTERN"\n", BYTETOBINARY(x));
                unsigned long long a = x & -x;
                unsigned long long y = x + a;
                x = ((y & -y) / a >> 1) + y - 1;
        }
    };
    

    It should print 7C3.

提交回复
热议问题