arrays - 在数组内移动数组元素

标签 arrays julia

像这样将元素移动到数组内的新索引的有效方法是什么?

A = collect(1:9)  # [1,2,3,4,5,6,7,8,9]

# now lets move elements 1:3 to index 2 
move!(A,1:3,2)    # [4,1,2,3,5,6,7,8,9]

# lets move the 9 to index 3 now
move!(A,9:9,3)    # [4,1,9,2,3,5,6,7,8]

# or this
move!(A,3:6,5)    # [4,1,6,7,9,2,3,5,8]

我总是最终调整数组的大小或像疯了一样交换。有没有一种有效(=快速)的方法来解决这个问题?

最佳答案

将数组中的一系列元素移动到新位置可以视为旋转更大的范围,其中包括一条边上的移动元素和目标位置。旋转刚好足以使移动的元素定位并将其他元素推开。

由于向量的长度保持不变,最好在没有分配的情况下就地执行此操作。就地进行这种旋转有点棘手,但可行,如下面的代码所示:

function rotate!(v,n::Int)
  l = length(v)
  l>1 || return v
  n = n % l
  n = n < 0 ? n+l : n
  n==0 && return v
  for i=1:gcd(n,l)
    tmp = v[i]
    dst = i
    src = dst+n
    while src != i
      v[dst] = v[src]
      dst = src
      src += n
      if src > l
        src -= l
      end
    end
    v[dst] = tmp
  end
  return v
end

move!(A,rng,loc) = begin 
  rotate!(view(A,min(first(rng),loc):max(last(rng),length(rng)+loc-1)),first(rng)-loc)
  return A
end

A = collect(1:9)
@show move!(A,1:3,2) == [4,1,2,3,5,6,7,8,9]
@show move!(A,9:9,3) == [4,1,9,2,3,5,6,7,8]
@show move!(A,3:6,5) == [4,1,6,7,9,2,3,5,8]

最后几行代码复制了问题中的示例。本质上,只有 view分配内存和 rotate!功能完全到位。

关于arrays - 在数组内移动数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42856351/

相关文章:

Javascript - 返回对象对象的reduce方法

javascript将关联数组推送到另一个中

floating-point - 从 Julia 中的像素检索 RGB 矢量

package - 如何在 Julia 中找到我的软件包版本?

arrays - 用于沿大矩阵对角线插入 2x2 矩阵的代码的向量化

c - 如何在以下函数内传递十六进制数据

julia - 导入具有不同名称的 Julia 模块

c++ - OpenCL 内核 _local 内存行为不正确

php - 将 xml 对象插入数组

c - Julia 中的装箱/拆箱复杂类型