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

Finding iterative intersection of array elements Perl

我想以迭代方式在散列(数组的散列)中列出的数组中找到共同元素,然后将每个 "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}|

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

   {|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;
    }
}