简体   繁体   中英

Basic Enumeration Efficiency in C

I'm trying to get some flying cloud technique and I'm working on these types of problems.

There were 16 presidents of the Continental Congresses from 1774 to 1788. Each of the five students in a seminar in American history chooses one of these on which to do a report. If all presidents are equally likely to be chosen, calculate the probability that at least two students choose the same president.

#include <stdio.h>
int main() 
{
int tot=0, probc=0, a=1, b=1, c=1, d=1, e=1, cnt=16;

while(e<=cnt)
{
   while(d<=cnt)
    {
        while(c<=cnt)
        {
            while(b<=cnt)
            {
                while(a<=cnt)
                {
                    if(a==b){++probc;}
                    else if(a==c){++probc;}
                    else if(a==d){++probc;}
                    else if(a==e){++probc;}
                    else if(b==c){++probc;}
                    else if(b==d){++probc;}
                    else if(b==e){++probc;}
                    else if(c==d){++probc;}
                    else if(c==e){++probc;}
                    else if(d==e){++probc;}
                    ++a;++tot;
                }
                a=1;++b;
            }
            b=1; ++c;
        }
        c=1; ++d;
    }
    d=1;++e;
}
printf("%d / %d", probc,tot);
return 0;
}
output:
524416 / 1048576

Any ideas on what would be more efficient, and techniques I could work on and so fourth to make this more logical and less lengthy? Specicially I could see maybe the loops, or maybe the else if, could I condense these arguments?

This is a relatively simple probability problem. No programming needed. To calculate the chance that at least two student's picked the same president, it's easier if you calculate the chance that no students picked the same one and then take the inverse of that.

Consider the students in order:

  1. Student #1 can choose any of the 16 presidents without worrying about overlap. Chance of picking a unique president = 16/16.
  2. Student #2 has a 15/16 chance of picking a unique president.
  3. Student #3 has a 14/16 chance.
  4. Student #4 has a 13/16 chance.
  5. Student #5 has a 12/16 chance.

Since these are independent choices you can multiply them together to get the overall chance of everyone picking a unique president.

16/16 * 15/16 * 14/16 * 13/16 * 12/16
= 4095/8192
≈ 49.98%

But remember, we're looking for the inverse of this. The answer is:

1 - 4095/8192
= 4097/8192
≈ 50.01%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM