Groovy 2d Arrays

I have 3 array l1[,,,,], l2[,,,,] and l3[,,,,]. Each of them has 5 characters.

e.g. l1["A","B","C","D","E"]

2d array consists of these

screen = [l1[],l2[],l3[]]

so it will look like this:

screen = [[,,,,],[,,,,],[,,,,]]

How can I iterate over this array?

I'm calling screen[5]? or screen[l1[5]]?

Can I:

for (i in 1..15){

 println screen[i]
}

Please, help!!!

How can I iterate through an array and call different parts, for example. 1st elementeach auxiliary array?

thank

+4
source share
1 answer

So, considering:

List l1 = ['A', 'B', 'C', 'D', 'E']
List l2 = ['a', 'b', 'c', 'd', 'e']
List l3 = ['1', '2', '3', '4', '5']

List screen = [ l1, l2, l3 ]

To repeat all the elements you can do:

3.times { y ->
    5.times { x ->
        println screen[ y ][ x ]  
    }
}

Or, you can use modand intdivto develop positions of x and y:

15.times { p ->
    def x = p % 5
    def y = p.intdiv( 5 )
    println screen[ y ][ x ]
}

Or, if you need the first item from each sub-list, you can do:

println screen*.head()

, , -:

println screen*.getAt( 2 )

:

def inlineScreen = [ *l1, *l2, *l3 ]

:

15.times { p ->
    println inlineScreen[ p ]
}

def x = 1, y = 1
println inlineScreen[ x + y * 5 ]

, , (.. , ), :

// groupedScreen == [['A', 'a', '1'], ['B', 'b', '2'], ['C', 'c', '3'], ['D', 'd', '4'], ['E', 'e', '5']]
def groupedScreen = [ l1, l2, l3 ].transpose()

, 3- , :

groupedScreen[ 2 ]
+9

Source: https://habr.com/ru/post/1535915/


All Articles