0

我编写了以下程序:

use strict;
use warnings;
use 5.010;

my $nodesNumber = 100 ;
my $communitiesNumber = 10;
my $prob_communities = 0.3;

for my $i (1 .. $nodesNumber){
    for my $j (1 .. $communitiesNumber){
        my $random_number=rand();
        if ($prob_comunities > $random_number){
            say "$i $j";
        }
    }
}

这个程序给出一个两列整数的列表作为输出:

1 2
1 4
2 2
2 5
2 7
...

我想创建一个向量,其中左列中的第一个元素计算一次,右列元素表示向量组件的值。我希望输出看起来像:

vector[0][0]= 1
vector[0][1]= 2
vector[0][2]= 4
vector[1][0]= 2
vector[1][1]= 2
vector[1][2]= 5
vector[1][3]= 7

有什么帮助吗?

4

2 回答 2

1
#!/usr/bin/env perl
# file: build_vector.pl

use strict;
use warnings;

my @vector;       # the 2-d vector
my %mark;         # mark the occurrence of the number in the first column
my $index = -1;   # first dimensional index of the vector

while (<>) {
    chomp;
    my ($first, $second) = split /\s+/;
    next if $second eq '';
    if (not exists $mark{$first}) {
        $mark{ $first } = ++$index;
        push @{ $vector[$index] }, $first;
    }
    push @{ $vector[$index] }, $second;
}

# dump results
for my $i (0..$#vector) {
    for my $j (0..$#{ $vector[$i] }) {
        print "$vector[$i][$j] ";
    }
    print "\n";
}

该脚本将处理脚本的输出并在@vector. 如果您的脚本有 filename generator.pl,您可以调用:

$ perl generator.pl | perl build_vector.pl

更新:

use strict;
use warnings;

my $nodesNumber = 100 ;
my $communitiesNumber = 10;
my $prob_communities = 0.3;

my @vector;       # the 2-d vector
my %mark;         # mark the occurrence of the number in the first column
my $index = -1;   # first dimensional index of the vector

for my $i (1 .. $nodesNumber){
    for my $j (1 .. $communitiesNumber){
    my $random_number=rand();
        if ($prob_communities > $random_number){
            if (not exists $mark{$i}) {
                $mark{ $i } = ++$index;
                push @{ $vector[$index] }, $i;
            }
            push @{ $vector[$index] }, $j;
        }
    }
}

# dump results
for my $i (0..$#vector) {
    for my $j (0..$#{ $vector[$i] }) {
        print "$vector[$i][$j] ";
    }
    print "\n";
}
于 2013-03-26T11:46:28.623 回答
0
#!/usr/bin/env perl

use 5.010;
use strict;
use warnings;

use Const::Fast;
use Math::Random::MT;

const my $MAX_RAND => 10;

my $rng = Math::Random::MT->new;

my @v = map {
    my $l = $rng->irand;
    [ map 1 + int($rng->rand($MAX_RAND)), 0 .. int($l) ];
} 1 .. 5;

use YAML;
print Dump \@v;
于 2013-03-26T11:21:19.310 回答