How to choose from a given set of values, rounding?

I have a ruby ​​hash array with two keys, "level" and "price". For this price, I want to return the level.

It's simple enough with exact matching, but how can I make sure I always have a match by rounding my input value to the next value in the array?

For example, given the array below, if I have a value of "499", I want to return "10".

tiers = [
    { tier: 0, price: 0 },
    { tier: 1, price: 50 },
    { tier: 2, price: 100 },
    { tier: 3, price: 150 },
    { tier: 4, price: 200 },
    { tier: 5, price: 250 },
    { tier: 6, price: 300 },
    { tier: 7, price: 350 },
    { tier: 8, price: 400 },
    { tier: 9, price: 450 },
    { tier: 10, price: 500 },
    { tier: 11, price: 550 },
    { tier: 12, price: 600 },
    { tier: 13, price: 650 },
    { tier: 14, price: 700 },
    { tier: 15, price: 750 },
    { tier: 16, price: 800 },
    { tier: 17, price: 850 },
    { tier: 18, price: 880 },
    { tier: 19, price: 950 },
    { tier: 20, price: 1000 }
]

I can get an exact match with tiers.detect { |tier| tier[:price] == "500"}[:tier], but that will return an error if I don't have a match. I could increase the value of the input until I return it, but that seems very inefficient.

, , ( 17 18, 30).

+4
3

. - :

def detect_tier(price)
  tiers.each_cons(2) do |t1, t2|
    next if price < t1[:price] # too low
    next if price > t2[:price] # too high

    return t1[:tier] if price == t1[:price] # matches tier price exactly
    return t2[:tier] # "round up"
  end
end

detect_tier(10) # => 1
detect_tier(100) # => 2
detect_tier(499) # => 10
+6

, -   Array # bsearch_index, O (n) O (log n).

, :price tiers nil , tiers.last[:price].

def round_up(tiers, price)
  return nil if price > tiers.last[:price]
  tiers[tiers.map { |h| h[:price] }.bsearch_index { |p| p >= price }][:tier]
end

.

tiers = [
  { tier: "cat", price:   0 },
  { tier: "dog", price:  50 },
  { tier: "pig", price: 100 },
  { tier: "owl", price: 150 },
  { tier: "ram", price: 300 }
]

round_up(tiers, -10) #=> "cat"
round_up(tiers,   0) #=> "cat"
round_up(tiers,   1) #=> "dog"
round_up(tiers,  49) #=> "dog"
round_up(tiers,  50) #=> "dog"
round_up(tiers,  51) #=> "pig"
round_up(tiers, 150) #=> "owl"
round_up(tiers, 250) #=> "ram"
round_up(tiers, 300) #=> "ram"
round_up(tiers, 301) #=> nil
+1
tiers.detect{|x| x[:price] >= <required_number>}[:tier]

, .

.

tiers.detect{|x| x[:price] >= 1}[:tier] #=> 1
tiers.detect{|x| x[:price] >= 100}[:tier] #=> 2
tiers.detect{|x| x[:price] >= 499}[:tier] #=> 10
tiers.detect{|x| x[:price] >= 750}[:tier] #=> 15
0

Source: https://habr.com/ru/post/1683907/


All Articles