Skip to main content
  1. Entry/

perlで複数リストのintersect(積集合)をとる

こんなかんじ?

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
sub intersect {
my @lists = grep { scalar @$_ } @_;
my $list_num = scalar @lists;
my %in_list;
for my $list ( @lists ) {
map { $in_list{$_}++ } @$list;
}
return [ grep { $in_list{$_} == $list_num } keys %in_list ];
}
my $list1 = [ 0, 1, 2, 3 ];
my $list2 = [ 1, 3, 5, 7 ];
my $list3 = [ 0, 3, 6, 9 ];
say Dumper intersect( $list1, $list2, $list3 );
view raw intersect.pl hosted with ❤ by GitHub

先頭で空のリストはスルーするようにしてるけど別にいらないかもしれない。
最後にgrepしてる部分で == の条件をなくすと和集合になりますね。