循环以螺旋外而内螺旋

2023-09-11 04:43:26 作者:继续 半吊z1°

我在找遍历类似于一个矩阵来循环的螺旋但循环代替内向外外到内,。谁能帮我配个好办法做到这一点的任何大小的矩阵,最好是在红宝石?

例: 在一个3×4矩阵我要开始在[0,0]在朝好的方向发展,然后向下移动一次,我到达[3,0],向左移动为[3,2]等。

  [0,0] [1,0] [2,0] [3,0]
[0,1] [1,1] [2,1] [3,1]
[0,2] [1,2] [2,2] [3,2]
 

顺序动作如下:

  0 2 1 3
9 10 11 4
8 7 6 5
 

和输出是:

 [0,0],[1,0],[2,0],[3,0],[3,1],[3,2],[2 ,2],[1,2],[0,2],[0,1],[1,1],[2,1]
 
何为滑动螺旋传动

解决方案

不失一般性,让我们写的数组:

  ARR = [
  [1,2,3,4,]
  [12,13,14,5,]
  [11,16,15,6,]
  [10,9,8,7,]
]
 

期望的结果是:

  [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 

我会用一个助手:

 高清旋转(ARR)
  arr.map(安培;:反转).transpose
结束
 

例如:

 旋转(ARR)
  #=> [[4,5,6,7],[3,14,15,8],[2,13,16,10],[1,12,11,10]]
 

我们现在可以计算所需的结果如下:

  OUT = []
A = arr.map(安培;:DUP)
而a.any?
  out.concat(a.shift)
  一个=旋转(一)
结束
出
  #=> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 

I'm looking to loop through a matrix similar to Looping in a spiral but looping outside-in, instead of inside-out. Can anyone help me with a good way to do this for a matrix of any size, ideally in Ruby?

Example: In a 3x4 matrix I want to start at [0,0] going right, then move down once I reach [3,0], move left at [3,2] etc.

[0,0] [1,0] [2,0] [3,0]
[0,1] [1,1] [2,1] [3,1]
[0,2] [1,2] [2,2] [3,2]

The order to move is shown below:

0  1  2  3
9  10 11 4
8  7  6  5

And the output would be:

[0,0], [1,0], [2,0], [3,0], [3,1], [3,2], [2,2], [1,2], [0,2], [0,1], [1,1], [2,1]

解决方案

Without loss of generality, let's write the array as:

arr = [
  [ 1, 2, 3, 4,],
  [12,13,14, 5,],
  [11,16,15, 6,],
  [10, 9, 8, 7,]
]

The desired result is:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

I will use a helper:

def rotate(arr)
  arr.map(&:reverse).transpose
end

For example:

rotate(arr)
  #=> [[4, 5, 6, 7], [3, 14, 15, 8], [2, 13, 16, 9], [1, 12, 11, 10]] 

We can now compute the desired result as follows:

out = []
a = arr.map(&:dup)
while a.any?
  out.concat(a.shift)
  a = rotate(a)
end
out
  # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]