in reply to Matching arrays

arrow,
I think you left out some important information. As BrowswerUK pointed out - are you looking for a match if the sequence doesn't match, but all the elements are present? Is a match acceptable if the same element is repeated in one array, but is only present once in the other? If you have a requirement to match duplicates than converting to a hash without a count is not going to work.

#!/usr/bin/perl -w use strict; my @array1 = (1,2,2,4); my @array2 = (2,2,4,1,6); my %hash1; my %hash2; my $not_ok; foreach(@array1){ $hash1{$_} +=1; } foreach(@array2){ $hash2{$_} +=1; } while (my ($key,$hash1_value) = each %hash1) { if ($hash2{$key} && ($hash1_value == $hash2{$key})) { next; } else { $not_ok = 1; last; } } if ($not_ok) { print "Array1 is not a subset of Array2\n"; } else { print "We have a winner\n"; }
There is a penalty in efficiency for wanting this kind of accuracy - thanks to gmax for pointing this out and my solution using Data::Dumper was just plain wrong!
Cheers - L~R

Update: If sequence is important, then I would use the following logic:

  • Determine the smaller of the two arrays
  • Store the first element of the smaller array in a variable
  • Do a for loop on the larger array in the (0 .. $#array) form
  • Check each element for the first element of smaller array or next
  • Upon match, verify each subsequent element is a match
  • Match if you reach the last element of smaller array
  • No match if you don't

    There is also a module that can preserve the order of a tied hash through some unknown magic you could look at, but I don't know much about it.