February 20, 2013

Magical Java puzzle, Pat the Unicorns

Yesterday while browsing the web I found that blog post by ZeroTurnaround: “Magical Java puzzle, pat the Unicorns“. It seemed interesting to find an easy and elegant solution. This is what I came up with:

/** 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:
 */
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");
  }
}
/*
 *
 * Will print:
UNICORN #1: PAT THIS UNICORN ONCE
UNICORN #2: PAT THIS UNICORN ONCE
END OF PROGRAM
 */

https://gist.github.com/agrison/4996166

Cheers !

Alexandre Grison - //grison.me - @algrison