By comparing `personal solution with `canonical, for a given problem, we can analyze what is our essence.
Many interview problem designed just for that purpose.
Problem One - `FooBuzz'.
You asked to enumerate numbers fro 1 to 100. It it is multiple of 3 then print `Foo. If multiple of 5 then print `Buzz. If multiple of both print `FooBuzz else print number.
Solution show the balance of mathematical awareness versus following programming standard.
Canonical solution for different type of languages (I skip most and ignore non-mainstream).
`C
int main ()
{
for (int i = 0; i < 100; ++i) {
bool flag = false;
if (i % 3 == 0) {
printf("Foo");
flag = true;
}
if (i % 5 == 0) {
printf("Buzz");
flag = true;
}
if (flag) {
printf("\n");
} else {
printf("%d\n", i);
}
}
}
`Python
for i in range (1, 100):
s = ""
if i % 3 == 0: s+="Foo"
if i % 5 == 0: s+="Buzz"
if s == "": s += str(i)
print s
`Scala
def FooBuzz {
for (i <- 1 until 100) {
val s = { if(i % 3 == 0) "Foo" else "" } +
{ if(i % 5 == 0) "Buzz" else "" }
println ( if(s.isEmpty) i.toString else s )
}
}
There is no extensive study of deviations for this solution only observations gathered from limited sources.
On math side main problem is failure to recognize instance of Monoids {nat, %} and {string, +} which naturally additive and don't need special treatment in code.
On coding side variety language specific problems. Only one was common - putting conditional of multiple being equal 0 but not just `i % 3.
Our efficiency as designer proportional to degree of flexibility we can take without damaging our brain. This and similar test show us our limits.
No comments:
Post a Comment