Spiral matrix: Difference between revisions
Content added Content deleted
No edit summary |
(Add Factor example) |
||
Line 1,441: | Line 1,441: | ||
{12,11,10,9,8} |
{12,11,10,9,8} |
||
} |
} |
||
=={{header|Factor}}== |
|||
This is an implementation of Joey Tuttle's method for computing a spiral directly as a list and then reshaping it into a matrix, as described in the [http://rosettacode.org/wiki/Spiral_matrix#J J entry]. To summarize, we construct a list with <code>n*n</code> elements by following some simple rules, then take its cumulative sum, and finally its inverse permutation (or rank in J parlance). This gives us a list which can be reshaped to the final matrix. |
|||
<lang factor>USING: arrays grouping io kernel math math.combinatorics |
|||
math.ranges math.statistics prettyprint sequences |
|||
sequences.repeating ; |
|||
IN: rosetta-code.spiral-matrix |
|||
: counts ( n -- seq ) |
|||
[1,b] reverse 2 repeat rest ; |
|||
: vals ( n -- seq ) |
|||
[ 1 swap 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ; |
|||
: evJKT2 ( n -- seq ) |
|||
[ counts ] [ vals ] bi [ <array> ] 2map concat ; |
|||
: spiral ( n -- matrix ) |
|||
[ evJKT2 cum-sum inverse-permutation ] [ group ] bi ; |
|||
: spiral-demo ( -- ) |
|||
5 9 [ spiral simple-table. nl ] bi@ ; |
|||
MAIN: spiral-demo</lang> |
|||
{{out}} |
|||
<pre> |
|||
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 |
|||
0 1 2 3 4 5 6 7 8 |
|||
31 32 33 34 35 36 37 38 9 |
|||
30 55 56 57 58 59 60 39 10 |
|||
29 54 71 72 73 74 61 40 11 |
|||
28 53 70 79 80 75 62 41 12 |
|||
27 52 69 78 77 76 63 42 13 |
|||
26 51 68 67 66 65 64 43 14 |
|||
25 50 49 48 47 46 45 44 15 |
|||
24 23 22 21 20 19 18 17 16 |
|||
</pre> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |