# How would I iterate through an array 'in chunks'?

• April 11th, 2013, 02:22 PM
vividMario52
How would I iterate through an array 'in chunks'?
Hello all, I've been working on tile generation for my game, and it uses 2d arrays. I was trying to think of some way to do biome/chunk generation, and I thought that looping through an array in chunks instead of looping straight through it. If you don't understand, here is what I am trying to do:

Code :

```for(int t = 0; t < World.MAP_WIDTH; t += 36) { for (int x = 0 + t; x < 36 + t; x++) { for (int y = 0 + t; y < 36 + t; y++) { genTiles(x, y, w, 1); } } }```

What I thought it would do is for the first loop (when t is 0) genTiles() from x 0 y 0 to x 35 y 35. Then get shifted over when that was done, so it started at x 36 y 36, ended at x 71 y 71. But I realized it skipped a few 'chunks'. Is it possible to iterate over an array in chunks but still counting every slot in the array?
Thanks.
• April 11th, 2013, 02:38 PM
Norm
Re: How would I iterate through an array 'in chunks'?
Quote:

Is it possible to iterate over an array in chunks but still counting every slot in the array?
Are you asking if you can iterate through a loop using an increment value other than 1 for the control variable?
Yes. It will be easier if the increment value doesn't change too often.
• April 11th, 2013, 04:21 PM
pbrockway2
Re: How would I iterate through an array 'in chunks'?
I *think* what you are trying to do is iterate over an array by considering that array to be made up of smaller subarrays. (Correct me if I've got it skipped a few 'chunks' wrong). Consider:

Code :

```aaabbbcccddd aaabbbcccddd eeefffggghhh eeefffggghhh iiijjjkkklll iiijjjkkklll```

It's an array 12 wide and 6 tall, but can be considered as an array of chunks 4 wide and 3 tall where each chunk is also an array (3 wide and 2 tall). You can iterate over each of the large array elements with:

Code :

```int width = 4; // number of chunks across int height = 3 // number of chunks tall int chW = 3; // width of a chunk int chH = 2; // height of a chink for(int chunkX = 0; chunkX < width; ++chunkX) { for(int chunkY = 0; chunkY < height; ++chunkY) { for(int x = 0; x < chW; ++x) { for(int y = 0; y < chH; ++y) { System.out.printf( "At (%d,%d) within the chunk at (%d,%d)", x, y, chunkX, chunkY); doSomething(chunkX * width + x, chunkY * height + y); } } } }```

(My preference is to make the loop variables "simple" and do the calculation of overall "coordinates" with the loop body. I guess initialising the loops with a more complex expression might be more efficient.)

The four for loops are a bit ungainly. If the chunks have some significance within your program, consider making a class to represent them. A class which has, as behaviour, the things that chunks can do. The array then presents itself in a straightforward way as a 2D array of chunks.