代码之家  ›  专栏  ›  技术社区  ›  Justin L.

优化Ruby中的数值“边界化”方法

  •  0
  • Justin L.  · 技术社区  · 16 年前

    也就是说,在边界周围“环绕”一个点;如果面积介于0和100之间,如果点变为-1:

    -1.boundarize(0,100)        # => 99 
    

    (往负方向走太远会把点从最大点绕到1)。

    102.boundarize(0,100)       # => 2
    

    我还需要说明的一点是,有些情况下,我不想将最小值包含在范围内,有些情况下,我不想将最大值包含在范围内。这被指定为参数。

    然而,我担心我目前的实现是可怕的,可怕的,非常低效。因为每次屏幕上有东西移动时,它都必须重新运行,这是我的应用程序的瓶颈之一。有人有什么想法吗?

    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)
    
    2 回复  |  直到 16 年前
        1
  •  2
  •   Alex Korban    16 年前

    在我看来,您所需要的只是模(%operator)和一些额外的检查来处理allow\u min和allow\u max:

    irb(main):002:0> -1 % 100
    => 99
    irb(main):003:0> -101 % 100
    => 99
    irb(main):004:0> 102 % 100
    => 2
    
        2
  •  0
  •   tliff    16 年前