Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.
See all our reports

Pencils down! Solutions to our “Pat The Unicorns” Java puzzle

ZeroTurnaround’s support line was trampled by a blessing of Unicorns last week, over 170 solutions were submitted!

This put us in a tough position, because the large amount of submissions pushed the bar little higher than we expected. What we considered great solutions before became average over time, as people kept coming up with similar approaches. The puzzle was not exactly difficult to solve, but coming up with a clever and novel approach was definitely a great brain tease.

However, there was a single submission that truly caught our eye, submitted by a clever coder named David Narum, who came up with this solution. He wins our Most Creative Solution prize, and you can see his solution at the bottom of this post.

The solutions varied severely from the writing style, from poetic unicorn to spell straight out of your favorite MMORPG. Well, it kind of works, once you remove the spell output. Of course, you can just point us to right direction, like Julien did. Some of you didn’t get enough of solving the puzzle once, but had to do it in six different ways. We even received solutions in different programming languages and frameworks on the JVM, though these did not qualify to be the actual solution.

As you can see from the solutions, our Java puzzle created a twisted realm that no programmer should hopefully ever face in the course of their normal day, so let’s look at those now…

Inspect the stack trace

Most submissions went with this method to solve the puzzle.

There were several holes in the Magical Land that could be used as a hook for custom code. First of all, there was the Unicorn.pat() method, which was necessary to implement. You could remember the Unicorn.pat() method call origin by examining the stack trace and decide based on it, whether you return true or false. The HashSet was perfect for storing the value:

