This is the solution to Lab 4. You can also get this file here.

#!/usr/bin/perl -w

# loop_add calculates the sum of a list of numbers using a loop
# Takes a single parameter, a list of numbers and returns their sum
sub loop_add {
  my($sum) = 0;
  for (my($i)=0; $i<@_; $i++) {
    $sum += $_[$i];
  }
  return $sum;
}

# unbal_add calculates the sum of a list of numbers using
# a simple recursion
# Takes a single parameter, a list of numbers and returns their sum
# It pops the last number off the list.  If the remaining list
# is nonempty it calculates its sum recursively and returns
# this sum plus the value popped off
sub unbal_add {
  my($lastnum) = pop @_;
  if (@_) {
    return $lastnum + unbal_add( @_ );
  }
  return $lastnum;
}

# bal_add calculates the sum of a list of numbers using
# a balanced  recursion
# Takes a single parameter, a list of numbers and returns their sum
# It pops half the numbers off the list, sums both halves
# recursively and returns the total of the two sums
sub bal_add {
  if (@_ == 1) {
    return pop @_;
  }
  my @half_list = ();
  while ($#_ > $#half_list) {
    push @half_list, pop @_;
  }
  return bal_add( @_ ) + bal_add( @half_list );
}

# Ask the user which subroutine to test, and which size(s)
# of arrays to test
print "Which subroutine would you like to test?\n";
print "  1) Loop\n";
print "  2) Unbalanced recursion\n";
print "  3) Balanced recursion\n";
print "Enter number: ";
chomp( $code =  );
while ( ($code < 1) || ($code > 3) ) {
  print "$code is not valid.  Try again: ";
  chomp( $code =  );
}
print "What is the minimum size you want to test? ";
chomp( $minsize =  );
while ( $minsize < 10 ) {
  print "$minsize is too small.  Enter a larger value: ";
  chomp( $minsize =  );
}
print "What is the maximum size you want to test? ";
chomp( $maxsize =  );
while ( $maxsize < $minsize ) {
  print "$maxsize is too small.  Enter a larger value: ";
  chomp( $maxsize =  );
}
if ($minsize == $maxsize) { $stepsize = 1; }
else {
  print "What step size would you like? ";
  chomp( $stepsize =  );
  while ( $stepsize < 10 ) {
    print "$stepsize is too small.  Enter a larger value: ";
    chomp( $stepsize =  );
  }
}

# Open the results file and loop through the specified tests
open TIMING, ">timefile";
for ($size=$minsize; $size<=$maxsize; $size+=$stepsize) {
  @numarray = ();
  for ($i=0; $i<$size; $i++) {
    push @numarray, -1 + int rand 2;
  }
  $start = times();
  if ($code == 1) {
    $sum = loop_add( @numarray );
  } elsif ($code == 2) {
    $sum = unbal_add( @numarray );
  } else {
    $sum = bal_add( @numarray );
  }
  $end = times();
  $elapsed = $end - $start;
  print TIMING "$size\t$elapsed\n";
}