1

我有一个如下的数组哈希:

my %HoA = (
    "M" => [ "L", "E" ],
    "L" => [ "I" ],
    "E" => [ "B", "C" ],
    "B" => [ "A" ],
    "C" => [ "A" ]
);

您可以通过这种方式对其进行可视化:

    M
   / \
  L   E
 /   / \
I   B   C
     \ /
      A

现在,我想知道每个节点的连接数:

M 6
E 3
L 1
B 1
C 1
I 0
A 0

使用 R 中的igraph包,这很简单,但我正在努力对 Perl 中的数组散列做同样的事情。

4

1 回答 1

8

Graph您可以使用该模块在 Perl 中构建图形

你需要一个Graph::Directed对象


这是一个例子

use strict;
use warnings 'all';

use Graph::Directed;

my %HoA = (
    "M" => [ "L", "E" ],
    "L" => [ "I" ],
    "E" => [ "B", "C" ],
    "B" => [ "A" ],
    "C" => [ "A" ]
);

# Build the graph
#
my $g = Graph::Directed->new;

while ( my ($from, $to) = each %HoA ) {
    $g->add_edge($from, $_) for @$to;
}

# Build a table of successors of each vertex
#
my %succ;

for my $v ( $g->vertices ) {
    my @succ = $g->all_successors($v);
    $succ{$v} = \@succ;
}

# Print the vertices in descending order of successors
#
for my $v ( sort { @{$succ{$b}} <=> @{$succ{$a}} } $g->vertices ) {
    printf "%s %d\n", $v, scalar @{$succ{$v}};
}

输出

M 6
E 3
C 1
B 1
L 1
A 0
I 0
于 2017-03-13T15:24:49.443 回答