experchange > perl

George Bouras (07-10-19, 01:24 AM)
what are the items that exists on two arrays no matter their offset.
a double for can find them but is there any faster method ?
Jim Gibson (07-10-19, 01:32 AM)
In article <qg37nv$1lsf$1>, George Bouras
<foo> wrote:

> what are the items that exists on two arrays no matter their offset.
> a double for can find them but is there any faster method ?


Two possibilities:

1. Sort each of the arrays and compare items in sort order, advancing
the index of the sorted array with the lessor value, etc.

2. Put the elements of one array into a hash, then for each element of
the other array test if the element exists in the hash.
George Mpouras (07-10-19, 02:35 PM)
Στις 10/7/2019 02:32, ο Jim Gibson έγραψε:
> 2. Put the elements of one array into a hash, then for each element of
> the other array test if the element exists in the hash.


# 2 is faster

my @a1 = qw/a b c d e f g h a a h/;
my @a2 = qw/1 2 h a/;
my @cm;
my %h; @h{@a2}=1;

# common
exists $h{$_} && push @cm,$_ for @a1;

# optional dedup
%h=();
@h{@cm}=1;
@cm=keys %h;

print "@cm";
Similar Threads