And of course I immediately thought "How could I golf this?" and after a couple of rounds on IRC I produced this:#Returns a copy of the input padded to size specified by pad_size with + value pad_value. #If pad_size is positive then the array is padded on the right, if it' +s negative then on the left. #If the absolute value of pad_size is less than or equal to the length + of the input then no padding takes place. #int pad_size, mixed pad_value, array input sub array_pad{ my($pad_size, $pad_value, @array) = @_; #this is just to get the absolute value of the pad_size my $temp = $pad_size; if($pad_size < 0){ $temp = $temp * -1; }#if #first let's see if the pad_size is less than or equal to the arra +y size, return 0 no padding my $input_size = @array; if($temp <= $input_size){ return 0; }#if #since it didn't return 0, time to pad #if the pad_size is < 0, pad on the left, else the right if($pad_size < 0){ my @retval; $temp = $temp - $input_size; for(my $i=0;$i<$temp;$i++){ unshift(@array, $pad_value); }#for return @array; }#if else{ $temp = $pad_size - $input_size; for(my $i=0;$i<$temp;$i++){ push(@array, $pad_value); }#for return @array; }#else }#array_pad
Which is really fairly long, and I know there are better solutions, because other people wrote some =].sub p{my($i,$z,@f)=@_;abs$i>@f&&$i<0?@f=(($z) x abs($i+@f),@f):(@f[@f. +.$i-1]=($z)x($i-@f));@f}
use Test::More tests => 4; my @x = 1 .. 5; is_deeply([p( 3, 'x', @x)], [ @x ]); is_deeply([p(-3, 'x', @x)], [ @x ]); is_deeply([p( 7, 'x', @x)], [ @x, 'x', 'x' ]); is_deeply([p(-7, 'x', @x)], [ 'x', 'x', @x ]);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Golfing Array_Pad (54)
by Zaxo (Archbishop) on Jan 23, 2005 at 06:12 UTC | |
by demerphq (Chancellor) on Jan 24, 2005 at 12:13 UTC | |
|
Re: Golfing Array_Pad
by Zaxo (Archbishop) on Jan 23, 2005 at 05:29 UTC | |
|
Re: Golfing Array_Pad
by PodMaster (Abbot) on Jan 23, 2005 at 05:48 UTC | |
by BUU (Prior) on Jan 23, 2005 at 05:55 UTC | |
by PodMaster (Abbot) on Jan 23, 2005 at 06:28 UTC | |
|
Re: Golfing Array_Pad
by holli (Abbot) on Jan 23, 2005 at 11:15 UTC | |
by demerphq (Chancellor) on Jan 24, 2005 at 16:10 UTC | |
by holli (Abbot) on Jan 24, 2005 at 16:14 UTC | |
by demerphq (Chancellor) on Jan 24, 2005 at 16:20 UTC | |
|
Re: Golfing Array_Pad [55]
by demerphq (Chancellor) on Jan 24, 2005 at 12:01 UTC |