我有一个类似于此的数组:
array = [["2","3","5","5"],["8","7","5","0"],["1","3","7","8"]]
索引和子索引应该类似于(y,x)格式的坐标,即第一个值" 2"有坐标(0,0),分别是第一个" 8"应该有坐标(1,0)。我试图将此输入到一个新的数组中,该数组的坐标后跟值,即对新数组的第一个输入将是0,0," 2"。我该怎么办呢?非常感谢!
答案 0 :(得分:4)
这样的事情会有用吗?
result = []
array.each_with_index do |subarray, x|
subarray.each_with_index do |elem, y|
result << [x, y, elem]
end
end
irb(main):043:0> result
=> [[0, 0, "2"], [0, 1, "3"], [0, 2, "5"], [0, 3, "5"], [1, 0, "8"], [1, 1, "7"], [1, 2, "5"], [1, 3, "0"], [2, 0, "1"], [2, 1, "3"], [2, 2, "7"], [2, 3, "8"]]
答案 1 :(得分:3)
array.map(&:each_with_index)
.flat_map.with_index { |e, i| e.map { |e, j| [i, j, e] } }
答案 2 :(得分:2)
以下是一些紧凑的方法。我假设,在示例中,作为array
元素的数组都具有相同的大小。
转换为矩阵以使用Matrix方法
require 'matrix'
Matrix[*array].each_with_index.map { |n,i,j| [i,j,n] }
#=> [[0, 0, "2"], [0, 1, "3"], [0, 2, "5"], [0, 3, "5"],
# [1, 0, "8"], [1, 1, "7"], [1, 2, "5"], [1, 3, "0"],
# [2, 0, "1"], [2, 1, "3"], [2, 2, "7"], [2, 3, "8"]]
如果偏移的顺序不重要,可以简化为以下内容。
Matrix[*array].each_with_index.to_a
#=> [["2", 0, 0], ["3", 0, 1], ["5", 0, 2], ["5", 0, 3],
# ["8", 1, 0], ["7", 1, 1], ["5", 1, 2], ["0", 1, 3],
# ["1", 2, 0], ["3", 2, 1], ["7", 2, 2], ["8", 2, 3]]
展平并制作地图
ncols = array.first.size
array.flatten.map.with_index { |n,i| [*i.divmod(ncols), n] }
#=> [[0, 0, "2"], [0, 1, "3"], [0, 2, "5"], [0, 3, "5"],
# [1, 0, "8"], [1, 1, "7"], [1, 2, "5"], [1, 3, "0"],
# [2, 0, "1"], [2, 1, "3"], [2, 2, "7"], [2, 3, "8"]]