July 26, 2007

Ruby code: Finding the closest point

We want to fetch an avatar of specific size. How to find the closest size from all available sizes? Suppose available sizes are 16, 48 and 96.

An obvious version is

  def closest_size(size)
case
when size < 32
16
when size < 72
48
else
96
end
end

The value used in comparison tests is the average of two neighboring candidate sizes. The problem is that when our available sizes change, we need to add or remove when clauses and recalculate average values.


Here is a smarter way

def closest_size(size)
points = [16, 48, 96]
distances = points.map {|a| (size - a).abs}
points[distances.index(distances.min)]
end

It finds the point with shortest distance to the given size. Now if we want to change candidate sizes, we only need to change the array literal. Further, we can even pass the candidate array as an argument.

4 comments:

Lisbet said...

Thanks for writing this.

モバゲー said...

モバゲーより確実に逢えるスタービーチ♪今まで遊びをしてこなかった人でも100%であいが堪能できます。理想の異性をGETするなら当サイトにお任せください

玉の輿度チェッカー said...

このサイトでこれからの人生が変わるかも?玉の輿度をチェックする性格診断で、ホントのあなたをズバリ分析しちゃいます!玉の輿度チェッカーの診断結果には、期待以上の意外な結果があるかも

高松宮記念 said...

高松宮記念の最新予想!オッズ、厳選買い目は?!レースの鍵を握る馬は裏情報を特別公開