1

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.

6
  • 2
    1) C or C++ 2) Homework? Commented Oct 31, 2017 at 20:31
  • C. Sort of homework, yes Commented Oct 31, 2017 at 20:32
  • 3
    min(i,j,n-i,n-j)+1 !!! Commented Oct 31, 2017 at 20:32
  • exercise not clear. Does the matrix has to be filled out with no defined rules (according to "didn't say what the rules were") but the matrix should look exactly like the one you show in your snippet? Commented Oct 31, 2017 at 20:36
  • It looks like the number is the minimum distance to an edge. Commented Oct 31, 2017 at 20:41

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.