- 论坛徽章:
- 0
|
第一题:- #!/usr/bin/perl -w
- use strict;
- use Data::Dumper;
- my @a = ([1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]);
- my $ret = &ChkNumInMaxis(\@a,$ARGV[0]);
- print $ret;
- sub ChkNumInMaxis() {
- my ($a,$x) = @_;
-
- my $NSeq = $#{$a->[0]};
-
- for (my $i=0;$i<=$#{$a};$i++) {
- for (my $j=$NSeq;$j>=0;$j--) {
- if ($a->[$i][$j] > $x) {
- $NSeq = $j;
- }
- elsif ($a->[$i][$j] == $x) {
- return 'ture';
- }
- else {
- next;
- }
- }
- }
-
- return 'flase';
- }
复制代码 第二题第一问:
实际是求组合
第二问是递归求组合:
写一下第二问的程序,功能包含第一问了:- #!/usr/bin/perl -w
- use strict;
- use Data::Dumper;
- my $Value = &Combine($ARGV[0],$ARGV[1],1,0);
- sub Combine() {
- my ($Step,$SLength,$Place,$Depth) = @_;
- #print "$Step,$SLength,$Place,$Depth\n";
-
- return 0 if ($Step== 0);
-
- my $MaxNum = int($SLength/$Step);
- my $Value = 0;
-
- for (my $i=0;$i<=$MaxNum;$i++) {
- #print "$Depth,$i:\n";
- my $CombinationValue = ($i==0)? 1:&CalCombinationValue($Place-1,$i+$Place-1);
- my $RLength = $SLength-$Step*$i;
- my $RPlace = $Place+$i;
- if ($RLength == 0) {
- $Value += $CombinationValue;
- }
- else {
- my $LValue += &Combine($Step-1,$RLength,$RPlace,$Depth+1);
- $Value += $CombinationValue * $LValue;
- }
- print "$i:Value = $Value\n" if($Depth == 0);
- }
-
- return $Value;
- }
- sub CalCombinationValue () {
- my ($mNum,$nNum) = @_;
-
- $mNum = $nNum - $mNum if($nNum - $mNum > $mNum);
-
- my $Permutation = 1;
- for (my $i=$mNum+1;$i<=$nNum;$i++) {
- $Permutation *= $i;
- }
-
- my $SubPermutation = 1;
- for (my $i=1;$i<=$nNum - $mNum;$i++) {
- $SubPermutation *= $i;
- }
- print "CombinationCal : $Permutation/$SubPermutation\t";
- my $CombinationValue = $Permutation/$SubPermutation;
- print "$CombinationValue\n";
-
- return $CombinationValue;
- }
复制代码 |
|