Sha256: b16d72156cb439ce9136919d74806483a347c0e6d07e00f6593d2ee759d8a7fa

Contents?: true

Size: 787 Bytes

Versions: 10

Compression:

Stored size: 787 Bytes

Contents

module GridSearch

  # Finds the argument which maximizes the function given in the block trhu grid-search maximization.
  #   [-1,0,1,2].argmax {|x| x**2 } #=> 2
  #
  def argmax(&block)
    argbest(:>, &block)
  end
  
  # Finds the argument which minimizes the function given in the block trhu grid-search minimization.
  #   [-1,0,1,2].argmin {|x| x**2 } #=> 0
  #
  def argmin(&block)
    argbest(:<, &block)
  end

  private
  
  def argbest(cmp)
    best_arg, best_val = nil, nil
    self.each do |*curr_arg|
      curr_val = yield(*curr_arg)
      if best_val.nil? || curr_val.send(cmp, best_val)
        best_val = curr_val
        best_arg = curr_arg
      end
    end
    best_arg
  end

end

module Enumerable
  include GridSearch
end

class Array
  include GridSearch
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
cartesian-0.6.7 lib/grid_search.rb
cartesian-0.6.6 lib/grid_search.rb
cartesian-0.6.5 lib/grid_search.rb
cartesian-0.6.4 lib/grid_search.rb
cartesian-0.6.3 lib/grid_search.rb
cartesian-0.6.2 lib/grid_search.rb
cartesian-0.6.0 lib/grid_search.rb
cartesian-0.5.3 lib/grid_search.rb
cartesian-0.5.2 lib/grid_search.rb
cartesian-0.5.0 lib/grid_search.rb