Contributed by vroom
on Jan 26, 2000 at 00:58 UTC
Q&A
> arrays
Answer: How can I find the union/difference/intersection of two arrays? contributed by chromatic This version works. :)
my @simpsons=("homer","bart","marge","maggie","lisa");
my @females=("lisa","marge","maggie","maude");
my %simpsons=map{$_ =>1} @simpsons;
my %females=map{$_=>1} @females;
# the intersection of @females and @simpsons:
my @female_simpsons = grep( $simpsons{$_}, @females );
# proof it works
print "Female Simpson:\t$_\n" foreach (@female_simpsons);
# the difference of @females and @simpsons
my @male_simpsons=grep(!defined $females{$_}, @simpsons);
# proof it works
print "Male Simpson:\t$_\n" foreach (@male_simpsons);
my %union = ();
# the union of @females and @simpsons
foreach(@females,@simpsons){
$union{$_}=1;
}
my @union2 = keys %union;
# or just do this
# my @union = (@females, @simpsons);
| Answer: How can I find the union/difference/intersection of two arrays? contributed by DrHyde TheDamian's Quantum::Superpositions module can do this.
Although it is slow, the code is quite readable:
use Quantum::Superpositions;
my @a = (1,2,3,4,5,6,7,8,9,10); # integers
my @b = (2,4,6,8,10,12,14,16,18,20); # doubled
my @unionAB = sort { $a <=> $b } eigenstates( any(@a, @b) );
my @intersectionAB = sort { $a <=> $b } eigenstates( any(@a) == any(@b
+) );
my @differenceAB = sort { $a <=> $b } eigenstates( any(@a) != all(@b
+) );
| Answer: How can I find the union/difference/intersection of two arrays? contributed by McMahon The List::Compare module has functions for all of these operations.
| Answer: How can I find the union/difference/intersection of two arrays? contributed by Dev Null This is inefficient, but I use it for intersection when I know I'm guaranteed small list sizes, and it's more valuable / pleasing to me to have a one-line solution:
my @isect = map { my $b = $_; grep { $_ eq $b } @a } @b; |
Please (register and) log in if you wish to add an answer
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, 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, 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.
|
|