我认为正则表达式匹配

时间:2011-10-21 14:08:58

标签: arrays perl sum

首先很抱歉,如果我应该将此添加到my earlier question today,但我现在有以下代码,并且遇到问题需要添加到100个...

use strict;
use warnings;

my @arr = map {int( rand(49) + 1) } ( 1..100 ); # build an array of 100 random numbers between 1 and 49

my @count2;

foreach my $i (1..49) {

my @count = join(',', @arr) =~ m/,$i,/g; #  ???
my $count1 = scalar(@count); # I want this $count1 to be the number of times each of the numbers($i) was found within the string/array.

#  push(@count2, $count1 ." times for ". $i); # pushing a "number then text and a number / scalar, string, scalar" to an array.
 push(@count2, [$count1, $i]); 
}

 #sort @count2 and print the top 7
my @sorted = sort { $b->[0] <=> $a->[0] } @count2;
my $sum = 0;
foreach my $i (0..$#sorted) {  # (0..6)

 printf "%d times for %d\n", $sorted[$i][0], $sorted[$i][1];
  $sum += $sorted[$i][0]; # try to add up/sum all numbers in the first coloum to make sure they == 100

}

print "Generated $sum random numbers.\n"; # doesn't add up to 100, I think it is because of the regex and because the first number doesn't have a "," in front of it
# seem to be always 96 or 97, 93...

3 个答案:

答案 0 :(得分:1)

替换这两行:

my @count = join(',', @arr) =~ m/,$i,/g; #  ???
my $count1 = scalar(@count); # I want this $count1 to be the number of times each of the numbers($i) was found within the string/array.

有了这个:

my $count1 = grep { $i == $_ } @arr;

grep将返回一个元素列表,其中只有{}中的表达式求值为true。这比join整个阵列和使用正则表达式更不容易出错且更有效。另请注意,scalar不是必需的,因为变量$count1是标量,因此perl将在标量上下文中返回grep的结果。

你也可以摆脱这一行:

push(@count2, $count1 ." times for ". $i); # pushing a "number then text and a number / scalar, string, scalar" to an array.

因为您已经在上一个foreach循环中打印了相同的信息。

答案 1 :(得分:0)

你可以重用一些来自List::MoreUtils的经过良好测试的代码。

use List::MoreUtils qw/ indexes /;
...
foreach my $i (1..49) {
    my @indexes = indexes { $_ == $i } @arr;
    my $count1 = scalar( @indexes );
    push( @count2, [ $count1, $i ] ); 
}

如果您不需要在sum循环中发出警告,那么我建议使用List:Util中的sum。

use List::Util qw/ sum /;
...
my $sum = sum map { $_->[0] } @sorted;

如果您坚持循环,请将其重写为:

foreach my $i ( @sorted ) {

答案 2 :(得分:0)

#!/usr/bin/perl

use strict; use warnings;
use YAML;

my @arr;
$#arr = 99;

my %counts;

for my $i (0 .. 99) {
    my $n = int(rand(49) + 1);
    $arr[ $i ] = $n;
    ++$counts{ $n };
}

my @result = map  [$_, $counts{$_}],
             sort {$counts{$a} <=> $counts{$b} }
             keys %counts;

my $sum;
$sum += $_->[1] for @result;

print "Number of draws: $sum\n";