Last active
December 13, 2015 23:59
-
-
Save agrison/4996166 to your computer and use it in GitHub Desktop.
Magical Java Puzzle: Pat the unicorns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** See: http://zeroturnaround.com/fun/magical-java-puzzle-pat-the-unicorns/ */ | |
import java.util.*; | |
public class Unicorn { | |
static Set<Integer> lines = new HashSet<Integer>(); | |
public static boolean pat() { | |
int callerLine = Thread.currentThread().getStackTrace()[3].getLineNumber(); | |
return lines.add(callerLine); | |
} | |
} | |
/** | |
* When called by the following program: | |
<code> | |
public class MagicalLand { | |
public static void main(String[] args) { | |
for (int i = 0; i < (Math.random() * 500) + 2; i++) { | |
if (Unicorn.pat()) { | |
System.out.println("UNICORN #1: PAT THIS UNICORN ONCE"); | |
} | |
} | |
for (int i = 0; i < (Math.random() * 500) + 2; i++) { | |
if (Unicorn.pat()) { | |
System.out.println("UNICORN #2: PAT THIS UNICORN ONCE"); | |
} | |
} | |
System.out.println("END OF PROGRAM"); | |
} | |
} | |
</code> | |
* | |
* Will print: | |
UNICORN #1: PAT THIS UNICORN ONCE | |
UNICORN #2: PAT THIS UNICORN ONCE | |
END OF PROGRAM | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's an elegant solution :)