GeekInterview.com
Series: Subject: Topic:
Question: 187 of 2110

printing numbers in spiral shape

I need an algorithm for some program. I'll take some number (say 'n'), then i should print the numbers in spiral shape starting from square(n). Can any one pls help me..

Ex: if n=3, it should print like

9 8 7
2 1 6
3 4 5

Thanks in advance
Asked by: p_n_lakshmi | Member Since Apr-2008 | Asked on: Apr 30th, 2008

View all questions by p_n_lakshmi

Showing Answers 1 - 2 of 2 Answers
Gerda

Answered On : May 8th, 2008

View all answers by Gerda

One of possible solutions:public class NumberSpiralShape { /*** @param args*/public static void main(String[] args) { // TODO Auto-generated method stub int n = 3, i, side = n, x=0, y=0;int tab [][]= new int [n][n];  i=n*n;while(i>=1){for(int j=0; j<side; j++) tab[x][y++] = i--;x++;y--;if(i>=1){for(int j=0; j<side-1; j++) tab[x++][y] = i--;x--;y--;}if(i>=1){for(int j=0; j<side-1; j++) tab[x][y--] = i--;x--;y++;}if(i>=1){for(int j=0; j<side-2; j++) tab[x--][y] = i--;y++;x++;side=side-2;}}//printfor(i=0; i<n; i++){ for(int j=0; j<n; j++)System.out.print(tab[i][j] + " ");System.out.println("n"); }}} 

  
Login to rate this answer.
datdo

Answered On : Jan 29th, 2009

View all answers by datdo

//spiral//by datdo//translated C codepublic class Spiral {int n =3;public static int SPIRALHEIGHT =  n;public static int SPIRALWIDTH = n;public static main(String[] args) {    int matrix[SPIRALWIDTH][SPIRALHEIGHT];    int c,r,rr, cc;    int a = 0;    cc = 0;    rr = 0;    for(c = 0; c < SPIRALHEIGHT; c++) {        for(r = 0; r < SPIRALWIDTH; r++) {            matrix[r][c] = 0;        }    }    c =-1;    r =-2;    while(a < SPIRALWIDTH * SPIRALHEIGHT) {        for(r+=2; r < SPIRALWIDTH -rr; r++) {            matrix[r][c+1] = a;            a++;        }        for(c+=2; c < SPIRALHEIGHT - cc; c++) {            matrix[r - 1][c] = a;            a++;        }        cc++;        for(r-=2; r > rr-1 ; r--) {            matrix[r][c - 1] = a;            a++;        }        for(c-=2; c > cc-1 ; c--) {            matrix[r+1][c] = a;            a++;        }        rr++;    }    for(c = 0; c < SPIRALHEIGHT; c++) {        for(r = 0; r < SPIRALWIDTH; r++) {            System.out.print("%3d ", matrix[r][c]);        }        System.out.print("n");    }}

  
Login to rate this answer.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.