Bxr MKH
Bxr MKH

Reputation: 131

How to count the each element of same index key in array?

How to count the each element of same index number?

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

The output is done by count only the same element of the index key? How can i do it?

Upvotes: 0

Views: 64

Answers (1)

Miller
Miller

Reputation: 35198

There are two potential interpretations to your problem:

1. How does one count the intersection of two arrays?

A hash is an ideal data structure to test for existance:

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";

Outputs:

Total: 3

Additional perldoc reference: How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

2. How does one test element equality between two arrays, index to index?

If this is your question, then you do not need two loops, just a single iterator.

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";

Outputs:

Total: 3

Upvotes: 3

Related Questions