$length = 5; #Set to the size of derangment my @results = &combinations(1..$length); $comb = 0; foreach (@results) { $found = 0; foreach my $num (1..$length){ if(@$_[$num-1] == $num) {$found = 1;} #If true then not a dera +ngement } if($found == 0) {print "@$_\n";$comb++;} } print "Number of derangements: $comb\n"; sub combinations { my @array = @_; if ($#array == 0) {return [ $array[0] ]; } my @results; my $element; foreach $element (0..$#array) { my @leftovers = @array; my $chosen_one = splice(@leftovers, $element, 1); foreach (&combinations(@leftovers)) { push(@results, [ $chosen_one, @{$_} ]); } } return @results; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: derangements
by BrowserUk (Patriarch) on Apr 26, 2003 at 05:47 UTC | |
|
Re: derangements
by hv (Prior) on Apr 26, 2003 at 04:32 UTC | |
|
Re: derangements
by thealienz1 (Pilgrim) on Apr 26, 2003 at 06:41 UTC |