سؤال

Let's say I have something like this:

def find_the_best(array)
  temp = 15435435435 # sufficiently large number
  value = 0
  array.each do |element|
    some_var = function_does_something_complex_and_returns_value(element)
    some_var < temp ? value = element[0]
  end
end

This sufficiently large number solution works, but it seems kinda hacky. What's the best way to handle this, particularly in ruby, but generally as well. The problem is that it really should be set to 0, then assigned the first value and then every value after that should be adopted only if it is smaller.

هل كانت مفيدة؟

المحلول

This doesn't look like a sorting problem as much as best fit based on criteria.

You're looking for the smallest value, there is no need to have the temp value (unless there is something you aren't telling us).

Simply assume the first value will be the best and continue checking as you go.

best_value = array[0];
foreach( element in array )
{
    if( best_value > element )
        best_value = element;
}

نصائح أخرى

What you're looking for is the sort_by routine to sort a list of objects by some arbitrary criteria:

best = array.sort_by do |element|
  function_does_something_complex_and_returns_value(element)
end.first

You may need to use first or last depending on if you want highest to lowest or lowest to highest.

array.min_by{|e| function_does_something_complex_and_returns_value(e) }

or

array.inject {|m,e| [m, function_does_something_complex_and_returns_value(e)].min }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top