Welcome
Welcome to the forums of AntiRTFM's Absolute N00b Spoonfeed C++ Tutorials!

You are currently viewing our boards as a guest, which gives you limited access to view most discussions and access our other features. By joining our free community, you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content, and access many other special features. Registration is fast, simple, and absolutely free, so please, <a href="/profile.php?mode=register">join our community today</a>!

Code for combinations and permutations

Display your little helpful snippets of code that may help us all get something done

Code for combinations and permutations

Postby syberslidder on Mon Apr 06, 2009 5:55 pm

We just finished doing some probability stuff in school and i thought id write some code to do some of the work. They are all in long doubles because i wanted it to be able to do probabilities for like 52 cards. I dunno if these functions alrdy exist but here is my attempt. nCr is combinations, nPr is permutations.

Code: Select all
long double nCr(int n, int r) {

long double r_value;
long double num   = 1;
long double den_1 = 1;
long double den_2 = 1;
int n_r = n - r;

   while (n > 1) {

   num = num * n;

   n--;

   }

   while (r > 1) {

   den_1 = den_1 * r;

   r--;

   }

   while (n_r > 1) {

   den_2 = den_2 * n_r;

   n_r--;

   }

   r_value = num/(den_1 * den_2);

return r_value;

}


long double nPr(int n, int r) {

long double r_value;
long double num = 1;
long double den = 1;
int n_r = n - r;

   while (n > 1) {

   num = num * n;

   n--;

   }

   while (n_r > 1) {
   
   den = den * n_r;
   
   n_r--;

   }

   r_value = num/den;

return r_value;

}
syberslidder
 
Posts: 4
Joined: Sat Mar 07, 2009 10:27 pm

Return to Snippets

Who is online

Users browsing this forum: No registered users and 0 guests