More concise version of max/min without the block
['abcd', 'def'].max_by &:length
Finding the element of a Ruby array with the maximum value for a particular attribute
array.max_by do |element|
element.field
end
Or:
array.max_by(&:field)
ruby comparing groups of objects on a specific property
To expand the answer here:
class Person
attr_accessor :height
def initialize(height)
self.height = height
end
end
people = [ Person.new(10), Person.new(20), Person.new(30) ]
tallest_person = people.max_by &:height
MIN and MAX in C
Where are
MIN
andMAX
defined in C, if at all?
They aren't.
What is the best way to implement these, as generically and type safe as possible (compiler extensions/builtins for mainstream compilers preferred).
As functions. I wouldn't use macros like #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
, especially if you plan to deploy your code. Either write your own, use something like standard fmax
or fmin
, or fix the macro using GCC's typeof (you get typesafety bonus too) in a GCC statement expression:
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
Everyone says "oh I know about double evaluation, it's no problem" and a few months down the road, you'll be debugging the silliest problems for hours on end.
Note the use of __typeof__
instead of typeof
:
If you are writing a header file that
must work when included in ISO C
programs, write__typeof__
instead of
typeof
.
Rails: Finding max of array that may contain nil
I'd go for:
shipping_costs.values.map(&:to_i).max
nil.to_i
is 0
.
Implementing variadic min / max functions
live example
This does perfect forwarding on arguments. It relies on RVO for return values, as it returns a value type regardless of the input types, because common_type
does that.
I implemented common_type
deduction, allowing mixed types to be passed in, and the "expected" result type output.
We support the min of 1 element, because it makes the code slicker.
#include <utility>
#include <type_traits>
template<typename T>
T vmin(T&&t)
{
return std::forward<T>(t);
}
template<typename T0, typename T1, typename... Ts>
typename std::common_type<
T0, T1, Ts...
>::type vmin(T0&& val1, T1&& val2, Ts&&... vs)
{
if (val2 < val1)
return vmin(val2, std::forward<Ts>(vs)...);
else
return vmin(val1, std::forward<Ts>(vs)...);
}
int main()
{
std::cout << vmin(3, 2, 0.9, 2, 5) << std::endl;
std::cout << vmin(3., 1.2, 1.3, 2., 5.2) << std::endl;
return 0;
}
Now, while the above is a perfectly acceptable solution, it isn't ideal.
The expression ((a<b)?a:b) = 7
is legal C++, but vmin( a, b ) = 7
is not, because std::common_type
decay
s is arguments blindly (caused by what I consider an over-reaction to it returning rvalue references when fed two value-types in an older implementation of std::common_type
).
Simply using decltype( true?a:b )
is tempting, but it both results in the rvalue reference problem, and does not support common_type
specializations (as an example, std::chrono
). So we both want to use common_type
and do not want to use it.
Secondly, writing a min
function that doesn't support unrelated pointers and does not let the user change the comparison function seems wrong.
So what follows is a more complex version of the above. live example:
#include <iostream>
#include <utility>
#include <type_traits>
namespace my_min {
// a common_type that when fed lvalue references all of the same type, returns an lvalue reference all of the same type
// however, it is smart enough to also understand common_type specializations. This works around a quirk
// in the standard, where (true?x:y) is an lvalue reference, while common_type< X, Y >::type is not.
template<typename... Ts>
struct my_common_type;
template<typename T>
struct my_common_type<T>{typedef T type;};
template<typename T0, typename T1, typename... Ts>
struct my_common_type<T0, T1, Ts...> {
typedef typename std::common_type<T0, T1>::type std_type;
// if the types are the same, don't change them, unlike what common_type does:
typedef typename std::conditional< std::is_same< T0, T1 >::value,
T0,
std_type >::type working_type;
// Careful! We do NOT want to return an rvalue reference. Just return T:
typedef typename std::conditional<
std::is_rvalue_reference< working_type >::value,
typename std::decay< working_type >::type,
working_type
>::type common_type_for_first_two;
// TODO: what about Base& and Derived&? Returning a Base& might be the right thing to do.
// on the other hand, that encourages silent slicing. So maybe not.
typedef typename my_common_type< common_type_for_first_two, Ts... >::type type;
};
template<typename... Ts>
using my_common_type_t = typename my_common_type<Ts...>::type;
// not that this returns a value type if t is an rvalue:
template<typename Picker, typename T>
T pick(Picker&& /*unused*/, T&&t)
{
return std::forward<T>(t);
}
// slight optimization would be to make Picker be forward-called at the actual 2-arg case, but I don't care:
template<typename Picker, typename T0, typename T1, typename... Ts>
my_common_type_t< T0, T1, Ts...> pick(Picker&& picker, T0&& val1, T1&& val2, Ts&&... vs)
{
// if picker doesn't prefer 2 over 1, use 1 -- stability!
if (picker(val2, val1))
return pick(std::forward<Picker>(pick), val2, std::forward<Ts>(vs)...);
else
return pick(std::forward<Picker>(pick), val1, std::forward<Ts>(vs)...);
}
// possibly replace with less<void> in C++1y?
struct lesser {
template<typename LHS, typename RHS>
bool operator()( LHS&& lhs, RHS&& rhs ) const {
return std::less< typename std::decay<my_common_type_t<LHS, RHS>>::type >()(
std::forward<LHS>(lhs), std::forward<RHS>(rhs)
);
}
};
// simply forward to the picked_min function with a smart less than functor
// note that we support unrelated pointers!
template<typename... Ts>
auto min( Ts&&... ts )->decltype( pick( lesser(), std::declval<Ts>()... ) )
{
return pick( lesser(), std::forward<Ts>(ts)... );
}
}
int main()
{
int x = 7;
int y = 3;
int z = -1;
my_min::min(x, y, z) = 2;
std::cout << x << "," << y << "," << z << "\n";
std::cout << my_min::min(3, 2, 0.9, 2, 5) << std::endl;
std::cout << my_min::min(3., 1.2, 1.3, 2., 5.2) << std::endl;
return 0;
}
The downside to the above implementation is that most classes do not support operator=(T const&)&&=delete
-- ie, they do not block rvalues from being assigned to, which can lead to surprises if one of the types in the min
does not . Fundamental types do.
Which is a side note: start deleting your rvalue reference operator=
s people.
Minimum value in each row and each column of a matrix - Python
Use numpy.
>>> import numpy as np
>>> matrix =[[12,34,28,16],
... [13,32,36,12],
... [15,32,32,14],
... [11,33,36,10]]
>>> np.min(matrix, axis=1) # computes minimum in each row
array([12, 12, 14, 10])
>>> np.min(matrix, axis=0) # computes minimum in each column
array([11, 32, 28, 10])
How to use awk to find the largest and smallest numbers?
The problem is the lines if (max < $2) max=$2 cmax=$1
and if (min > $2) min=$2 cmin=$1
the should be if (max < $2){ max=$2; cmax=$1 }
and if (min > $2){ min=$2; cmin=$1}
respectively. Another error is with the line print cmin min \n cmax max
which should at least be print cmin min "\n" cmax max
. Errors are easierly spotted when you format the code better:
BEGIN{
first=1
}
{
if (first) { # We should move this to it's own block and test against NR
max = min = $2
first = 0
next
}
if (max < $2) { # confusing using max to store min
max=$2
cmax=$1
}
if (min > $2) { # and min to store max your operators are the wrong way round
min=$2
cmin=$1
}
}
END {
print cmin min "\n" cmax max
}
Your script should now work but still has a few issue, compare with the version below:
NR==1{ # If we are on the first line in the file
min=max=$2 # Set initial min/max values
next # Skip to next line
}
{
if ($2 > max) { # If the value in field 2 is greater than current max
max=$2 # Store the new values
cmax=$1
}
if ($2 < min) { # If the value in field 2 is less than current min
min=$2 # Store the new values
cmin=$1
}
}
END {
# Use printf to properly format the output
printf "%s %d\n%s %d\n",cmin,min,cmax,max
}
A side note: if you presort the file on the second field you can be more concise:
sort -nk2 file | awk 'NR==1{print}END{print}'
Related Topics
Ruby Converting Utc to User's Time Zone
Pg::Error: Error: Invalid Byte Sequence for Encoding "Utf8": 0Xfc
Rails 4 Error with Every Command "'Load': No Implicit Conversion of Nil into String" (MAC Os X 10.9)
Parsing Large Xml with Nokogiri
Do I Need to Indent My Code in Ruby
How to Define a Simple Global Variable in an Rspec Test That Can Be Accesed by Helper Functions
Upgrade Ruby on Elastic Beanstalk
Rails Format Validation -- Alphanumeric, But Not Purely Numeric
Floating Point Precision in Ruby on Rails Model Validations
Rugged Gem Installation Issue Possibly with Libgit2 on Windows
How to Get Gmail Oauth or Xauth Tokens with Omniauth
Net-Ssh and Remote Environment
Selenium Webdriver Getting a Cookie Value
Rake Test Very Slow in Windows
How to Assign a Has_Many/Belongs_To Relation Properly in Rails Activerecord