本帖最后由 523066680 于 2014-9-1 21:49 编辑
直接贴代码了。
思路就是通过组合方法,递归列出两列数各自的组合情况,将每一个组合的合计存储到
%A, %B 哈希表中,然后遍历%A %B 把同类项并排列出。如果是对小范围随机数据
进行匹配,相同的情况可能会很多。但实际应用中,合计金额的独立性会强很多。- use IO::Handle;
- STDOUT->autoflush(1);
- my (@cupa, @cupb);
- my (@numa, @numb);
- my (%A, %B);
- @numa = qw/
- 1
- 14
- 72
- 24
- 53
- 66
- 77
- 8
- /;
-
- @numb = qw/123 344 22 77/;
-
- &func(\@cupa, \@numa, \%A);
- &func(\@cupb, \@numb, \%B);
- my ($fa, $fb);
- foreach $fa (keys %A) {
- foreach $fb (keys %B) {
- if ($fa == $fb) {
- print $fa, "\n",
- "\tA -> ",
- join(" | ", @{$A{$fa}}),
- "\n\tB -> ",
- join(" | ", @{$B{$fb}}),
- "\n";
- }
- }
- }
-
- sub func {
- my ($a, $b, $h) = (shift, shift, shift);
- my @ar;
- my @br;
- my $i;
- my $sum=0;
- my $allnum="";
- if (scalar(@{$a}) > 0) {
- foreach (@{$a}) {
- $sum += $_;
- }
- $allnum = join(",",@{$a});
- push @{$h->{$sum}}, $allnum;
- }
- foreach $i (0..$#{$b}) {
- @ar=(@{$a}, $b->[$i]);
- @br=@{$b}[$i+1..$#{$b}];
- &func(\@ar, \@br, $h);
- }
- }
复制代码
|