AmenKa

09-20-2011, 02:59 PM

Curious question, do other people get put off as easily as I do when you see a somewhat simple mistake in a code tutorial? Example below.

In a tutorial related to OpenCL, the author wrote the following function to represent the mathematical max function.

int max(int[] x)

{

int max = -1;

for(int i = 0; i < x.length; i++)

if(max < x[i]) max = x[i];

return max;

}

This really bothered me as it only covers half of the domain of the function it is supposed to implement, and I felt it was obvious a simple change is in order:

int max(int[] x)

{

int max = x[0];

for(int i = 1; i < x.length; i++)

if(max < x[i])

max = x[i];

return max;

}

This version (only two simple changes) covers the entire domain of the function it represents, and is technically less computationally expensive (saves one comparison always and makes better use of the assignment). I couldn't continue reading the tutorial and closed it to look for another because this bothered me so much. Am I a code snob?

PS: Just a note: the tute. author's version will never fail. My version will throw an index out of bounds exception if you pass it an array with no values.

In a tutorial related to OpenCL, the author wrote the following function to represent the mathematical max function.

int max(int[] x)

{

int max = -1;

for(int i = 0; i < x.length; i++)

if(max < x[i]) max = x[i];

return max;

}

This really bothered me as it only covers half of the domain of the function it is supposed to implement, and I felt it was obvious a simple change is in order:

int max(int[] x)

{

int max = x[0];

for(int i = 1; i < x.length; i++)

if(max < x[i])

max = x[i];

return max;

}

This version (only two simple changes) covers the entire domain of the function it represents, and is technically less computationally expensive (saves one comparison always and makes better use of the assignment). I couldn't continue reading the tutorial and closed it to look for another because this bothered me so much. Am I a code snob?

PS: Just a note: the tute. author's version will never fail. My version will throw an index out of bounds exception if you pass it an array with no values.