寻找数组元素Perl的迭代交集

时间:2016-04-16 11:57:59

标签: arrays perl hash intersection

我希望以迭代方式在散列(数组的散列)中列出的数组中找到公共元素,然后将每个“交集”除以第一个数组的标量值。为每个数组迭代与其他数组的交集。

my @CS1= ("c1", "c2", "c3", "c4", "-c5");
my @CS2= ("c1", "c2", "c8", "c9");
my @CS3= ("c1", "c2", "c3");


my %CSHash= ( "set1" => [@CS1],
         "set2"=> [@CS2], 
         "set3" => [@CS3],

        );

我建议的解决方案:但是,它不会产生所需的输出。

  my %union=();
  my %isect=();

my $cumLativeIsect=0;

 foreach my $lst(keys %CSHash)
 {
   my $elCount=0;

    foreach my $ele(@{$CSHash{$lst}})
   {
    $elCount++;
    $union{$ele}++ && $isect{$ele}++;
    }

   my @intrsection= keys %isect;

if($elCount!=0 && scalar @intrsection!=0 )
{
 $cumLativeIsect+=  scalar @intrsection/$elCount;
}

}

数学上,我喜欢跟随计算(intr = intersection): Intrsection = | {(cs1 intr cs1)/ cs1 +(cs1 intr cs2)/ cs1 +(cs1 intr cs3)/ cs1} | + | {(cs2 intr cs2)/ cs2 +(cs2 intr cs1)/ cs2 +(cs2 intr cs3)/ cs2} | + | {(cs3 intr cs1)/ cs1 +(cs3 intr cs2)/ cs1 +(cs3 intr cs3)/ cs3} |

1 个答案:

答案 0 :(得分:0)

这是一个建议。我已经重命名了一些变量,并使用了数组数组而不是数组的哈希值。在我们在评论中讨论之后,我假设您想要计算以下内容:

   {|cs1 ∩ cs1|/|cs1| + |cs1 ∩ cs2|/|cs1| + |cs1 ∩ cs3|/|cs1| + ... } 
 + {|cs2 ∩ cs1|/|cs2| + |cs2 ∩ cs2|/|cs2| + |cs2 ∩ cs3|/|cs2| + ... } 
 + ...

以下是代码:

use strict;
use warnings;

use List::Util qw(any);

my @sets = (
    [ "c1", "c2", "c3", "c4", "-c5"],
    [ "c1", "c2", "c8", "c9"],
    [ "c1", "c2", "c3"],
    [ "c1", "c2", "c3"],
    [ ],
    [ ],
);

my $intr_sect = 0;
for my $set1 ( @sets ) {
    my $N = scalar @$set1;
    for my $set2 ( @sets ) {
        my @intersect;
        for my $item ( @$set2 ) {
            if ( any { $_ eq $item } @$set1 ) {
                push @intersect, $item;
            }
        }
        $intr_sect += (scalar @intersect) / $N if $N;
    }
}