Groovy - Create a 2-dimentional array

Viewed 42

I have a function

def workTheList (List data, cutIndex){...}

The function should get the list and cutIndex as integer. i want to create a 2nd dimensional array from this data. example: list = '1.1.1.1','2.2.2.2','3.3.3.3' .. (for example lets say 40 ips) cutIndex = 5

so 40 / 5 = 8 I would like to get an Array.size = 8 and Array[0] = '1.1.1.1','2.2.2.2','3.3.3.3'... (Each array item need to hold 5 ips)

def workTheList (List data, cutIndex){
    def arraySize = Math.round(Math.ceil(data.size / cutIndex))
       
    
    println("array size will be " + arraySize)

    def myArray = new String[arraySize][cutIndex]
    //myArray[0] = (items in data from 0 to cutIndex )
    //myArray[1] = (items in data from cutIndex to (cutIndex*2))
    //myArray[2] = (items in data from (cutIndex*2) to (cutIndex*3))
    //.
    //.
    //.
}

Disregard the fact that i will loop it but this is the main logic that i need. id be happy for some help with this im very new to groovy

1 Answers

collate() is here to help:

def workTheList (List data, cutIndex){
  def list2d = data.collate cutIndex
  ( cutIndex - list2d.last().size() ).times{ list2d.last() << 0 } // fill the last element with some defaults
  list2d
}

def res = workTheList 1..20, 4
assert res == [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

res = workTheList 1..20, 3
assert res == [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 0]]

res = workTheList 1..23, 7
assert res == [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 0, 0, 0, 0, 0]]
Related