我使用我稱之爲「Boundarize」的方法擴展了Numerics,因爲缺乏更好的名稱;我確定這裏有真正的名字。但其基本目的是將給定點重置爲邊界內。在Ruby中爲數值優化這種「Boundarize」方法
也就是說,「圍繞」邊界的一個點;如果面積betweeon 0到100,如果指針轉到-1:
-1.boundarize(0,100) # => 99
(去一個太遠負「包裝」點周圍一個從最大值)。
102.boundarize(0,100) # => 2
這是一個非常簡單的函數來實現;當數字低於最小值時,只需添加(max-min)直到它處於邊界內。如果數字高於最大值,只需減去(max-min),直到它在邊界內。
我還需要考慮的一件事是,有些情況下我不想在範圍中包含最小值,以及我不想在範圍中包含最大值的情況。這被指定爲參數。
但是,我擔心我目前的實施可怕,非常非常低效。而且因爲每次屏幕上出現某些東西時,都必須重新運行,這是我的應用程序的瓶頸之一。有人有主意嗎?
module Boundarizer
def boundarize min=0,max=1,allow_min=true,allow_max=false
raise "Improper boundaries #{min}/#{max}" if min >= max
raise "Cannot have two closed endpoints" if not (allow_min or allow_max)
new_num = self
if allow_min
while new_num < min
new_num += (max-min)
end
else
while new_num <= min
new_num += (max-min)
end
end
if allow_max
while new_num > max
new_num -= (max-min)
end
else
while new_num >= max
new_num -= (max-min)
end
end
return new_num
end
end
class Numeric
include Boundarizer
end
0.boundarize(10,50) # => 40
10.boundarize(0,10) # => 0 (the maximum is by default not allowed)
0.boundarize(0,20,false) # => 20 (the minimum is not allowed)
哇靠,模。我真笨。 – 2010-05-25 04:57:09