Created
September 30, 2016 23:25
-
-
Save spot62/6c0038f66fff6f6a7886de8c05b2b3c2 to your computer and use it in GitHub Desktop.
Fill an array of spiral
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main (int argc, char *argv[]) | |
{ | |
int i; | |
int j; | |
int n=2; | |
int size = 2*n+1; | |
int (*data)[size] = malloc(sizeof(int[size][size])); | |
memset(data, 0, sizeof(int[size][size])); | |
int num = 0; | |
i = j = n; | |
for (int offset=1; offset<=size; offset++) | |
{ | |
int sign = (offset % 2)?-1:1; | |
for(int di=1; di<= offset; di++) | |
{ | |
i += sign; | |
if(i<0) | |
goto exit_; | |
data[i][j] = ++num; | |
printf ("data[%i,%i]=%i\n", i, j, num); | |
} | |
for(int dj=1; dj<= offset; dj++) | |
{ | |
j += sign; | |
if(j<0) | |
goto exit_; | |
data[i][j] = ++num; | |
printf ("data[%i,%i]=%i\n", i, j, num); | |
} | |
} | |
exit_: | |
; | |
for(i=0;i<size;i++) | |
{ | |
for(j=0;j<size;j++) | |
printf("%3i ", data[i][j]); | |
printf("\n"); | |
} | |
free(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment