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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.