Tue 3 Mar 2009
write a pseudocode function that implements the following:
- 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
here are two solutions:
string function DumbWizBangCheck(int number) { string output=''; if (number%3==0) output='wiz'; if (number%5==0) output='bang'; if (number%5==0&&number%3==0) output='wiz bang'; if (output=='') output=(string) number; return output; }
string function BetterWizBangCheck(int number) { if (number%15==0) return 'wiz bang'; if (number%3==0) return 'wiz'; if (number%5==0) return 'bang'; return (string) number; }
This is of course a ridiculous question. The right answer is your first response: the most simple and readable answer. It’s easy to write and easy to read. If it *must* be optimized then there is so much more to consider – a profiler, inlining the function, etc.
If this is a question in an interview, it either means the interviewer is cleverly trying to figure out if the candidate is a premature optimizer, or it means the interviewer values “clever” code and the candidate should consider that a con to working there.
I like neither. The best solution should use if..else, which is much better optimized in every single programming language. There should also be curly brackets for grouping the statements, reducing the risk of adding something that messes up an if..else result. Lastly, assigning to a variable when simply returning (or printing to console/whatever) the value is a waste of memory, if ever so slightly.