public class Unicorn {
  private static final Set<StackTraceElement> set = new HashSet<StackTraceElement>();
  public static boolean pat() {
    return set.add(Thread.currentThread().getStackTrace()[2]);

Custom Math class

There was the Math class which could simply be rewritten in the local package to hide the original one in java.lang, creating a very simple solution:

public class Unicorn { 
  public static boolean pat() {
    return true;

public class Math { 
  public static double random() {
    return -0.002;

This method was the second most-used solution after the Stack Trace Inspection method.

Intersect the calls to println()

Next, there were two System.out.println() method calls in the puzzle. This could enable you to use an approach similar to overriding the Math class. You could remember that the last String argument is passed to the println() method and decide whether you will pass it to the standard output or stop it from going through. To achieve that, you could either define the new System class, or simply use the System.setOut(PrintStream out) method to set custom PrintStream. The following code here shows the former solution:

class Unicorn {
  public static boolean pat() {
    return true;

class System{
  public static final System out = new System();
  private final HashSet<String> strings = new HashSet<String>();

  public void println(String str){


Other submissions used reflection API to change the default Random object in the Math class to a custom Random object, essentially getting the same behavior as writing the custom Math class.

public class Unicorn {
  static {
    Field field;
    try {
      field = Math.class.getDeclaredField("randomNumberGenerator");
      field.set(null, new Random() {
        public double nextDouble() {
          return 0;
    } catch (Exception e) {
  static int counter = 0;
  public static boolean pat() {
    return counter++ % 2 == 0;

There were also attempts to change the String class behavior by reflection, but the solutions provided were very close to crossing the Rule #2 of the puzzle: Do not print out the output directly by deflecting the program flow.

The solutions sent used the first loop to print out both of the required lines, by knowing in advance what is supposed to be printed, and then ignored the second loop. We do not consider these valid solutions because these redefined the printed Strings outside of the MagicalLand class and that kind of a loses the whole point of the puzzle (and Java method arguments).

The Universe is deterministic after all (our favorite solution)

Have you ever tried to reverse engineer the Random class? Here’s the solution we mentioned above solution by David Narum. The beauty of this solution is that it does not create pollution anywhere else, doesn’t use reflection and keeps the logic tightly in the Unicorn scope. This is a true masterpiece!

public class Unicorn {
  private static int nextRandom(long seed, int bits) {
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int)(seed >>> (48 - bits));
  private static Random getMathematicalRandomness() {
    double r = Math.random();
    long v = (long)(r * (1L << 53));
    long c1 = (long)(v >> 27);
    int c2 = (int)(v & ((1L << 27) - 1));
    for (int i=0;i<(1<<22);i++) {
      long guessSeed = (c1 << 22) + i;
      int gb = nextRandom(guessSeed, 27);
      if (gb == c2) {
        Random fancyRandom = new Random();
        fancyRandom.setSeed(guessSeed ^ 0x5DEECE66DL); //Random xors the seed when setting it, so we need to double-xor it
        return fancyRandom;
    throw new RuntimeException("Unable to break Math.random(). Is the universe really that random?");
  private static int state = 0;

   * Pat the unicorn three times for truthfullness.
   * Patting the unicorn may collapse the quantum state of the universe
  public static boolean pat() {
    Random fancyRandom = getMathematicalRandomness();
    while (fancyRandom.nextDouble() * 500 >= 1) {

    state = (state + 1)%3;
    return state == 0;

Beautiful. And here is how he did it:

The solution takes the random double from the Math.random() method and applies the logic, which was used to produce the double, backwards to get the raw components. At one point it tries to guess one of the components for the seed by iterating from 0 to 1 << 22 and comparing the produced results with one of the previously calculated components. It produces an almost-instant result on a modern computer, because 1 << 22 is only slightly below 4.2 million and the operations involved aren’t costly. The worst case scenario, 1 << 22 iterations, took around 5 ms on our normal office laptop.

When it figures out the seed, it composes a fancyRandom object, which is then used one step ahead of the real Random object. These are identical random generators, but fancyRandom is used first to know in advance what number jumps out of the Math.random() next.

The fancyRandom is then used to detect and throw away all the “big” numbers from the Math.random(), so when the Math.random() is about to produce a number small enough, the Unicorn.pat() method will return and the next number from the Math.random() will be so small that the loop breaks. For the loop to break, the incremental i in MagicalLand must be at least 3, so it returns true or false, based on Unicorn’s internal state, which keeps count of the calls.


All in all, this little puzzle proved to be great source of inspiration for coders all over the world, from Germany to India to Indiana, USA. We got a ton of responses, with one cooler than the others, we got people talking about Java and coming up with the most clever ways to come get the problem solved. Thanks for taking part, and stay tuned for the next Java puzzle: “Beat the Unicorns with Their Own Horns”. Actually, that one is just in project stage, name could change ;-)

  • Stefan

    No doubt the solution by David Narum is slick. However in terms of clean coding I would always prefer the stack trace solution.

  • Clean code doesn’t always mean less code but I guess it depends on the job. From a functional programming perspective, using the stack-trace is malicious and therefore not clean. David Narum’s solution is just mathlicious.

  • I know the stacktrace solution will work with the “javac and java” approach with default params but I wonder if it will work if compiled without debug flags? I’ll give it a shot later on!

  • Han Boon Kiat

    keep it going 0TA… this is great mental fodder! and will help to onboard a lot of us noobs

  • Stefan

    Interesting, but it would surprise me if the stack trace approach wouldn’t work without debug flags. Every exception stack depends on this information.

  • Pejobo70

    stativ boolean state = true;
    pat() {
    if (state) {
    System.out.println(“UNICORN #1: PAT THIS UNICORN ONCE”);
    System.out.println(“UNICORN #2: PAT THIS UNICORN ONCE”);
    state = false;
    return false;

    Always apply KISS ;)

  • Without line numbers stack traces would be equal, right? So there’s no way to determine if we’re patting the first beast or the second.

    A similar result can be achieved by writing in one line, rendering stacktrace approach useless.

  • Yeah, like Oleg said, once you don’t have line numbers your stacktrace elements will be the same. To test it out yourself you can take and compile with ‘javac -g:none’ and ‘java MagicalLand’. It will print

    toomasr@cigarillo-2 ~/workspace/Tmp/src » java MagicalLand

  • The original problem statement required to use the program flow and not just do static prints!

  • pejobo70

    Oh yes, this would have been really too simple.

  • srbs

    Ha, I got a variation of all four ‘normal’ solutions. I tried my best to reverse engineer the Random class, but it was beyond me.
    Thanks to David Narum for a way to do that.