perlで複数リストのintersect(積集合)をとる
こんなかんじ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 ); |
先頭で空のリストはスルーするようにしてるけど別にいらないかもしれない。
最後にgrepしてる部分で == の条件をなくすと和集合になりますね。