5

我有一组可变大小的字符串,例如:

AAA23

AB1D1

A1BC

AAB212

我的目标是按字母顺序和为 COLUMNS 收集的唯一字符,例如:

第一栏:AAAA

第二栏:AB1A

等等...

此刻,我能够通过哈希值提取帖子。但是现在,我该如何对数据进行排序?我可以为哈希的每个哈希创建一个新数组吗?

非常感谢您的帮助!

我的代码:

#!/usr/bin/perl

use strict;
use warnings;

my @sessions = (
    "AAAA",
    "AAAC",
    "ABAB",
    "ABAD"
);

my $length_max = 0;
my $length_tmp = 0;

my %columns;

foreach my $string (@sessions){

    my $l = length($string);

    if ($l > $length_tmp){
            $length_max = $l;
    }
}

print "max legth : $length_max\n\n";

my $n = 1;

foreach my $string (@sessions){

    my @ch = split("",$string);

    for my $col (1..$length_max){
        $columns{$n}{$col} = $ch[$col-1];
    }

    $n++;
}

foreach my $col (keys %columns) {

    print "colonna : $col\n";

    my $deref = $columns{$col};

    foreach my $pos (keys %$deref){
            print " posizione : $pos --> $$deref{$pos}\n";
    }

    print "\n";
}

exit(0);
4

2 回答 2

2

你正在做的是旋转阵列。它不需要散列或任何东西的散列,只需要另一个数组。令人惊讶的是,List::Util 和 List::MoreUtils 都没有提供。这是一个带有测试的简单实现。我假设您希望用空格填充简短条目,以便列正确。

#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use List::Util qw(max);

my @Things = qw(
    AAA23
    AB1D1
    A1BC
    AAB212
);


sub rotate {
    my @rows = @_;

    my $maxlength = max map { length $_ } @rows;

    my @columns;
    for my $row (@rows) {
        my @chars = split //, $row;
        for my $colnum (1..$maxlength) {
            my $idx = $colnum - 1;
            $columns[$idx] .= $chars[$idx] || ' ';
        }
    }

    return @columns;
}


sub print_columns {
    my @columns = @_;

    for my $idx (0..$#columns) {
        printf "Column %d: %s\n", $idx + 1, $columns[$idx];
    }
}


sub test_rotate {
    is_deeply [rotate @_], [
        "AAAA",
        "AB1A",
        "A1BB",
        "2DC2",
        "31 1",
        "   2",
    ];
}


test_rotate(@Things);
print_columns(@Things);
done_testing;
于 2010-07-08T18:42:17.227 回答
0

%columns您可以使用以下命令对代码中的输出进行排序

foreach my $i (sort { $a <=> $b } keys %columns) {
  print join(" " => sort values %{ $columns{$i} }), "\n";
}

这给

AAAA
AAAC
AABB
AABD

但是使用索引号作为散列键意味着您应该使用数组来代替,所以让我们这样做。要获取列,请使用

sub columns {
  my @strings = @_;
  my @columns;

  while (@strings) {
    push @columns => [ sort map s/^(.)//s ? $1 : (), @strings ];
    @strings = grep length, @strings;
  }

  @columns;
}

给定您问题中的字符串,它会返回

AAAA
1个AAB
1 ABB
2 2 光盘
1 1 3
2

如您所见,这是未排序的并重复字符。在 Perl 中,当你看到唯一这个词时,总是会想到哈希!

sub unique_sorted_columns {
  map { my %unique;
        ++$unique{$_} for @$_;
        [ sort keys %unique ];
      }
      columns @_;
}

如果您不介意破坏信息,则可以columns对重复项进行排序和过滤:

sub columns {
  my @strings = @_;
  my @columns;

  while (@strings) {
    my %unique;
    map { ++$unique{$1} if s/^(.)//s } @strings;
    push @columns => [ sort keys %unique ];
    @strings = grep length, @strings;
  }

  @columns;
}

输出:

一个
1 AB
1 AB
2张光盘
1 3
2
于 2010-07-08T18:57:01.230 回答