TITLE: Something New Every Day AUTHOR: Eugene Wallingford DATE: October 11, 2005 6:54 PM DESC: Just when I think I have seen it all, a student does something fresh and strange. ----- BODY: I'm not a Way Old-Timer, but I have been teaching at my current university for thirteen years. In that time, I have seen a lot of odd student programs: wacky bugs, quirky algorithms, outlandish hacks, and just plain funny code. But today I saw a new one... One of my colleagues is teaching our intro majors course. In the lab today, he asked students to write some code, including a three-argument Java method to return the minimum of the three. The goal of this exercise was presumably to test the students' ability to consider multiple decisions, to write compound boolean expressions, and most probably to write nested if statements. Here is my rendition of one student's extraordinary solution:
```    public int min( int x, int y, int z )
{
for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++)
if ( i == x )
return x;
else if ( i == y )
return y;
else if ( i == z )
return z;
}
```
Sadly, the student didn't do this quite right, as right would be for this approach. The program did not use Integer.MIN_VALUE and Integer.MAX_VALUE to control its loop; it used hardcoded negative and positive 2,000,000,000. As a result, it had to throw in a back-up return statement after the for-loop to handle cases where the absolute of all three numbers were greater than 2,000,000,000. So, the solution loses points for correctness, and a bit of luster on style. But still -- wow. No matter what instructors think their students will think, the students can come up with something out of left field. I have to admit... In a certain way, I admire this solution. It demonstrates creativity, and even applies a pattern that works well in other contexts. If the student had been asked to write a method to find the smallest value in a three-element unsorted array, then brute force would not only have seemed like a reasonable thing to do; it would have been the only option. Why not try it for ints? (For us XP mavens: Is this algorithm the simplest thing that will work?) One answer to the "Why not?" question comes at run time. This method uses 12 seconds or so on average to find its answer. That's almost 12 seconds more than an if-based solution uses. :-) Students can bring a smile to an instructors face most every day. -----