简体   繁体   English

填充稀疏数组

[英]Fill sparse array

I have a sparse array, for example: 我有一个稀疏数组,例如:

rare = [[0,1], [2,3], [4,5], [7,8]]

I want to plot a chart with these data, each pair are point coordinates. 我想用这些数据绘制图表,每对都是点坐标。 As you can see I don't have points for x=1, x=3 , x=5, x=6 如您所见,我没有x = 1,x = 3,x = 5,x = 6的积分

I want to fill the array with the previous values, so for the above example I will get: 我想用以前的值填充数组,因此对于上面的示例,我将得到:

filled = [[0,1], [1,1], [2,3], [3,3], [4,5], [5,5], [6,5], [7,8]

As you can see, for calculating the y value, I simply take the last y value I used. 如您所见,为了计算y值,我只取了我使用的最后一个y值。

What is the best aproach to accomplish this ? 达到此目的的最佳方法是什么?

Range.new(*rare.transpose.first.sort.values_at(0,-1)).inject([]){|a,i|
  a<<[i, Hash[rare][i] || a.last.last]
}

Step-by-step explanation: 分步说明:

  1. rare.transpose.first.sort.values_at(0,-1) finds min and max x ( [0,7] in your example) rare.transpose.first.sort.values_at(0,-1)查找min和max x (在您的示例中为[0,7]
  2. Range.new() makes a range out of it ( 0..7 ) Range.new()使其超出范围( 0..7
  3. inject iterates through the range and for every x returns pair [x,y] , where y is: inject遍历该范围,对于每个x返回对[x,y] ,其中y为:
    1. y from input array, where defined 输入数组中的y (已定义)
    2. y from previously evaluated pair, where not y来自先前评估的对,其中不

Note: here are some other ways of finding min and max x: 注意:以下是找到最小和最大x的其他方法:

[:min,:max].map{|m| Hash[rare].keys.send m}
rare.map{|el| el.first}.minmax # Ruby 1.9, by steenslag
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]]

An inject solution: 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

More about Enumerable#inject and functional programming with Ruby here . 此处提供有关Enumerable#inject和使用Ruby进行函数式编程的更多信息。

irb(main):001:0> rare = [[0,1], [2,3], [4,5], [7,8]]
=> [[0, 1], [2, 3], [4, 5], [7, 8]]
irb(main):002:0> r=rare.transpose
=> [[0, 2, 4, 7], [1, 3, 5, 8]]
irb(main):003:0> iv = (r[0][0]..r[0][-1]).to_a.select {|w| !r[0].include?(w) }
=> [1, 3, 5, 6]
irb(main):004:0> r[1][-1]=r[1][-2]
=> 5
irb(main):005:0> p (iv.zip(r[1]) + rare).sort
[[0, 1], [1, 1], [2, 3], [3, 3], [4, 5], [5, 5], [6, 5], [7, 8]]
=> [[0, 1], [1, 1], [2, 3], [3, 3], [4, 5], [5, 5], [6, 5], [7, 8]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM