I have 3 arrays, l1[,,,,], l2[,,,,] and l3[,,,,]
. Each of which has 5 characters in it.
e.g. l1["A","B","C","D","E"]
The 2d array is made up of these
screen = [l1[],l2[],l3[]]
so it will look as so:
screen = [[,,,,],[,,,,],[,,,,]]
How can I iterate through this array?
do I call screen[5]
? or screen[l1[5]]
?
can I:
for (i in 1..15){
println screen[i]
}
please help!!!
How can I iterate in the array and call different parts, e.g. the 1st element
of each sub array?
Thanks
To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.
A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional array of characters.
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. int x = a[1,1]; Console. WriteLine(x);
Two-dimensional arrays can be defined as arrays within an array. 2D arrays erected as metrics, which is a collection of rows and columns.
So, given:
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 iterate all the elements, you could do:
3.times { y ->
5.times { x ->
println screen[ y ][ x ]
}
}
Or, you could use mod
and intdiv
to work out x and y positions:
15.times { p ->
def x = p % 5
def y = p.intdiv( 5 )
println screen[ y ][ x ]
}
Or, if you want the first element from each sub-list, you can do:
println screen*.head()
Or, say you want the 3rd element from each sub-list:
println screen*.getAt( 2 )
Alternatively, you could put all the items into a one-dimensional List:
def inlineScreen = [ *l1, *l2, *l3 ]
Then access then by:
15.times { p ->
println inlineScreen[ p ]
}
or:
def x = 1, y = 1
println inlineScreen[ x + y * 5 ]
Or, if it is important that you always want to get the elements together (ie, you always want the second elements from all the arrays together), then you could do:
// groupedScreen == [['A', 'a', '1'], ['B', 'b', '2'], ['C', 'c', '3'], ['D', 'd', '4'], ['E', 'e', '5']]
def groupedScreen = [ l1, l2, l3 ].transpose()
Then, to get the 3rd elements, you can just do:
groupedScreen[ 2 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With