Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>max_x=5 len=max_x^2 middle=ceiling(max_x/2) A=matrix(NA,max_x,max_x) increments=Reduce( f=function(lhs,rhs) c(lhs,(-1)^(rhs/2+1)*rep(1,rhs)), x=2*(1:(max_x)), init=0 )[1:len] idx_x=Reduce( f=function(lhs,rhs) c(lhs,rep(c(TRUE,FALSE),each=rhs)), 1:max_x, init=FALSE )[1:len] increments_x=increments increments_y=increments increments_x[!idx_x]=0 increments_y[idx_x]=0 A[(middle+cumsum(increments_x)-1)*(max_x)+middle+cumsum(increments_y)]=1:(max_x^2) </code></pre> <p>Gives</p> <pre><code>#&gt; A # [,1] [,2] [,3] [,4] [,5] #[1,] 21 22 23 24 25 #[2,] 20 7 8 9 10 #[3,] 19 6 1 2 11 #[4,] 18 5 4 3 12 #[5,] 17 16 15 14 13 </code></pre> <p>Explanation: The vector <code>increments</code> denotes the steps along the path of the increasing numbers. It's either <code>0/+1/-1</code> for unchanged/increasing/decreasing row and column indices. Important here is that these numbers do not differentiate between steps along columns and rows. This is managed by the vector <code>idx_x</code> - it masks out increments that are either along a row (<code>TRUE</code>) or a column (<code>FALSE</code>). The last line takes into account R's indexing logic (matrix index increases along columns).</p> <hr> <p>Edit: As per request of the OP, here some more information about how the <code>increments</code> vector is calculated.</p> <p>You always go two consecutive straight lines of equal length (row-wise or column-wise). The length, however, increases by 1 after you have walked twice. This corresponds to the <code>x=2*(1:(max_x))</code> argument together with <code>rep(1,rhs)</code>. The first two consecutive walks are in increasing column/row direction. Then follow two in negative direction and so on (alternating). This is accounted for by <code>(-1)^(rhs/2+1)</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload