For the beginner quiz:
I decided not to sort the list and not to remove duplicates.
Reason: Trying to "do one thing" and trying to keep individual functions
simple and clean. If further manipulation is required, I'd (probably)
put it outside these two subs.
I don't handle negative numbers at all. I count this as a bug.
I don't get much chance for skilled code review where I work.
If you take the time to read this, and have any comments, please don't
keep them to yourself.
Thanks!
My notes:
-------------------
For expand_number_list:
if a single number, push it to the array
if a range of numbers, push each element of the range to the array.
For format_number_list:
normal case:
if the next is one more than this one and a starting point is defined,
move on.
if the next is one more than this one and no starting point is
defined, define it to be this one and move on.
if the next is not one more than this one, and a starting point is
defined, write "starting point - this one, " and then undefine the
starting point.
if the next is not one more than this one, and no starting point is
defined, write "this one, "
special case (first element)
This is not a special case.
special case (last element)
if a starting point is defined, write "starting point - this one"
if a starting point is not defined, write "this one."
My code:
-------------------
#!/usr/bin/perl -w
use strict;
my @numbers = ( 1,2,4,5,6,7,9,13,24,25,26,27);
print "Beginning with this list:\n";
print "$_ " for @numbers;
print "\n\nformat_number_list turns it into this:\n";
my $list = format_number_list( @numbers );
print $list;
print "\n\nexpand_number_list turns *that* into this:\n";
print "$_ " for expand_number_list( $list );
#########
sub format_number_list{
my @num = @_;
my $out = '';
my $run_start;
my $i;
for( $i=0; $i<$#num; $i++ ){
if( $num[$i] == ($num[$i+1] - 1) ){
$run_start = $num[$i] unless( defined ($run_start) );
}
else{
if( defined $run_start ){
$out .= "$run_start-";
undef $run_start;
}
$out .= "$num[$i], ";
}
}
# last element
if( defined $run_start ){
$out .= "$run_start-";
}
$out .= "$num[$#num]";
return $out;
}
sub expand_number_list{
my $list = shift;
my @list = split /, /, $list;
my @out = ();
foreach(@list){
if( /^(\d+)-(\d+)$/ ){
push @out, ($1 .. $2);
}
else{
push @out, $_;
}
}
return @out;
}
|