DevilWAH
DevilWAH

Reputation: 2633

Looping through arrays of different sizes

Hi I have lets imagen 3 arrays

ArrayA = {1,2,3}
ArrayB = {4,5,6,7}
ArrayC = {8,9,10,11,12}

I want to loop though these but in sequence like below

print ArrayA,B,C first value
print ArrayA,b,C second value
print ArrayA,B,C third value
print ArrayA,b,C forth value
... ... ...

so it would output

1,4,8
2,5,9
3,6,10

at this point Array A needs to wrap around so the next output would be

1,7,11
2,4,12
... ...

if the arrays where the same size of 10 items I could do

x = 0 to 9
print ArrayA{x}
print ArrayB(x)
print ArrayC(x)
next x

but with arrays of different lengths can i still put them in the same loop I suppose I could put a counted with in the array that increments each time the loop runs, like the

x=x+1 if x > array max value then x = 0

but can it be done in a more efficent way?

I am looking at doing this in perl and I know the above code is nothing like perl, so the actual code is below but currently I am playing in VBA.

stars is a 199 single dimension array and each item in this array is a 2 dimension array 720 long and 3 wide. SO stars(individual star)(point on orbit, x cordinate, y cordinate)

so star(1) contains the array that has the x,y cordinates of the orbit of the star in 0.5 degree resolution. but some need to have different resolutions so will vary in size. but i still want to be able to loop through them continually and wrap around each array as needed.

For h = 0 To 720
'Application.ScreenUpdating = False
For st = 0 To 199
Cells(st + 10, 2).Value = stars(st)(h, 1)
Cells(st + 10, 3).Value = stars(st)(h, 2)

Next

'calls chart to update
'Application.ScreenUpdating = True
DoEvents

Next

Cheers

Upvotes: 3

Views: 438

Answers (1)

dwn
dwn

Reputation: 563

If you want to wrap around, you can just use 'mod', as in 'index mod size'

[ADDENDUM - FreeBasic example]

const aSize=5
const bSize=3
dim a(0 to aSize-1) as integer
dim b(0 to bSize-1) as integer

a(0)=0
a(1)=1
a(2)=2
a(3)=3
a(4)=4

b(0)=0
b(1)=10
b(2)=20

for i=0 to 20
  print "[";a(i mod aSize);" ";b(i mod bSize);"]"
next

sleep

Upvotes: 4

Related Questions