Definitely not as efficient as iterating through each index once and deciding on a 1 or a 0 arithmetically, but I wanted to try solving this one in a different way to see how it worked out. I'd probably go back and refactor this a bit, given the choice, but it seems to work well enough.
If we had a way of initializing the array values at 0, this method could actually be more efficient, as it wouldn't necessitate visiting every single index, just those touched by the spiral.
C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
intmain(intargc,char**argv){intsize=atoi(argv[1]);if(argc!=2||size<5){printf("Usage: ./make-a-spiral.c int\n");return1;}intresult[size][size];intx=0,y=0,dir=1,horizontal=1,boundary_x=0,boundary_y=0,turns=0;// Iterate through our result array and set the default to 0,// as otherwise we will end up with garbage values polluting the result.for(inti=0;i<size;i++){for(intj=0;j<size;j++){result[i][j]=0;}}// Change our x and y location as is appropriate, and check when we // need to turn.while(turns<size){result[y][x]=1;if(y==0+boundary_y&&!horizontal&&dir==-1){horizontal=1;dir*=-1;turns++;}elseif(y==size-boundary_y-1&&!horizontal&&dir==1){horizontal=1;boundary_y+=2;dir*=-1;turns++;}elseif(x==size-boundary_x-1&&horizontal&&dir==1){horizontal=0;turns++;}elseif(y!=0&&x==0+boundary_x&&horizontal&&dir==-1){horizontal=0;boundary_x+=2;turns++;}// Handle movementif(horizontal){x+=dir;}else{y+=dir;}}// Iterate through once more to print the resulting spiral.for(inti=0;i<size;i++){for(intj=0;j<size;j++){printf("%c",result[i][j]?'0':'.');}printf("\n");}return0;}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Definitely not as efficient as iterating through each index once and deciding on a 1 or a 0 arithmetically, but I wanted to try solving this one in a different way to see how it worked out. I'd probably go back and refactor this a bit, given the choice, but it seems to work well enough.
If we had a way of initializing the array values at 0, this method could actually be more efficient, as it wouldn't necessitate visiting every single index, just those touched by the spiral.
C