Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the smartest way to find the larger / smaller of two numbers

Tags:

dart

In search of the smartest, most efficient and readable way to do the below:

int one = 1, two = 2;
int larger = one < two?two:one;

I prefer(or a variadic version of the below):

int largest(one,two){return one<two?two:one;}
int larger = largest(one,two);

But dart has no inline or macro.

With List:

var nums = [51,4,6,8];
nums.sort();
in largest = nums.last

Or(Thank you, Günter Zöchbauer):

print([1,2,8,6].reduce(max));

Using math library:

import 'dart:math';
int largest = max(21,56);

Probably the best, but how efficient is max in comparison to the first approach?

Why the question?
With the first approach I must check comparisons are done right for each of them;hundreds of them sometimes. With the second, only one function to verify, but hundreds of function calls.

like image 609
TastyCatFood Avatar asked Jan 21 '16 07:01

TastyCatFood


People also ask

What is the larger of two numbers mean?

Let's say that x is the smaller number and y is the larger number. You know that if you multiply the smaller number by 4 and add 8 , you get the larger number. This means that you can write. 4⋅x+8=y. Moreover, you know that if you multiply the smaller number by 4 and add it to the larger number, the result will be 40 .

Which function returns the maximum of 2 numbers?

The answer is: max() !


1 Answers

I'm pretty sure just

import 'dart:math';
int largest = max(21,56);

is the best way. It is small enough to be inlined by a compiler (dart2js, VM) and it is the least surprise for the reader. For a custom implementation the reader had to investigate the function to be sure about what it does.

For collections of values I find this the most elegant way

from https://stackoverflow.com/a/20490970/217408

import 'dart:math';

main(){
  print([1,2,8,6].reduce(max)); // 8
  print([1,2,8,6].reduce(min)); // 1
}

Reordering a list just to get the min/max is quite inefficient

var nums = [51,4,6,8];
nums.sort();
in largest = nums.last
like image 197
Günter Zöchbauer Avatar answered Oct 10 '22 16:10

Günter Zöchbauer