[ create a new paste ] login | about

Link: http://codepad.org/2PGoABh0    [ raw code | output | fork ]

novatech - C++, pasted on Jan 15:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

int i=0,x,y,spiral[100][100];
char direction = 'r';
void change_direction() {
     switch(direction) {
     case 'r':direction='d';break;
     case 'd':direction='l';break;
     case 'l':direction='u';break;
     case 'u':direction='r';break;
     }
}
int check_cell(int a,int b) {
 if (b >= y || b <0) { return 0; }
 else if (a >= x) { return 0; }
 else if (spiral[a][b] != 0) { return 0; }
 else { return 1; }
}
void move_cell(int &a,int &b) {
     int next_a = a, next_b = b;
     if (i == x*y-1) { return; }
     switch(direction) {
     case 'r': next_b = b + 1;break;
     case 'd': next_a = a + 1;break;
     case 'l': next_b = b - 1;break;
     case 'u': next_a = a - 1;break;
     }   
     if (check_cell(next_a,next_b)) {
         a = next_a;b = next_b;                              
     }
     else { 
          change_direction(); 
          move_cell(a,b);
          }
    return; 
}

int main() {
int j,a=0,b=0;    
srand((unsigned)time(0));
while (!x||!y) { x = rand()%10; y = rand()%10; } 
printf("%dx%d spiral number\n",x,y);
for (i = 0;i<x*y;i++) {
     spiral[a][b]=i+1;
     move_cell(a,b);
     }
for (i = 0;i < x;i++) {
         for (j = 0;j < y;j++) {
             printf("%d\t",spiral[i][j]);
         }
         printf("\n");
     }
return 0;
}


Output:
1
2
3
4
5
6
5x9 spiral number
1	2	3	4	5	6	7	8	9	
24	25	26	27	28	29	30	31	10	
23	40	41	42	43	44	45	32	11	
22	39	38	37	36	35	34	33	12	
21	20	19	18	17	16	15	14	13	


Create a new paste based on this one


Comments: