Write a program (or explain how to do it) that will display a descending "spiral" of NxN numbers, using constant space (no arrays allowed). For example, here's what the spiral looks like for N=10:
99 98 97 96 95 94 93 92 91 90
64 63 62 61 60 59 58 57 56 89
65 36 35 34 33 32 31 30 55 88
66 37 16 15 14 13 12 29 54 87
67 38 17 4 3 2 11 28 53 86
68 39 18 5 0 1 10 27 52 85
69 40 19 6 7 8 9 26 51 84
70 41 20 21 22 23 24 25 50 83
71 42 43 44 45 46 47 48 49 82
72 73 74 75 76 77 78 79 80 81
Gave the problem a shot. This is what I came up with:
#include<stdio.h>
#include<string.h>
#define N 12
void printArr(int a[N][N]){
int i,j;
for(i=0; i < N; i++){
for(j=0; j < N; j++){
printf("%d ",a[i][j]);
if(a[i][j] < 10)
printf(" ");
if(a[i][j] < 100)
printf(" ");
}
printf("\n");
}
}
main() {
int arr[N][N];
int orig[N][N];
int i,j,change,limi,limj,lim,cnt;
int not;
cnt = 0;
not = 0;
for(i=0; i < N; i++)
for(j=0; j < N; j++){
arr[i][j] = cnt++;
}
printArr(arr);
i = N/2; j = N/2-1;
if(N%2 == 1)
j++;
cnt=0;
limi=limj=lim=1;
change = -1;
while(1){
if(not == 0){
orig[i][j] = arr[cnt/N][cnt%N];
cnt++;
}
else
not = 0;
if(cnt == (N*N))
break;
if(limi != 0){
j-=change; limi--;
}
else if(limj != 0){
i+=change; limj--;
}
else{
change *= -1;
lim++;
limi=limj=lim;
not = 1;
}
}
printf("\n");
printArr(orig);
return 1;
}
Formatting works well for numbers below 1000. Once I got it working, was too lazy to do any formatting!