Talk:Spiral matrix

From Rosetta Code

Explanation of Python code

See Spiral. --Paddy3118 06:30, 5 August 2008 (UTC)

At least for the iterative solution. --Paddy3118 10:48, 5 August 2008 (UTC)

J

The J solution was:

   spiral =. ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)

Here are some hints that will allow you to reimplement it in your language:

   counts   =:  }.@(2 # >:@i.@-)
   counts 5
5 4 4 3 3 2 2 1 1
   
   values   =:  <:@:+: $ (, -)@(1&,)
   values 5
1 5 _1 _5 1 5 _1 _5 1
   
   copy     =:  #
   3 copy 9
9 9 9
   
   (counts copy values) 5
1 1 1 1 1 5 5 5 5 _1 _1 _1 _1 _5 _5 _5 1 1 1 5 5 _1 _1 _5 1
   
   sumscan  =:  +/\       NB.  Cumulative sum
   sumscan 0 1 2 3 4
0 1 3 6 10
   
   (counts sumscan@copy values) 5
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13
   
   grade    =:  /:  NB.  Permutation which tells us how to sort
   grade 5 2 3 1 0 4
4 3 1 2 5 0
   
   (counts grade@sumscan@copy values) 5
0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8
   
   dup      =:  ,~
   dup 5
5 5
   
   reshape  =:  $   NB. Reshape an array
   3 4 reshape 'hello'
hell
ohel
lohe
   
   (dup reshape counts grade@sumscan@copy values) 5
 0  1  2  3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10  9 8

For a fuller explanation, see the original source.

Yet another J solution that looks both interesting and impenetrable to me. at least for Zig Zag a Haskel person had reimplemented the J solution and left me the clue that it involved a sort :-)
--Paddy3118 16:56, 5 August 2008 (UTC)