Re:Array Iteration Interview Problem
by kbenson on Wednesday August 01, 2012 @11:43PM
(#4327137)
perl, for fun:
sub add1 {
my ($arrayref,$val,$count) = @_;
# Just incremet matches and return if we aren't limited
# Useless return of array ref
return \map { $_++ if $_ == $val } @$arrayref unless $count;
# increment up to count matches
for ($count<0 ? reverse @$arrayref : @$arrayref) {
next if $_ != $val;
$_++;
# Advance count towards zero
$count<0 ? $count++ : $count--;
return if $count == 0;
}
}
Splitting the loop into separate versions for positive and negative counts is quicker than checking if count is positive or negative each iteration, but I figured that's a step more than I wanted to take it.
Alternatively, defining a variable for the amount the $count changes (-1 or 1) and just adding that to count would work as well, but I'm working under the assumption that's less likely to be special cased in the interpreter than post-{in,de}crement.
Edit: Clarified reasoning behind post-increment, etc.
Alternatively, defining a variable for the amount the $count changes (-1 or 1) and just adding that to count would work as well, but I'm working under the assumption that's less likely to be special cased in the interpreter than post-{in,de}crement.
Edit: Clarified reasoning behind post-increment, etc.