A response to the "wiz bang" question
Posted: 3 March 2009 at 10:25:11
(Ryan Byrd)[http://www.ryanbyrd.net/techramble/] blogged recently with a (programming interview question)[http://www.ryanbyrd.net/techramble/2009/03/03/programming-interview-question-of-the-day/] that I thought I'd take a stab at in Perl.
The question is as follows:
- when passed in a number that is evenly divisible by 3, return "wiz"
- when passed in a number that is evenly divisible by 5, return "bang"
- when passed in a number that is evenly divisible by both 3 and 5, return "wiz bang"
- otherwise, return the number passed in
My solution exploits Perl's list type to store potential output as a queue of sorts.
sub function {
my $num = shift;
my @output = ();
unless($num % 3) { push @output, "wiz"; }
unless($num % 5 ) { push @output, "bang"; }
if(@output) { return join ' ', @output; }
return $num;
}