Chinaunix

标题: 求助:perl格式化数组 [打印本页]

作者: 815138698    时间: 2015-07-28 19:05
标题: 求助:perl格式化数组
Write a function, format_number_list, whose argument is a list of integers.  It then returns a string which represents the input list in compact, human-readable form.
For example,
         format_number_list (1, 2, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27)
will return
        "1-2, 4-7, 9, 13, 24-27"
Also write a function, 'expand_number_list', which does the conversion in the opposite direction, so that
        expand_number_list("1-2, 4-7, 9, 13, 24-27")
will return
        (1, 2, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27)

作者: MMMIX    时间: 2015-07-28 20:24
题目不错呀
作者: rubyish    时间: 2015-07-29 01:03
biru:
  1. #!/usr/bin/perl
  2. use 5.022;

  3. sub Join {
  4.     my @a = [shift];
  5.     $_ - $a[-1][-1] > 1 ? push @a, [$_] : ( $a[-1][1] = $_ ) for @_;
  6.     join ', ', map { join '-', @$_ } @a;
  7. }

  8. sub Split {
  9.     map { @_ = /\d+/g; $_[0] .. $_[$#_] } split ', ', pop;
  10. }

  11. my @input = ( 1, 2, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27 );
  12. my $list  = Join @input;
  13. my @list  = Split $list;

  14. say "@input";
  15. say $list;
  16. say "@list";
复制代码

作者: MMMIX    时间: 2015-07-29 09:16
回复 3# rubyish


    Join 的实现可以再稍微简化下,就和上面的 Split 风格更一致了:

  1. map { @_ = split '-'; $_[0] .. $_[-1] } split ', ', pop;
复制代码

作者: rubyish    时间: 2015-07-29 23:36
回复 4# MMMIX

    map { @_ = split '-'; $_[0] .. $_[-1] } split ', ', pop;


3Q ~ xiangbudao  -1
split '-' : 9 chars
/\d+/g : 6 chars
作者: MMMIX    时间: 2015-07-30 09:36
回复 5# rubyish


    你在 Split 里面 -1 用的挺好的呀。

/\d+/g 更短这个还真没注意,我主要是考虑到在 Split 里面用了两个 join, 刚好能和 Join 里面的两个 split 对上,然后看起来会更对称一些。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2