December 24, 2009

Groovy Goodness: Looping Through Each Permutation in a Collection

Groovy 1.7 adds news methods to the standard Java classes. One of the new methods is eachPermutation(). With this method we can loop through all permutations of a collection and run a closure for the iterations. To get all permutations for a collection we can use the permutations() method.

def languages = ['Groovy', 'Clojure', 'Scala']

def result = []
languages.eachPermutation {
    result << it

assert 6 == result.size()
assert ['Groovy', 'Clojure', 'Scala'] == result[0]
assert ['Groovy', 'Scala', 'Clojure'] == result[1]
assert [['Clojure', 'Groovy', 'Scala'], ['Clojure', 'Scala', 'Groovy']] == result.findAll { it[0] == 'Clojure' }

// We can also get the complete list of permutations as Set.
def list = [true, false]
def permutations = list.permutations()
assert 2 == permutations.size()
assert [[false,true], [true,false]] as Set == permutations