如何计算数组中相同索引键的每个元素?

时间:2014-07-04 19:50:04

标签: perl

如何计算相同索引号的每个元素?

my @a = qw"A B C D E F";
my @b = qw"A B C C";
my $count = 0;
for($i = 0; $i<=scalar @a; $i++){
    for($j = 0; $j <= scalar @b; $j++){
        if($a[$i] eq $b[$j]){
            $count++;
        }
    }
}
print "Total: $count";

I expect the output is:
Total:3

输出是通过只计算索引键的相同元素来完成的吗?我该怎么办?

1 个答案:

答案 0 :(得分:3)

您的问题有两种可能的解释:

1。如何计算两个数组的交集?

散列是测试存在的理想数据结构:

use strict;
use warnings;

my @a = qw"A B C D E F";
my @b = qw"A B C C";

my %b = map {$_ => 1} @b;

my $count = scalar grep {$b{$_}} @a;

print "Total: $count";

输出:

Total: 3

额外的perldoc参考:How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

2。一个测试元素如何在两个数组之间相等,索引到索引?

如果这是你的问题,那么你不需要两个循环,只需要一个迭代器。

use strict;
use warnings;

use List::Util qw(min);

my @a = qw"A B C D E F";
my @b = qw"A B C C";

my $count = scalar grep {$a[$_] eq $b[$_]} (0..min($#a, $#b));

print "Total: $count";

输出:

Total: 3