gpt4 book ai didi

ruby-on-rails - 返回集合中与给定值相比具有最高(但不更高)或相等属性值的对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:25 26 4
gpt4 key购买 nike

我有五个对象的集合。

它们有一个数字属性 day,其唯一值范围为 0-6。

如果与一个值相比,比方说 5 或 0,我如何找到具有相等属性值或集合中最高值但不超过给定值的对象?

collection.map(&:day)
=> [0, 2, 3, 4, 6]

collection 与值 5 进行比较时所需的返回值应返回具有 day 值 4 的对象。

collection 与值 0 进行比较时所需的返回值应返回具有 day 值 0 的对象。

最佳答案

让我们看看这些方法在性能上的比较。我只比较不需要对数组进行预排序的方法。我将编辑以添加建议的其他方法。

方法比较

module Methods
def awendt(collection, value)
collection_sorted_desc = collection.sort_by{|num| -num}
collection_sorted_desc.detect{|num| num <= value }
end

def awendt_rev(collection, value)
collection_sorted_desc = collection.sort.reverse
collection_sorted_desc.detect{|num| num <= value }
end

def cary1(a,v)
a.select { |e| e <= v }.max
end

def cary2(a,v)
enum = a.each
mx = - Float::INFINITY
loop do
x = enum.next
mx = x if x <= v && x > mx
end
mx
end

def cary3(a,v)
a.sort.take_while { |e| e <= v }.last
end
end

include Methods
methods = Methods.instance_methods
#=> [:awendt, :cary1, :cary2, :cary3]

测试数据

def test_data(n,m)
[[*(0..n)].shuffle, m.times.with_object([]) { |_,a| a << rand(n) }]
end

arr, cutoffs = test_data(8,3)
#=> [[1, 5, 2, 0, 3, 8, 4, 6, 7], [5, 1, 7]]

确认方法返回相同的值

arr, cutoffs = test_data(1000,100)
results = cutoffs.each_with_object([]) { |c,a|
a << send(methods.first, arr, c) }
puts methods[1..-1].all? { |m|
cutoffs.zip(results).all? { |c,r| r == send(m, arr, c) } }
#=> true

基准

require 'benchmark'

arr, cutoffs = test_data(200_000, 20)

Benchmark.bm(methods.map { |m| m.to_s.size }.max) do |bm|
methods.each do |m|
bm.report m.to_s do
cutoffs.each { |c| send(m, arr, c) }
end
end
end

user system total real
awendt 5.140000 0.040000 5.180000 ( 5.188094)
awendt_rev 1.030000 0.010000 1.040000 ( 1.050535)
cary1 0.490000 0.010000 0.500000 ( 0.489371)
cary2 6.740000 0.010000 6.750000 ( 6.782410)
cary3 0.910000 0.010000 0.920000 ( 0.919538)

编辑:我添加了一个方法 :awendt_rev 来替换 collection.sort_by{|num| -num} in :awendt with collection.sort.reverse.

关于ruby-on-rails - 返回集合中与给定值相比具有最高(但不更高)或相等属性值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25836468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com