Here's another approach:
my @array_one = (2, 1, 3, 5); my @array_two = (2, 3, 1, 0); my %indices; for my $i (0..3) { # store at which index the elements occurred push @{$indices{$array_one[$i]}}, $i; push @{$indices{$array_two[$i]}}, $i; } my ($same_pos, $diff_pos) = (0, 0); for my $val (sort keys %indices) { my $i = $indices{$val}; if (@$i >= 2) { if ($i->[0] == $i->[1]) { $same_pos++; print "element '$val' in same position\n"; } else { $diff_pos++; print "element '$val' in different position\n"; } } } printf "=> %d element%s in same position, %d element%s in different po +sition\n", $same_pos, $same_pos==1 ? "":"s", $diff_pos, $diff_pos==1 ? "":"s";
Output:
element '1' in different position element '2' in same position element '3' in different position => 1 element in same position, 2 elements in different position
Note that this assumes that an element occurs in either the same or in a different position, but not both (and that there's no more than one occurrence of each element within one array). I.e. something like this
3, 1, 3, 5 3, 3, 1, 0
will produce ambiguous output (report the first occurrence, that is).
In reply to Re: Array compare
by almut
in thread Array compare
by plink
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |