Spiral matrix: Difference between revisions
m
→{{header|R}}: Syntax highlighting.
(Added solution for Action!) |
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax highlighting.) |
||
Line 4,120:
=={{header|R}}==
===Sequence Solution===
<lang
stopifnot(is.numeric(n))
stopifnot(n > 0)
Line 4,132:
}</lang>
{{out}}
<lang
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
Line 4,149:
===Recursive Solution===
<lang
spiralv <- function(v) {
n <- sqrt(length(v))
Line 4,167:
===Iterative Solution===
Not the most elegant, but certainly distinct from the other R solutions. The key is the observation that we need to produce n elements from left to right, then n-1 elements down, then n-1 left, then n-2 right, then n-2 down, ... . This gives us two patterns. One in the direction that we need to write and another in the number of elements to write. After this, all that is left is battling R's indexing system.
<lang
{
spiral<-matrix(0,nrow=n,ncol=n)
|