Jak wygenerować losową wartość int
w określonym zakresie?
Próbowałem następujących rozwiązań, ale te nie działają:
Próba 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Próba 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
W Java 1.7 lub nowszej, standardowy sposób, aby to zrobić jest następujący:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
Zobacz odpowiedni dokument JavaDoc. To podejście ma tę zaletę, że nie trzeba jawnie inicjalizować instancji java.util.Random, która może być źródłem nieporozumień i błędów, jeśli jest niewłaściwie używana.
Jednakże, odwrotnie, nie ma sposobu na jawne ustawienie nasion, więc może być trudno odtworzyć wyniki w sytuacjach, w których jest to przydatne, takich jak testowanie lub zapisywanie stanów gry lub podobnych. W takich sytuacjach można użyć techniki sprzed Java 1.7 pokazanej poniżej.
Przed Javą 1.7, standardowy sposób na zrobienie tego jest następujący:
import java.util.Random;
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance. Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Zobacz odpowiedni dokument JavaDoc. W praktyce, klasa java.util.Random jest często preferowana zamiast java.lang.Math.random().
W szczególności, nie ma potrzeby ponownego wymyślania koła generowania losowych liczb całkowitych, gdy istnieje proste API w ramach biblioteki standardowej, aby wykonać to zadanie.
Użyj:
minimum + rn.nextInt(maxValue - minvalue + 1)
rand.nextInt((max+1) - min) + min;