Talk:Spiral matrix: Difference between revisions

added J explanatation
(added J explanatation)
Line 2:
See [http://paddy3118.blogspot.com/2008/08/spiral.html Spiral]. --[[User:Paddy3118|Paddy3118]] 06:30, 5 August 2008 (UTC)
:At least for the iterative solution. --[[User:Paddy3118|Paddy3118]] 10:48, 5 August 2008 (UTC)
 
== J ==
The [[Spiral#J|J solution]] was:
 
<pre>
spiral =. ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)
</pre>
 
Here are some hints that will allow you to reimplement it in your language:
 
<pre>
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 =: +/\
sumscan 1 1 1 1 1
1 2 3 4 5
(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
</pre>
 
For a fuller explanation, see [http://www.jsoftware.com/papers/play132.htm the original source].
Anonymous user