Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
Número aleatorio entre int.MinValue e int.MaxValue, inclusive

Aquí hay un pequeño rompecabezas: Random.Next() tiene una sobrecarga que acepta un valor mínimo y un valor máximo. Esta sobrecarga devuelve un número mayor o igual que el valor mínimo (inclusive) y menor que el valor máximo (exclusivo).

Me gustaría incluir todo el rango, incluido el valor máximo. En algunos casos, podría lograr esto simplemente agregando uno al valor máximo. Pero en este caso, el valor máximo puede ser int.MaxValue , y agregar uno a esto no lograría lo que quiero.

Entonces, ¿alguien sabe un buen truco para obtener un número aleatorio de int.MinValue a int.MaxValue , inclusive?

ACTUALIZAR:

Tenga en cuenta que el rango inferior puede ser int.MinValue pero también puede ser otra cosa. Si sé que siempre sería int.MinValue , entonces el problema sería más simple.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

La implementación interna de Random.Next(int minValue, int maxValue) genera dos muestras para rangos grandes, como el rango entre Int32.MinValue e Int32.MaxValue . Para el método NextInclusive , tuve que usar otro Next de gran rango, con un total de cuatro muestras. Por lo tanto, el rendimiento debería ser comparable con la versión que llena un búfer con 4 bytes (una muestra por byte).

 public static class RandomExtensions { public static int NextInclusive(this Random random, int minValue, int maxValue) { if (maxValue == Int32.MaxValue) { if (minValue == Int32.MinValue) { var value1 = random.Next(Int32.MinValue, Int32.MaxValue); var value2 = random.Next(Int32.MinValue, Int32.MaxValue); return value1 < value2 ? value1 : value1 + 1; } return random.Next(minValue - 1, Int32.MaxValue) + 1; } return random.Next(minValue, maxValue + 1); } }

Algunos resultados:

 new Random(0).NextInclusive(int.MaxValue - 1, int.MaxValue); // returns int.MaxValue new Random(1).NextInclusive(int.MaxValue - 1, int.MaxValue); // returns int.MaxValue - 1 new Random(0).NextInclusive(int.MinValue, int.MinValue + 1); // returns int.MinValue + 1 new Random(1).NextInclusive(int.MinValue, int.MinValue + 1); // returns int.MinValue new Random(24917099).NextInclusive(int.MinValue, int.MaxValue); // returns int.MinValue var random = new Random(784288084); random.NextInclusive(int.MinValue, int.MaxValue); random.NextInclusive(int.MinValue, int.MaxValue); // returns int.MaxValue

Actualización: mi implementación tiene un rendimiento mediocre para el rango más grande posible ( Int32.MinValue - Int32.MaxValue ), así que se me ocurrió una nueva que es 4 veces más rápida. Produce alrededor de 22,000,000 de números aleatorios por segundo en mi máquina. No creo que pueda ser más rápido que eso.

 public static int NextInclusive(this Random random, int minValue, int maxValue) { if (maxValue == Int32.MaxValue) { if (minValue == Int32.MinValue) { var value1 = random.Next() % 0x10000; var value2 = random.Next() % 0x10000; return (value1 << 16) | value2; } return random.Next(minValue - 1, Int32.MaxValue) + 1; } return random.Next(minValue, maxValue + 1); }

Algunos resultados:

 new Random(0).NextInclusive(int.MaxValue - 1, int.MaxValue); // = int.MaxValue new Random(1).NextInclusive(int.MaxValue - 1, int.MaxValue); // = int.MaxValue - 1 new Random(0).NextInclusive(int.MinValue, int.MinValue + 1); // = int.MinValue + 1 new Random(1).NextInclusive(int.MinValue, int.MinValue + 1); // = int.MinValue new Random(1655705829).NextInclusive(int.MinValue, int.MaxValue); // = int.MaxValue var random = new Random(1704364573); random.NextInclusive(int.MinValue, int.MaxValue); random.NextInclusive(int.MinValue, int.MaxValue); random.NextInclusive(int.MinValue, int.MaxValue); // = int.MinValue
over 4 years ago · Santiago Trujillo Report

0

Sin casting, sin long , todos los casos límite se tienen en cuenta, el mejor rendimiento.

 static class RandomExtension { private static readonly byte[] bytes = new byte[sizeof(int)]; public static int InclusiveNext(this Random random, int min, int max) { if (max < int.MaxValue) // can safely increase 'max' return random.Next(min, max + 1); // now 'max' is definitely 'int.MaxValue' if (min > int.MinValue) // can safely decrease 'min' // so get ['min' - 1, 'max' - 1] // and move it to ['min', 'max'] return random.Next(min - 1, max) + 1; // now 'max' is definitely 'int.MaxValue' // and 'min' is definitely 'int.MinValue' // so the only option is random.NextBytes(bytes); return BitConverter.ToInt32(bytes, 0); } }
over 4 years ago · Santiago Trujillo Report

0

Bueno, tengo un truco. No estoy seguro de describirlo como un "buen truco", pero siento que podría funcionar.

 public static class RandomExtensions { public static int NextInclusive(this Random rng, int minValue, int maxValue) { if (maxValue == int.MaxValue) { var bytes = new byte[4]; rng.NextBytes(bytes); return BitConverter.ToInt32(bytes, 0); } return rng.Next(minValue, maxValue + 1); } }

Entonces, básicamente, un método de extensión que simplemente generará cuatro bytes si el límite superior es int.MaxValue y se convertirá en un int , de lo contrario, solo use la sobrecarga estándar Next(int, int) .

Tenga en cuenta que si maxValue es int.MaxValue , ignorará minValue . Supongo que no me di cuenta de eso...

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!