Syntax for accessing row/column of 2D arrays

Started by lettersquash, March 10, 2020, 23:14:46

Previous topic - Next topic

lettersquash

Quick question about 2D arrays - can you refer to an entire row with a single expression, as you can access a nested array from its higher structure?
What I mean is that if I have a data structure like
a = [[1,2,3],[4,5,6],[7,8,9]]
I can use a[1] to refer to the nested array [4,5,6].
With
a = [1,2,3;4,5,6;7,8,9]
I can refer to any single element like a(1,0), and of course I can loop to get the row elements individually, but I can't use a[1] to give [4,5,6]. Is there any syntax for that?
I'll have you know, I'm coding all the right commands, just not necessarily in the right order.

ImJustAnotherCoder

#1
Sure you can:
Strict

Local a1:Int[][] = [[1,2,3],[4,5,6],[7,8,9]]
Local a456:Int[] = a1[1]

Local a2:Int[] = [1,2,3,4,5,6,7,8,9]
Local a123:Int[] = a2[0..3]


Oops, I thought this was the BlitzMax board. I don't have the answer for SmallBasic, sorry.

bplus

#2
At first I thought you couldn't, then I remembered that marvelous tool split

a = [1,2,3;4,5,6;7,8,9]
split a, ";", rows
? rows(1)


Quote4,5,6

Oh ha, ha!

a = [1,2,3;4,5,6;7,8,9]
split a, ";", rows
? rows(0)
for i in rows do ? i

see attached

This might be better:

a = "1,2,3;4,5,6;7,8,9"
split a, ";", rows
? rows(0)
?
for i in rows do ? i

see attached 2
1 person likes this

lettersquash

That's genius, and weird! So it looks like the split does that smallbasic-y thing of changing the array into a string, because split is a string function? But then split outputs an array, so rows can be treated like an array. This language is amazing and dangerous!

BTW, you can also put "[;]" as the delimiters and strip the brackets out, but you create another couple of array elements, a null string at the 0th and end.

Fascinating. Probably not suitable for what I was going to do with it, but might be useful some day. I was looking for something similar to what you can do with maps (as I called nested arrays before), erasing one of the inner maps just by referring to it, e.g. erase a[42], where a[42] is its own map, now gone and leaving a null element of the top level a[] map. I could possibly use the above, but I don't suppose it would be very efficient. The alternative with 2D arrays would be to erase each element in a loop, which is pretty fast anyway.

I wondered whether I could construct an array by making a string with brackets around it and then treating it like an array, but apparently not. I tried, and the error was that the variable wasn't an array and to use dim, but I can't even use it as an array when I've dimensioned it...perhaps because I've referred to it as a string afterwards!

Many thanks bplus!
I'll have you know, I'm coding all the right commands, just not necessarily in the right order.