【问题标题】:Selecting two coordinates of minimum slope difference选择最小斜率差的两个坐标
【发布时间】:2016-07-29 04:52:06
【问题描述】:

我正在尝试制作一个可以整理的功能 最小斜率差的两个坐标。

具体来说, 输入数据是:

  1. standard_dot(一个数组) 例如[0,0]
  2. other_dots(一个由7个数组组成的数组) 例如[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8]]

函数 'calculate_min_dif' 会做接下来的事情:

  1. 计算standard_dot 与数组other_dots 中7 个点之间的斜率
  2. 选择一组斜率最接近的 2 个点
  3. 返回数组中这两个点的索引。
   def calculate_min_dif(standard_dot, other_dots)
       index = 0
       slope_list = Array.new(7)

       other_dots.each do |dot|
           slope_list[index] = (( standard_dot[1]-dot[1] ) / (standard_dot[0]-dot[0] )).abs
           index = index + 1
       end

       result = slope_list.index(slope_list.combination(2).min_by { |a,b| (a-b).abs })
       return  result
    end

编译器说问题出在第 6 行

nil can't be coerced into Fixnum
(repl):6:in `-'
(repl):6:in `block in calculate_min_dif'
(repl):6:in `combination'
(repl):6:in `each'
(repl):6:in `min_by'
(repl):6:in `calculate_min_dif'

表示-的右边,b的值为nil 我不知道为什么......

对不起,如果我太愚蠢了。我是 Ruby 和英语的新手(有点..) 谢谢

【问题讨论】:

  • 我在代码中看到的问题很少。看起来 standard_dot 不是一个数组,但是当你迭代 other_dots 时,你有 standard_dot[1] 这是不正确的。应该是standard_dot。此外,当您迭代 other_dots 时,您不必再次执行 dot[1],您可以简单地使用 dot
  • 我不明白你的问题,所以我估计至少 10% 或者读者不会明白。您能否提供导致报告异常的数据,并告诉我们哪行代码产生了异常。请通过编辑您的问题来做到这一点。
  • @PamioSolanky 其实standard_dot 也是一个数组。抱歉解释不佳。我已经编辑了我的问题。非常感谢!

标签: ruby


【解决方案1】:

你可以这样做。我会留给其他人解释为什么您会收到错误消息。

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

def slope((x,y), (bpt_x, bpt_y))
  ((y - bpt_y).to_f/(x - bpt_x)).round(5)
end

def slope_diff(pt1, pt2, base_pt)
  (slope(pt1, base_pt)-slope(pt2, base_pt)).abs
end

pts.combination(2).min_by { |pt1, pt2| slope_diff(pt1, pt2, base_pt) }
  #=> [[6, 7], [7, 8]]

让我们对照斜坡检查一下。

pts.each_with_object({}) { |pt, h| h[pt] = slope(pt, base_pt).round(5) }
  #=> {[1, 2]=>2.0, [2, 3]=>1.5, [3, 4]=>1.33333, [4, 5]=>1.25,
  #    [5, 6]=>1.2, [6, 7]=>1.16667, [7, 8]=>1.14286} 

您可以看到通过base_pt 的线以及点[6, 7][7, 8] 的斜率绝对差最小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多