It uses pretty little space (not just in this particular example, but in general...) considering what's doing... Think of it as an index on the joins of the three arrays...

For really big arrays using greps on every iteration would make the operation really cumbersome and memory would be used anyway for the temporaries for grep on each of the arrays... This approach allows logarithmic access to the key once the index is done, yours would be at least of order O(N^2)...

Example:

# some are shared by others... @array1 = (1 .. 100001); @array2 = (100001 .. 200001); @array3 = (200001 .. 300000); for $i ( 1 .. 100000, 1 .. 10000 ) { $a = int( rand( 3 ) ) + 1; # dark magic, beware... push @array4, ${*{"array$a"}}[$i]; } 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 "." if "$one and $two are in (@{$which{$one}}) and (@{$which{ +$two}}) respectively\n"; } __END__ This renders (on my box): 4.05user 0.15system 0:04.31elapsed 97%CPU (0avgtext+0avgdata 0maxresid +ent)k 0inputs+0outputs (0major+22995minor)pagefaults 0swaps

with bigger arrays it will grow bigger, of course, but if you have that many data you will have a lot of RAM... memory is cheap nowadays, cheaper than CPU cycles, I think...

best regards

--
our $Perl6 is Fantastic;


In reply to Re^4: matching values in arrays by Excalibor
in thread matching values in arrays by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.