Thursday, September 2, 2010

Groovy ranges and combinations

Today I stumbled upon Groovy combinations and thought I would share my findings. The idea behind them is quite simple. Take a collection of collections and produce all the combinations of those items. Here is a very quick example:

def stuff = [['apple', 'orange'], ['cat', 'zebra']]
def combo = stuff.combinations()
println combo

// results in: [[apple, cat], [orange, cat],
// [apple, zebra], [orange, zebra]]

That's neat, and useful, but really not exciting.

That's where ranges come in to play. Remember, ranges are collections too! So we can have something like this:

def pat = { "${one}-${two}-${three}" }

def range1 = 1..2
def range2 = 'A'..'B'
def range3 = 'X'..'Z'
def combo = [range1, range2, range3].combinations()

def applied = combo.collect {
one = it[0]
two = it[1]
three = it[2]
pat()
}
println applied

// results in: [1-A-X, 2-A-X, 1-B-X, 2-B-X, 1-A-Y,
// 2-A-Y, 1-B-Y, 2-B-Y, 1-A-Z, 2-A-Z, 1-B-Z, 2-B-Z]

Now that's exciting!

No comments:

Post a Comment