r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

39

u/OneWingedShark May 08 '15

Problem 1

Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.

So, how many solutions had recursion, for-loops, and while-loops in all three functions? ;)

10

u/sarahbau May 08 '15

Or used recursion, for, and while to get one solution

#!/usr/bin/perl
use strict;

my @list = (1,2,3,4,5,6,7,8,9,10);
my $size = scalar(@list);
my $i = 0;



my $sum = &forsum + &whilesum + &recsum(@list);
print "sum = $sum\n";


sub forsum() {
	my $s = 0;
	for( ; $i<($size/3); $i++) {
		$s+=shift(@list);
	}
	return $s;
}

sub whilesum() {
	my $s = 0;
	while($i < ($size/3)*2) {
		$s+=shift(@list);
		$i++;
	}
	return $s;
}

sub recsum() {
	if((scalar @_) == 0) {
		return 0;
	}
	return shift(@_) + &recsum(@_);
}

(yes, this was meant to be horrible. I just felt like being silly).

→ More replies (5)