Last active
December 13, 2015 23:19
-
-
Save ethankhall/4990742 to your computer and use it in GitHub Desktop.
Magical Java Puzzle: “Pat The Unicorns”
This file contains 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
package io.ehdev; | |
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"); | |
} | |
} |
This file contains 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
package io.ehdev; | |
public class Unicorn { | |
static Integer lineNumber = null; | |
public static boolean pat() { | |
StackTraceElement[] currentStackTrace = Thread.currentThread().getStackTrace(); | |
StackTraceElement returnAddress = currentStackTrace[2]; | |
int currentLineNumber = returnAddress.getLineNumber(); | |
if(lineNumber == null || currentLineNumber != lineNumber){ | |
lineNumber = currentLineNumber; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment