# Manipulating array of arrays...

• March 1st, 2013, 12:49 PM
choloboy
Manipulating array of arrays...
I am trying to work with this a two dimensional array, that represents greyscale of an image... I want to pixelate the image by averaging 2x2 blocks and replacing each value by the average of the 2x2 grid... for example, if the input is the array

Code :

``` 2, 4, 31, 31 3, 3, 21, 41 1, 2, 10, 20 3, 2, 20, 30```
then you start by looking at the first 2x2 sub-array (from the top-left)

Code :

``` 2, 4 3, 3```
and find the average of this sub-array (which is (2+4+3+3)/4 = 3). In the returned array, the first 2x2 sub-array will then be

Code :

``` 3, 3 3, 3```
We then look at the next 2x2 block

Code :

``` 31, 31 21, 41```
with average 31, The next 2x2 block in the output will be

Code :

``` 31, 31 31, 31```
I am wondering what approach would best solve this problem. Not too sure how to solve it... Thanks in advance
• March 1st, 2013, 12:59 PM
Norm
Re: Manipulating array of arrays...
Try nested loops and walk through the dimensions by 2 vs by 1
• March 1st, 2013, 01:19 PM
choloboy
Re: Manipulating array of arrays...
but how do i make a loop to go through 2x2 portions of my array of array?
• March 1st, 2013, 01:19 PM
Zaphod_b
Re: Manipulating array of arrays...
Quote:

Originally Posted by choloboy
... what approach would best...

I wouldn't worry about finding the "best" approach. Just think about an approach.

For example:
Code :

```Suppose you have a two-dimension array of ints named pixelArray.   Declare an int named numRows and set it equal to pixelArray.length; Declare an int named numCols and set it equal to pixelArray[0].length;   First of all make sure that numRows and numCols are both even numbers. (Use numRows%2 and numCols%2 to determine that.)```

Then make nested loops that go through the rows and columns of pixelArray two at a time:

Code :

``` for (int i = 0; i < numRows; /* What goes here to make it step through the rows two at a time? */) { for (int j = 0; j < numCols; /* What goes here to make it step through the columns two at a time? */) { // // Do the Good Stuff here // } }```

Now, what is the Good Stuff?

Code :

```Declare an int variable named sum, or some such thing.   In the innermost loop, calculate it by adding the values of the elements of the 2x2 sub array: pixelArray[i][j] + pixelArray[i][j+1] + pixelArray[i+1][j] + pixelArray[i+1][j+1]   Declare an int variable named avg or some such thing Set the value of avg equal to Math.round(sum/4.0f) to get the int value closest to the average value of the four pixels.   Copy this average value back into the pixelArray elements that were used to calculate the sum.```

Cheers!

Z