Skip to content

Instantly share code, notes, and snippets.

@palmerabollo
Created March 6, 2013 23:24
Show Gist options
  • Save palmerabollo/5104187 to your computer and use it in GitHub Desktop.
Save palmerabollo/5104187 to your computer and use it in GitHub Desktop.
Magical Java Puzzle: “Pat The Unicorns”
import java.io.PrintStream;
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");
}
}
class Unicorn {
static String lastOutput = null;
static {
System.setOut(new PrintStream(System.out) {
@Override
public void println(String x) {
switch (x) {
case "UNICORN #1: PAT THIS UNICORN ONCE":
if (lastOutput == null) {
super.println(x);
}
break;
case "UNICORN #2: PAT THIS UNICORN ONCE":
if (!lastOutput.equals(x)) {
super.println(x);
}
break;
default:
super.println(x);
}
lastOutput = x;
}
});
}
static boolean pat() {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment