在每个元素中找到的第一个数字上排序数组

时间:2011-10-21 11:40:26

标签: perl sorting

我正在寻找帮助排序数组,其中每个元素由“数字,然后是字符串,然后是数字”组成。我想排序数组元素的第一个数字部分,降序(这样我先列出更高的数字),同时列出文本等。

我仍然是初学者,所以也欢迎下面的替代品

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; # maybe try to make a string only once then search trough it... ???
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.
}

#for (@count2) {print "$_\n";}
# try to add up all numbers in the first coloum to make sure they == 100

 #sort @count2 and print the top 7
@count2 = sort {$b <=> $a} @count2; # try to stop printout of this, or sort on =~ m/^anumber/ ??? or just on the first one or two \d

foreach my $i (0..6) {
 print $count2[$i] ."\n"; # seems to be sorted right anyway
}

2 个答案:

答案 0 :(得分:2)

首先,将数据存储在数组中,而不是字符串中:

# inside the first loop, replace your line with the push() with this one:
push(@count2, [$count1, $i]; 

然后您可以根据每个子阵列的第一个元素轻松排序:

my @sorted = sort { $b->[0] <=> $a->[0] } @count2;

当你打印它时,构造字符串:

printf "%d times for %d\n", $sorted[$i][0], $sorted[$i][1];

另请参阅:http://perldoc.perl.org/perlreftut.htmlperlfaq4

答案 1 :(得分:2)

按原样提出要求。你最好不要在字符串中嵌入计数信息。但是,我会把它作为一种学习练习。

请注意,我通过使用哈希进行计数来简化和快速交易内存。

但是,可以使用Schwartzian Transform来优化排序。

编辑:仅使用绘制的数字

创建结果数组
#!/usr/bin/perl

use strict; use warnings;

my @arr = map {int( rand(49) + 1) } ( 1..100 );

my %counts;
++$counts{$_} for @arr;

my @result = map sprintf('%d times for %d', $counts{$_}, $_),
             sort {$counts{$a} <=> $counts{$b}} keys %counts;

print "$_\n" for @result;

但是,我可能做过这样的事情:

#!/usr/bin/perl

use strict; use warnings;
use YAML;

my @arr;
$#arr = 99; #initialize @arr capacity to 100 elements 

my %counts;

for my $i (0 .. 99) {
    my $n = int(rand(49) + 1); # pick a number
    $arr[ $i ] = $n;           # store it
    ++$counts{ $n };           # update count
}

# sort keys according to counts, keys of %counts has only the numbers drawn
# for each number drawn, create an anonymous array ref where the first element
# is the number drawn, and the second element is the number of times it was drawn
# and put it in the @result array

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

print Dump \@result;