Wednesday, January 26, 2011

Hello Code Blog!

First, an introduction.

I, am a computer engineer/computer programmer, partially in training (I am still a student).

That is, to say, I know my way around the computer, I understand some of the fundamentals. And, I love code, I wish to know more about code, and I hope to further and share this love through this blog.

This blog will tend towards presentation of compact and clean code snippets, as well as general topics of code, etc..

As my first entry to this blog, I will be presenting a simple loop in Java. I make no claims as to its originality or perfection, in fact I suspect there to be better loops out there. Its purpose, in short, is classic; to find the index of a given number for a particular function. The caveat; it must all fit on one line, in Java.

A little background on where this came from; my professor in Algorithms class was going over arrays, and how to loop through them and retrieve values using a for loop. I made the comment that what he was doing could be simplified and turned into a while loop with a bit of ternary logic. Although my first stab left out a couple edge cases, I eventually came up with the following answer, which can in fact be compiled in one line, and will correctly select the first matching value in an integer array.

while((i++<s)&&!(f=(a[i-1]==k?true:false)));return f?(i-1):-1;

At 63 characters, there are likely several optimizations that could be made to this, which I may explore in later posts. For now, feel free to download the code and hack on it, which I've licensed under the CC license  Apart from the comments the file is implemented on a single line, at 238 characters. Personally, I find it rather interesting that Java as a language is cluttered to the degree that 175 characters must be devoted to simply setting up the loop. Even if you discount  array initialization and declaration of 30 characters, which I setup as a 3 element array, and the call to print the output which takes up 23 characters, and add 8 (",int[] a") characters for passing the array in as a parameter to the loop function, you still have 130 characters being used for semantics, which is roughly half of the overall code. I suppose I could save on the character count here by removing the static qualifiers, however all of this is relatively moot, since the point is to get something executable on one line.

Please find the download on the Google Site page below:
oneLiner download
print "#3110 vv021|)"