Solomon Zestra
Solomon Zestra

Reputation: 31

Algorithm to fill 2D array in C

and sorry for the noob question.

So I've been asked to create an algorithm to fill a 2D array. They didn't say what the rules were, however, I've been told that the resulting matrix should look like this:

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

I haven't been told if the matrix is necessarily square, but the size may vary. So substantially what I'm seeing is the matrix is vertically, horizontally and diagonally symmetrical. Now whatever I try, it ends up being super complicated, while as I look at it, I feel like it should be pretty simple...

Any trick or snippet on how you'd do it? Thanks in advance.

Upvotes: 1

Views: 1110

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

You need 2 nested loops, to traverse through rows and columns. The content of the field is the minimum of the control variables and and the minimum of the difference of a control variable and the size of the array dimension, incremented by 1.

N = 5

0: min(0, N-0-1) + 1 = 1
1: min(1, N-1-1) + 1 = 2
2: min(2, N-2-1) + 1 = 3
3: min(3, N-3-1) + 1 = 2
4: min(4, N-4-1) + 1 = 1

#include <stdio.h>

#define N 5

#define MIN(a,b) (((a)<(b))?(a):(b))

int main()
{
    int a[N][N];
    for ( int i = 0; i < N; ++ i )
    {
        for ( int j = 0; j < N; ++ j)
        {
            int minI = MIN(i, N-i-1);
            int minJ = MIN(j, N-j-1);
            a[i][j] = MIN(minI, minJ) + 1; 
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output:

1 1 1 1 1 
1 2 2 2 1 
1 2 3 2 1 
1 2 2 2 1 
1 1 1 1 1

See the live example

Upvotes: 2

Related Questions