Faster Java solution for generalized http://unriskinsight.blogspot.com/2014/06/fast-functional-goats-lions-and-wolves.html