Spiral matrix: Difference between revisions

m
→‎{{header|R}}: Syntax highlighting.
(Added solution for Action!)
m (→‎{{header|R}}: Syntax highlighting.)
Line 4,120:
=={{header|R}}==
===Sequence Solution===
<lang Rrsplus>spiral_matrix <- function(n) {
stopifnot(is.numeric(n))
stopifnot(n > 0)
Line 4,132:
}</lang>
{{out}}
<lang Rrsplus>> spiral_matrix(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
Line 4,149:
 
===Recursive Solution===
<lang Rrsplus>spiral_matrix <- function(n) {
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 Rrsplus>spiralMatrix<-function(n)
{
spiral<-matrix(0,nrow=n,ncol=n)
331

edits