¿Como Math.Max pero toma 3 o params de int?
Gracias
¿Como Math.Max pero toma 3 o params de int?
Gracias
Respuestas:
Bueno, puedes llamarlo dos veces:
int max3 = Math.Max(x, Math.Max(y, z));
Si te encuentras haciendo esto mucho, siempre puedes escribir tu propio método auxiliar ... Me alegraría mucho ver esto en mi base de código una vez , pero no con regularidad.
(Tenga en cuenta que es probable que esto sea más eficiente que la respuesta basada en LINQ de Andrew, pero obviamente, cuantos más elementos tenga, más atractivo será el enfoque LINQ).
EDITAR: Un enfoque de "lo mejor de ambos mundos" podría ser tener un conjunto personalizado de métodos de cualquier manera:
public static class MoreMath
{
// This method only exists for consistency, so you can *always* call
// MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
// depending on your argument count.
public static int Max(int x, int y)
{
return Math.Max(x, y);
}
public static int Max(int x, int y, int z)
{
// Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
// Time it before micro-optimizing though!
return Math.Max(x, Math.Max(y, z));
}
public static int Max(int w, int x, int y, int z)
{
return Math.Max(w, Math.Max(x, Math.Max(y, z)));
}
public static int Max(params int[] values)
{
return Enumerable.Max(values);
}
}
De esa manera, puede escribir MoreMath.Max(1, 2, 3)o MoreMath.Max(1, 2, 3, 4)sin la sobrecarga de la creación de matrices, pero aún escribir MoreMath.Max(1, 2, 3, 4, 5, 6)para obtener un código legible y coherente cuando no le importa la sobrecarga.
Personalmente, lo encuentro más legible que la creación explícita de matrices del enfoque LINQ.
MoreMath.Max(x, y, z)es incluso más legible que el enfoque LINQ, en mi opinión.
public static int Max(params int[] values) ?
Max(1, 2, 3)creará una matriz sin ningún motivo. Al proporcionar algunas sobrecargas para un número relativamente pequeño de parámetros, puede hacerlo más eficiente sin afectar la legibilidad de la persona que llama.
Podrías usar Enumerable.Max:
new [] { 1, 2, 3 }.Max();
[]. Hábil.
new int[] { 1,2,3 }. Por lo tanto, es una matriz de tipo int, que está implícitamente determinada por su contenido.
Linq tiene una función Max .
Si tiene un IEnumerable<int>, puede llamarlo directamente, pero si los necesita en parámetros separados, puede crear una función como esta:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
Entonces podría llamarlo así: max(1, 6, 2)permite un número arbitrario de parámetros.
Maxlugar de max, y hacerlo estático :) Al sobrecargarlo para menos parámetros, también puede hacerlo más eficiente.
Como genérico
public static T Min<T>(params T[] values) {
return values.Min();
}
public static T Max<T>(params T[] values) {
return values.Max();
}
fuera de tema, pero aquí está la fórmula para el valor medio ... en caso de que alguien lo esté buscando
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
Si, por cualquier motivo (por ejemplo, la API de Space Engineers), System.array no tiene una definición para Max ni tiene acceso a Enumerable, una solución para Max de n valores es:
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
El valor máximo del elemento en priceValues [] es maxPriceValues:
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
Esta función toma una matriz de números enteros. (Entiendo completamente la queja de @Jon Skeet sobre el envío de matrices).
Probablemente sea un poco exagerado.
public static int GetMax(int[] array) // must be a array of ints
{
int current_greatest_value = array[0]; // initializes it
for (int i = 1; i <= array.Length; i++)
{
// compare current number against next number
if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
{
// array[i+1] exists
if (array[i] < array[i+1] || array[i] <= current_greatest_value)
{
// current val is less than next, and less than the current greatest val, so go to next iteration
continue;
}
} else
{
// array[i+1] doesn't exist, we are at the last element
if (array[i] > current_greatest_value)
{
// current iteration val is greater than current_greatest_value
current_greatest_value = array[i];
}
break; // next for loop i index will be invalid
}
// if it gets here, current val is greater than next, so for now assign that value to greatest_value
current_greatest_value = array[i];
}
return current_greatest_value;
}
Luego llama a la función:
int highest_val = GetMax (new[] { 1,6,2,72727275,2323});
// highest_val = 72727275