all pairs method (almost stolen from AllPairs)