Re: Трава перл...фсем курить. Коррективы.

Greg Belenky greg на webzavod.ru
Пт Сен 26 02:27:50 CDT 2003


вот чего получилось:

use strict;

my $str = qq{A simple
.... наш любимый текст поскипан:
the decoded value.};

# считаем минимально возможную ширину строки
sub minwidth {
  my ($str) = @_;
  my $minwidth = undef;
  while ($str =~ /(\S*)\s+(\S*)/sg) {
    my $w = length($1)+length($2)+1;
    $minwidth = $w if $w > $minwidth;
    pos( $str ) -= length($2) if $2;
  }
  return $minwidth;
}

# "расширение" пробелами до необходимой длины
sub padline {
  my ($width, $line) = @_;
  while (length( $$line ) < $width) {
    if ($$line =~ /(\S)(\s)/sg) {
      substr($$line, (my $p = pos( $$line ))-1, 1) = $2x2;
      pos( $$line ) = $p;
    } else {
      pos( $$line ) = 0;
    }
  }
}

# это из предыдущего задания, только возвращает не одну строку, а список
sub greg {
  my ($width, $str) = @_;
  my $i = 0;
  my @wrap = ();

    foreach (split /\s+/, $str) {
      unless (length( $wrap[$i] ) + length() + 1 <= $width) {
        padline( $width, \$wrap[$i] );
        $i++;
      } $wrap[$i] .= ($wrap[$i] && ' ') . $_;
    } return @wrap;
}

# рисуем квадрат (если возможно)
sub square {
  my ($str) = @_;
  my $mw = minwidth( $str );
  die "Squaring is not possible..." if greg( $mw, $str ) < $mw;

  my @sqr;
  $mw++ while (do{ @sqr = greg( $mw, $str ); length( $sqr[0] ) < @sqr });
  @sqr = greg( --$mw, $str );

  if (length( $sqr[0] ) < @sqr) {
    for (my $i = 0; $i < $#sqr; $i++) {
      padline( scalar @sqr, \$sqr[$i] );
    }
  }
  return join "\n", @sqr;
}

print square( $str );

__END__

Результат (33x33):

A    simple,   easy  to  remember
system    for   encoding  integer
amounts   can be very useful. For
example,  dealers at flea markets
put   the  information  about  an
item   on  a  card  that they let
potential   buyers see. They find
it   advantageous  to  encode the
amount   they originally paid for
the   item  on  the  card. A good
system   is to use a substitution
code,   in  which  each  digit is
encoded   by a letter. An easy to
remember    10-letter   word   or
phrase,    the  key,  is  chosen.
Every    '1'   in  the  value  is
replaced   by the first letter of
the   key,  every '2' is replaced
by  the second letter of the key,
and  so on. Every '0' is replaced
by   the  last letter of the key.
Letters   that  do  not appear in
the  key can be inserted anywhere
without    affecting   the  value
represented   by  the code.. This
helps  to make the resulting code
much   harder  to  break (without
knowing  the key). Create a class
Substitute    that  contains  the
method   getValue  that  is given
the   Strings  key  and  code  as
input    and   that  returns  the
decoded value.

---
Григорий "Grishace" Беленький
http://search.cpan.org/author/GRISHACE/




Подробная информация о списке рассылки Samara-pm