Perl/배열 중복 검출




How can I find the union/difference/intersection of two arrays?

1. It 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 );

2. Quantum::Superpositions #

Quantum::Superpositions 모듈 사용. 느리지만, 제법 readable.
http://search.cpan.org/~lembark/Quantum-Superpositions-2.02/lib/Quantum/Superpositions.pm
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+) );

3. 기타 #

3.1. 비효율적이지만 간단한 방법 #

비용이 크지만 작은 리스트에서 활용 가능한 한 줄 코드.
my @isect = map { my $b = $_; grep { $_ eq $b } @a } @b;


이 글에는 0 개의 댓글이 있습니다.