Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
46
Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffee
Normal file
46
Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffee
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# Let's say you want to arrange the first N-squared natural numbers
|
||||
# in a spiral, where you fill in the numbers clockwise, starting from
|
||||
# the upper left corner. This code computes the values for each x/y
|
||||
# coordinate of the square. (Of course, you could precompute the values
|
||||
# iteratively, but what fun is that?)
|
||||
|
||||
spiral_value = (x, y, n) ->
|
||||
prior_legs =
|
||||
N: 0
|
||||
E: 1
|
||||
S: 2
|
||||
W: 3
|
||||
|
||||
edge_run = (edge_offset) ->
|
||||
N: -> edge_offset.W - edge_offset.N
|
||||
E: -> edge_offset.N - edge_offset.E
|
||||
S: -> edge_offset.E - edge_offset.S
|
||||
W: -> edge_offset.S - edge_offset.W
|
||||
|
||||
edge_offset =
|
||||
N: y
|
||||
E: n - 1 - x
|
||||
S: n - 1 - y
|
||||
W: x
|
||||
|
||||
min_edge_offset = n
|
||||
for dir of edge_offset
|
||||
if edge_offset[dir] < min_edge_offset
|
||||
min_edge_offset = edge_offset[dir]
|
||||
border = dir
|
||||
|
||||
inner_square_edge = n - 2 * min_edge_offset
|
||||
corner_offset = n * n - inner_square_edge * inner_square_edge
|
||||
corner_offset += prior_legs[border] * (inner_square_edge - 1)
|
||||
corner_offset + edge_run(edge_offset)[border]()
|
||||
|
||||
spiral_matrix = (n) ->
|
||||
# return a nested array expression
|
||||
for y in [0...n]
|
||||
for x in [0...n]
|
||||
spiral_value x, y, n
|
||||
|
||||
do ->
|
||||
for n in [6, 7]
|
||||
console.log "\n----Spiral n=#{n}"
|
||||
console.log spiral_matrix n
|
||||
18
Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffee
Normal file
18
Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffee
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
> coffee spiral.coffee
|
||||
|
||||
----Spiral n=6
|
||||
[ [ 0, 1, 2, 3, 4, 5 ],
|
||||
[ 19, 20, 21, 22, 23, 6 ],
|
||||
[ 18, 31, 32, 33, 24, 7 ],
|
||||
[ 17, 30, 35, 34, 25, 8 ],
|
||||
[ 16, 29, 28, 27, 26, 9 ],
|
||||
[ 15, 14, 13, 12, 11, 10 ] ]
|
||||
|
||||
----Spiral n=7
|
||||
[ [ 0, 1, 2, 3, 4, 5, 6 ],
|
||||
[ 23, 24, 25, 26, 27, 28, 7 ],
|
||||
[ 22, 39, 40, 41, 42, 29, 8 ],
|
||||
[ 21, 38, 47, 48, 43, 30, 9 ],
|
||||
[ 20, 37, 46, 45, 44, 31, 10 ],
|
||||
[ 19, 36, 35, 34, 33, 32, 11 ],
|
||||
[ 18, 17, 16, 15, 14, 13, 12 ] ]
|
||||
Loading…
Add table
Add a link
Reference in a new issue