Velocity Reviews > Java > How to create a spiral matrix?

# How to create a spiral matrix?

indian_gaurav
Guest
Posts: n/a

 09-02-2008
Let A be an array of (n) elements. Write a procedure which will také
this array as input and return a matrix which will be spiral in
nature. i.e.

if A= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] then

fn(A)= B

=

7 8 9 10

6 1 2 11

5 4 3 12

16 15 14 13

although i could easily handle the problem for a 2 dimension matrix
the problem has to be solved in 3 dimension as well as n dimension.

i'm finding it difficult to visualize the same problem for 3 dimension
and then for n dimension.
can som1 help me?

thank u
Gaurav

Plz write to http://www.velocityreviews.com/forums/(E-Mail Removed)

Roedy Green
Guest
Posts: n/a

 09-06-2008
On Tue, 2 Sep 2008 11:39:54 -0700 (PDT), indian_gaurav
<(E-Mail Removed)> wrote, quoted or indirectly quoted
someone who said :

>7 8 9 10
>
>6 1 2 11
>
>5 4 3 12
>
>16 15 14 13

So how did you create that? You first decided how many rows/columns
you need. You can do that with sqrt and rounding up. See
http://mindprod.com/jgloss/round.html

Then you had to find the center of the matrix. That is matter of
dividing the size by 2 with possibly a one off adjust.

Then you have a loop that spirals outward. It starts in the bottom
left corner and spiral clockwise

you spiral out 0, 1, 2 , 3 etc rows. So compute the co-ordinates of
the bottom right corner of the next layer. Now plop down the numbers
for the left, top, right and bottom sides, incrementing your number by
one each time. you continue with the loop for the next layer out.
--

The Java Glossary
http://mindprod.com

Roedy Green
Guest
Posts: n/a

 09-06-2008
On Tue, 2 Sep 2008 11:39:54 -0700 (PDT), indian_gaurav
<(E-Mail Removed)> wrote, quoted or indirectly quoted
someone who said :

>
>i'm finding it difficult to visualize the same problem for 3 dimension
>and then for n dimension.

You probably can't. But what you can do is see the obvious
generalisation of the structure of your code. however, you will need
the code under your nose first to do that.

--

The Java Glossary
http://mindprod.com