This problem is covered in elementary statistics first year university. The number of combinations can be calculated with the following formula:
X
N = C
Y
Which stands for give me the number of combinations by picking Y items from a total of X number of items. The mathematical expansion of the above formula becomes:
X X(x) * X(x-1) * ... * X(y+1)
N = C = ----------------------------
Y 1 * 2 * ... (x - y)
To pick 6 numbers from 7 numbers = 7C6 = 7/1 = 7 possible ways.
To pick 6 numbers from 8 numbers = 8C6 = 8*7/1*2 = 28.
To pick 6 numbers from 9 numbers = 9C6 = 9*8*7/1*2*3 = 84.
The perl for calculating the number of combinations is thus:
use strict;
sub xCy()
{
my ($x, $y) = @_;
return(0) if $x < $y; # can not pick more number than given
return(1) if $x == $y; # 1 combination if X = Y
my $diff = $x - $y;
my $n = 1;
for (0 .. $diff-1) { $n *= $x - $_ }
my $m = 1;
for (1 .. $diff) { $m *= $_ }
return $n / $m;
}
printf "%d\n", &xCy($_, 6) for 7 .. 10;
__END__
7
28
84
210
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.