Wednesday, February 29, 2012

collate

//src: http://blog.bloidonia.com/post/18073244930/whats-new-in-groovy-1-8-6-the-collate-method

//v1.8.6+//
def list = 1..10
def listInFours  = list.collate( 4 )
assert listInFours == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]

def listInFours2 = list.collate( 4, false )

// Notice the [ 9, 10 ] remainder has been dropped
assert listInFours2 == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]

def gridList = list.collate( 3 ).collate( 2 )

assert gridList == [ [ [1, 2, 3], [4, 5, 6] ],
                     [ [7, 8, 9], [10]      ] ]

def mph        = [ 10, 26, 30, 32, 27, 14, 19, 22, 40, 14 ]
def window     = mph.collate( 3, 1, false )

assert window == [ [10, 26, 30],
                   [26, 30, 32],
                   [30, 32, 27],
                   [32, 27, 14],
                   [27, 14, 19],
                   [14, 19, 22],
                   [19, 22, 40],
                   [22, 40, 14] ]
                   
def windowAvg  = window*.sum()*.intdiv( 3 )
assert windowAvg == [22, 29, 29, 24, 20, 18, 27, 25]

def items   = [ 'ham', 30, 'cheese', 20, 'steak', 95 ]
def itemMap = items.collate( 2 ).collectEntries()

assert itemMap == [ ham:30, cheese:20, steak:95 ]

def range   = 1..20
def (odds,evens) = range.collate( 2 ).transpose()

assert odds  == (1..19).step( 2 ) // odd numbers 1 - 19
assert evens == (2..20).step( 2 ) // even numbers 2 - 20

No comments:

Post a Comment