Tuesday, September 08, 2015

Complicated Solutions To Simple Problems

I found this on the Internet today via Twitter.
isneg
It works. Well more or less. I can imagine cases where it might not but they include other problems. It’s not very efficient. A simple bit of code like this should do the trick with a lot less effort.
   1: static bool isNegative(float arg)

   2: { return arg < 0.0; }

It also avoids the horrible memory link of a malloc without a corresponding free to give the memory back. Yes, the example is in C and not one of those cool languages with garbage collection.

These sorts of solutions appeal to some beginners. When I shared this I heard from people who have seen similar code for things like separating characters in a number. Why do they do things like this? Mostly it is because they don’t know better. That doesn’t mean they may not know other tools so much as it means they don’t know how to apply the tools they do know. So they look for solutions and grab the first one they find.

Often students will argue that “it works” means something should get full credit. The rubric I’m using this year (borrowed from Harvard’s CS50 course) includes an explicit look on how efficient the solution is.  I want to encourage students to look beyond the first solution they come up with and think about efficiency.

1 comment:

  1. Decades ago my coworkers and I mused that Byte Magazine (I know, I'm dating myself) should have a contest for the most obscure coding of a simple solution. Sad thing is that years later (mid- to late-80's) I came across a prime example of this in device driver code for a major operating system: A single module that could be included in either C or x86 Assembler (whichever you preferred). The code relied on the fact that comments in C could begin with /* and end with */, while comments in x86 Assembler began with a semicolon. Thus lines in the file looked like this:

    ;/*
    mov ax,0A14h ;*/ int x = 0x0A14; /*
    mov bx,0003h ;*/ int y = 3; /*
    ;*/

    The Assembler compiler would ignore everything after a semicolon, and just compile the "mov ax" and "mov bx" lines.
    The C compiler would ignore the initial semicolon as an empty statement, then ignore everything between the /* and */, and compile the "int x" and "int y" statements.

    Did it work? Yes.
    Should it ever been done? NO WAY!

    ReplyDelete