我有一个稀疏数组,例如:
rare = [[0,1], [2,3], [4,5], [7,8]]我想用这些数据绘制一张图表,每一对都是点坐标。如你所见,我没有针对x=1,x=3,x=5,x=6的积分
我想用前面的值填充数组,因此对于上面的示例,我将获得:
filled = [[0,1], [1,1], [2,3], [3,3], [4,5], [5,5], [6,5], [7,8]正如您所看到的,为了计算y值,我只取我使用的最后一个y值。
实现这一目标的最佳方法是什么?
发布于 2010-09-17 22:42:42
Range.new(*rare.transpose.first.sort.values_at(0,-1)).inject([]){|a,i|
a<<[i, Hash[rare][i] || a.last.last]
}分步说明:
rare.transpose.first.sort.values_at(0,-1)从输入数组中找到最小和最大数组( example)Range.new()中的数组生成一个范围,(0..7)inject遍历该范围,并为每个输入数组返回对not,其中y是:[0,7] from x [x,y],其中y来自先前计算的对,其中not
注意:以下是求取最小x和最大x的其他方法:
[:min,:max].map{|m| Hash[rare].keys.send m}
rare.map{|el| el.first}.minmax # Ruby 1.9, by steenslag发布于 2010-09-17 22:12:16
rare = [[0,1], [2,3], [4,5], [7,8]]
filled = rare.inject([]) do |filled, point|
extras = if filled.empty?
[]
else
(filled.last[0] + 1 ... point[0]).collect do |x|
[x, filled.last[1]]
end
end
filled + extras + [point]
end
p filled
# => [[0, 1], [1, 1], [2, 3], [3, 3], [4, 5], [5, 5], [6, 5], [7, 8]]发布于 2010-09-17 22:17:10
inject解决方案:
filled = rare.inject([]) do |filled_acc, (pair_x, pair_y)|
padded_pairs = unless filled_acc.empty?
last_x, last_y = filled_acc.last
(last_x+1...pair_x).map { |x| [x, last_y] }
end || []
filled_acc + padded_pairs + [[pair_x, pair_y]]
end更多关于Enumerable#inject和使用Ruby here进行函数式编程的信息。
https://stackoverflow.com/questions/3735967
复制相似问题