在perl中创建不同长度的向量

时间:2013-03-26 10:52:44

标签: perl

我写了以下程序:

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

任何帮助?

2 个答案:

答案 0 :(得分: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中构建向量。如果您的脚本具有文件名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";
}

答案 1 :(得分: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;