Background: I introduced code golf in a previous post.
I recently came across an easy but fun problem posted on Yahoo! Answers. It could make for a good code golf exercise. I will write the problem statement in a purposely vague manner, but clear enough to make the goal obvious; specifics can be added according to any particular contest or testing environment.
Using only recursion and no loops, print a triangular pattern of asterisks according to the following example:
* * ** *** ** *
Background: Code golf is a game in which the goal is to solve programming problems using as few keystrokes as possible. It has its roots in Perl golf, and anyone with golfing experience knows that Perl is particularly well suited to such challenges. J and K, as well as the more esoteric GolfScript, are also known for combining terse syntax with powerful features. Obfuscation is a related topic.
In this post, I will discuss a snippet of Java code one might not normally think to write. I understand that “Java code golf” is practically an oxymoron, since it seems the goal of Java is to write code using as many keystrokes as possible, but let us overlook this point for now.
Suppose we want to increment a variable by an integer from standard input, but only if that integer is positive. We could use this code fragment: