def fact(BigInteger n) {
(n == 0 || n == 1) ? 1 : n * fact(n-1)
}
def fisherExactTest(def matrix) {
def rowSums = []
def colSums = []
matrix.eachWithIndex { row, i ->
rowSums[i] = row.sum()
row.eachWithIndex { val, j ->
colSums[j] = colSums[j] == null ? val : colSums[j] + val
}
}
def totalSum = rowSums.sum()
def factorialProduct = { x, y ->
x * fact(y)
}
(rowSums.inject(1, factorialProduct) * colSums.inject(1, factorialProduct)) / (fact(totalSum) * matrix.flatten().inject(1, factorialProduct))
}
println fisherExactTest([[5, 0],[1, 4]])
println fisherExactTest([[15, 20, 15],[20, 25, 5]])