in reply to Lottery combinations golf
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 N = C Y
To pick 6 numbers from 7 numbers = 7C6 = 7/1 = 7 possible ways.X X(x) * X(x-1) * ... * X(y+1) N = C = ---------------------------- Y 1 * 2 * ... (x - y)
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
|
|---|