How to pixel averaging in one nested for loop?

Let's image there's a 3x3 array. I want each element in the array be the average of it's neighbor. How to do it with just ONE nested for loop.

1
2
3
4
5
6
7
8
int[][] arr = new int[3][3];
// suppose I already initialized each element from 1 to 9 and made a copy of the array call cpyarr. 

for (int i = 0; i < 3; i++){
   for (int j = 0; j < 3; j++){
       int a = cpyarr[i-1][j-1] + cpyarr[i][j-1] + cpyarr[i+1][j-1] +...+cpyarr[i+1][j+1];
       arr[i][j] = a;}}
 


This code is going to cause error because it will go out of bound for cases near the boundary and corner. I know how to solve the problem but I don't know how to solve the problem with ONE nested for loop.
Last edited on
The line 6 could contain an elaborate if statement.
I know how to solve the problem but I don't know how to solve the problem with ONE nested for loop.


One nested for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

const unsigned dim = 3;
typedef int array_type [dim][dim];

void average(array_type& dest, const array_type& src)
{
    // corners:
    dest[  0  ][  0  ] = (src[  0  ][  0  ] + src[  0  ][  1  ] + src[  1  ][  0  ] + src[  1  ][  1  ]) / 4;
    dest[dim-1][  0  ] = (src[dim-1][  0  ] + src[dim-2][  0  ] + src[dim-1][  1  ] + src[dim-2][  1  ]) / 4;
    dest[  0  ][dim-1] = (src[  0  ][dim-1] + src[  1  ][dim-1] + src[  0  ][dim-2] + src[  1  ][dim-2]) / 4;
    dest[dim-1][dim-1] = (src[dim-1][dim-1] + src[dim-2][dim-1] + src[dim-1][dim-2] + src[dim-2][dim-2]) / 4;

    // top, bottom, and sides:
    for (unsigned i = 1; i < dim - 1; ++i)
    {
        const unsigned j = dim - 1;

        dest[0][i] = (src[0][i-1] + src[0][i] + src[0][i+1] + src[ 1 ][i-1] + src[ 1 ][i] + src[ 1 ][i+1]) / 6;
        dest[j][i] = (src[j][i-1] + src[j][i] + src[j][i+1] + src[j-1][i-1] + src[j-1][i] + src[j-1][i+1]) / 6;

        dest[i][0] = (src[i-1][0] + src[i][0] + src[i+1][0] + src[i-1][ 1 ] + src[i][ 1 ] + src[i+1][ 1 ]) / 6;
        dest[i][j] = (src[i-1][j] + src[i][j] + src[i+1][j] + src[i-1][j-1] + src[i][j-1] + src[i+1][j-1]) / 6;
    }

    // middle:
    for (unsigned i = 1; i < dim - 1; ++i)
    {
        for (unsigned j = 1; j < dim - 1; ++j)    // <- single nested for loop
        {
            dest[i][j] = (src[i-1][j-1] + src[i-1][j] + src[i-1][j+1] +
                          src[ i ][j-1] + src[ i ][j] + src[ i ][j+1] +
                          src[i+1][j-1] + src[i+1][j] + src[i+1][j+1]) / 9 ;
        }
    }
}

http://ideone.com/HPqtBf

=P
Topic archived. No new replies allowed.