簡體   English   中英

在數組中找到最接近給定值的數字

[英]Find closest numbers in array to given value

我正在尋找一種方法,該方法將向我返回數組中5個最接近的數字。 這是我必須開始的工作。 我想比較差異,但是我覺得必須有一種更簡單的方法。

def get_suggested_items
    @suggested_items = []
    new_price = self.price
    products = Product.all
    products.each do |product, difference|
        price = product.price
        old_difference = new_price - product.price
        difference = (new_price - product.price).abs
        while difference < old_difference 
            @suggested_items << product
        end

end

我希望以價格返回最接近的5個產品的數組@suggested_items

SQL是為這種事情而設計的。 將以下類方法添加到您的Product模型中:

class Product < ActiveRecord::Base

  def self.with_price_nearest_to(price)
    order("abs(products.price - #{price})")
  end
end

然后您可以編寫:

Product.with_price_nearest_to(3.99).limit(5)

與您在問題中概述的方法相比,此方法具有明顯的性能優勢。 在這種情況下,數據庫將為您進行計算和排序,並僅將您需要的5種產品返回給ActiveRecord。 當您執行Product.all甚至是Product.each您都在迫使ActiveRecord為表中的每一行實例化一個模型,隨着表的增大,該模型會變得很昂貴。

注意,這種方法仍然需要全表掃描。 如果要進一步改善性能,可以在products表的price列中添加索引。

假設arr是一個有序的整數數組。 (如果未排序,則作為第一步進行排序。)我假設您想從數組a = arr[i,5]找到五個元素的序列,這樣a.last-a.first對於全部i0 <= i <= arr.size-4 如果是正確的話,那就很簡單:

start_index = (arr.size-4).times.min_by { |i| arr[i+4]-arr[i] }

假設

arr = [1, 2, 4, 5, 8, 9, 11, 12, 13, 15, 17, 19, 23, 24, 24, 25, 30]
start_index = (arr.size-4).times.min_by { |i| arr[i+4]-arr[i] }
  #=> 4

因此,“最接近的”五個數字將是:

arr[4,5]
  #=> [8, 9, 11, 12, 13]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM