Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I have a newbie question: I have four arrays, three contain lists of numbers, and the fourth contains pairs of numbers. For each pair of numbers in the fourth array, I want to find the two arrays that the pair of numbers come from (they might be from the same array).

# e.g. @array1 = (1,2,3,4,5); @array2 = (6,7,8,9,10); @array3 = (11,12,13,14,15); #@array4 = (1,13, # where 1 & 13; 5 & 6; 15 & 4 are pairs 5,6, 15, 4); # i want to say that pair 1 & 13 are from array1 and array3
I know this is really easy but its getting me confused.

Hope you can help!

Replies are listed 'Best First'.
Re: matching values in arrays
by ysth (Canon) on Dec 14, 2004 at 10:44 UTC
    Easiest looking up if you keep track of which array each number goes to:
    my @which; $which[$_] = "array1" for @array1; $which[$_] = "array2" for @array2; $which[$_] = "array3" for @array3; my @pairs = @array4; while (my ($one,$two) = splice(@pairs,0,2)) { print "$one and $two are in $which[$one] and $which[$two]\n"; }
    If the numbers are negative or non-integral or too big, use a hash %which instead of the array @which.

      This solution is nice, and the hash is probably the way to go with it, but if the arrays contain repeated numbers, (i.e. their intersection is not void) it will probably fail (as it will always mark the last array, instead of the first one, or all of them)...

      Expanding your solution a bit will yield this:

      my %which; do { push @{ $which{$_} } => "array1" } for @array1; do { push @{ $which{$_} } => "array2" } for @array2; do { push @{ $which{$_} } => "array3" } for @array3; my @pairs = @array4; while (my ($one,$two) = splice(@pairs,0,2)) { print "$one and $two are in (@{$which{$one}}) and (@{$which{$two} +}) respectively\n"; }

      which is more generic and works even if the numbers are shared by any of the arrays...

      Great idea, anyway!

      --
      our $Perl6 is Fantastic;

        Yeah, but it uses a lot more memory...

        Another approach would be to use grep, loop the fourth array and in each iteration use grep on the other arrays...