ruby - 根据矩阵形状进行坐标转换

标签 ruby arrays math matrix coordinates

我想将扁平数组中的索引转换为多维数组中的坐标。

示例: 下面的二维数组,其大小为[3, 3]:

[
  [ -, -, - ],
  [ *, -, - ],
  [ -, -, - ]
]

*的坐标是[0, 1]。如果我们将这个数组展平为:

[ -, -, -, *, -, -, -, -, - ]

* 的坐标(或索引)变为 3。我们怎样才能做相反的事情呢?也就是说,这样的方法:

index_to_coordinates([3, 3], 3)  # => [0, 1]

最佳答案

请注意,您的 index_to_coordinates 采用 [3, 3] (除了扁平索引 3)作为参数,但那是多余的。您需要的信息是矩阵中每行的长度为 3,并且展平索引为 3

3.divmod(3).reverse # => [0, 1]

divmod 为您提供一对商和余数。由于您期望的顺序是:x 坐标(余数)然后 y 坐标(商),因此您需要 reverse 来翻转顺序。

根据问题的变化进行编辑

注意:下面我假设 ruby​​ 1.9。我不想打扰 ruby​​ 1.8。如有需要请自行翻译为ruby 1.8。这应该很容易。

假设你有一个结构:

[
  [
    [0, 1, 2, 3]
    [4, 5, 6, 7]
    [8, 9, 10, 11]
  ]
  [
    [12, 13, 14, 15]
    [16, 17, 18, 19]
    [20, 21, 22, 23]
  ]
]

使得这个结构体的大小表示为[2,3,4]。一般来说,我们可以将大小表示为数组sizes。您可以将其转换为一个数组flattened,该数组表示当整个结构展平到该维度时每个维度的大小:

flattened = sizes.dup.drop(1)
(1...flattened.length).reverse_each{|i| flattened[i-1] *= flattened[i]}

具体示例:

flattened # => [12, 4]

这意味着最大的循环是12,下一个是4。假设你想要7的坐标。为了实现这一点,您需要:

index = 7
coordinate = flattened.each_with_object([]) do |size, array|
  quotient, index = index.divmod(size)
  array.push(quotient)
end
coordinate.push(index)

这会给你:

coordinate # => [0, 1, 3]

关于ruby - 根据矩阵形状进行坐标转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930662/

相关文章:

ruby - 使用 ruby​​ 进行网页抓取

ruby - HAML - if/elsif 结构

ruby-on-rails - 将 Ruby 时间戳转换为 Epoch 中的秒数并返回

java - 如何标记输出并去除零?

java - 数学解析器 - 标记结构

ruby-on-rails - EC2中Mongo::OperationFailure反复出现,怎么办?

javascript - 在 JavaScript 函数中获取 Json 数组值

javascript - js中将Array转为Jsondata对象的对象

c++ - 音频处理 C++ - FFT

c++ - 4x4矩阵预乘和后乘