Java random from to range

How do I generate random integers within a specific range in Java?

How do I generate a random int value in a specific range? The following methods have bugs related to integer overflow:

randomNum = minimum + (int)(Math.random() * maximum); // Bug: `randomNum` can be bigger than `maximum`. 
Random rn = new Random(); int n = maximum - minimum + 1; int i = rn.nextInt() % n; randomNum = minimum + i; // Bug: `randomNum` can be smaller than `minimum`. 

When you need a lot of random numbers, I do not recommend the Random class in the API. It has just a too small period. Try the Mersenne twister instead. There is a Java implementation.

Before you post a new answer, consider there are already 65+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers.

72 Answers 72

In Java 1.7 or later, the standard way to do this is as follows:

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); 

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random; /** * Returns a pseudo-random number between min and max, inclusive. * The difference between min and max can be at most * Integer.MAX_VALUE - 1. * * @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; >

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

Читайте также:  Python deleting elements in list

Источник

Class Random

An instance of this class is used to generate a stream of pseudorandom numbers; its period is only 2 48 . The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald E. Knuth, The Art of Computer Programming, Volume 2, Third edition: Seminumerical Algorithms , Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random . Java implementations must use all the algorithms shown here for the class Random , for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

Источник

Generating a random number between multiple ranges

I’d go with something like this, to allow you to do it with as many ranges as you like:

import java.util.ArrayList; import java.util.List; import java.util.Random; class RandomInRanges < private final Listrange = new ArrayList<>(); RandomInRanges(int min, int max) < this.addRange(min, max); >final void addRange(int min, int max) < for(int i = min; i > int getRandom() < return this.range.get(new Random().nextInt(this.range.size())); >public static void main(String[] args) < RandomInRanges rir = new RandomInRanges(1, 10); rir.addRange(50, 60); System.out.println(rir.getRandom()); >> 

@KarloDelalic Basically it just makes a list of all the numbers which are in the ranges you give it, then picks a random number from that list, which is therefore a random number from any of the ranges.

First generate an integer between 1 and 20. Then if the value is above 10, map to the second interval.

Random random = new Random(); for (int i=0;i<100;i++) < int r = 1 + random.nextInt(60-50+10-1); if (r>10) r+=(50-10); System.out.println(r); > 

First, you need to know how many numbers are in each range. (I’m assuming you are choosing integers from a discrete range, not real values from a continuous range.) In your example, there are 10 integers in the first range, and 11 in the second. This means that 10/21 times, you should choose from the first range, and 11/21 times choose from the second. In pseudo-code

x = random(1,21) if x in 1..10 return random(1,10) else return random(50,60) 

These ranges are easily replaced with variables. And calculate the total number of numbers in all ranges using variables.

if the list is known I think you can use something like this.

public class Test < public static void main(String[] args) < int a; for(int i=0;i<10;i++) < a=(int) (Math.random()*((10-0)+(60-50))); if(a<=10) < >else if(a>(60-50)) < a=a+50; >System.out.println(a); > > > 

How about the following approach: randomize picking a range an use that range to generage your random number, for that you’ll have to put your ranges in some list or array

public class RandomRangeGenerator < class Range < public int min, max; public Range(int min, int max) < this.min = min; this.max = max; >> @Test public void generate() < Listranges = new ArrayList<>(); ranges.add(new Range(1, 10)); ranges.add(new Range(50, 60)); List randomNumbers = generateRandomNumbers(ranges, 10); System.out.println(randomNumbers.toString()); for(Integer i : randomNumbers) < Assert.assertTrue((i >= 1 && i = 50 && i > private List generateRandomNumbers(List ranges, int numberOfNumbers) < ListrandomNumbers = new ArrayList<>(numberOfNumbers+1); while(numberOfNumbers-- > 0) < Range range = ranges.get(new Random().nextInt(ranges.size())); randomNumbers.add(range.min + (int)(Math.random() * ((range.max - range.min) + 1))); >return randomNumbers; > > 

To generate numbers between two ranges add up the total number of possibilities. 1 — 10 gives us 10 and 50 — 60 gives us another 11, so 21 total. Then, generate a random number between 1 — 21.

int rn = (int)(1 + (Math.random() * 21)); 

If the random number is between 1 and 10, that is easy, you have your number. If it is between 11 — 21, then you have to do some work. First, you can use modulus to get the index of the number between 50 — 60. Since you have 11 possible values in that range, then mod the random number by 11 and add 50.

if (rn > 10) < rn %= 11; rn += 50; >System.out.println(rn); 

This will print values between 1 — 10 and 50 — 60 inclusive.

Читайте также:  Java stream api boxed

Источник

Генерация случайного числа в заданном диапазоне

Java-университет

Генерация случайного числа в заданном диапазоне - 1

Привет по ту сторону экрана. Любой из нас рано или поздно встречается с необходимостью генерировать случайное число в заданном нами диапазоне будь то вещественное или целое число. Для чего? На самом деле это не важно, это может быть функция для расчета шанса для запуска какого нибудь события, получение случайного множителя или любого другая. Итак, для чего это нужно разобрались, а именно для чего угодно 🙂 На самом деле методов получения псевдослучайного числа очень много, я же приведу пример с классом Math , а именно с методом random() ; Что же мы имеем? Вызов метода Math.random() возвращает псевдослучайное вещественное число ( double ) из диапазона [0;1) , то есть, от 0 до 1 исключая 1, а значит максимальное число в диапазоне это 0.99999999999. Хорошо, мы получили псевдослучайное число, но если нам нужен свой диапазон? К примеру, нам нужно псевдослучайное число из диапазона [0;100)? Пишем код:

 public static void main(String. args) < final double max = 100.; // Максимальное число для диапазона от 0 до max final double rnd = rnd(max); System.out.println("Псевдослучайное вещественное число: " + rnd); >/** * Метод получения псевдослучайного вещественного числа от 0 до max (исключая max); */ public static double rnd(final double max)

Получилось не плохо, но max (в нашем случае) мы все равно не получим. Для того чтобы получить случайное число в диапазоне [0;100] нам необходимо прибавить к нашему max 1, а затем преобразовать в целое число типа int или long (зависит от диапазонов которые Вы будете использовать). Пишем код:

 public static void main(String. args) < final int max = 100; // Максимальное число для диапазона от 0 до max final int rnd = rnd(max); System.out.println("Псевдослучайное целое число: " + rnd); >/** * Метод получения псевдослучайного целого числа от 0 до max (включая max); */ public static int rnd(int max)

Примечание: Как видите переменная max была инкрементирована префиксной формой. (Если Вы не знаете что это советую почитать мою статью) Отлично, мы получили то что хотели, но если нам нужен диапазон не от 0, а к примеру [10;75] Пишем код:

 public static void main(String. args) < final int min = 10; // Минимальное число для диапазона final int max = 75; // Максимальное число для диапазона final int rnd = rnd(min, max); System.out.println("Псевдослучайное целое число: " + rnd); >/** * Метод получения псевдослучайного целого числа от min до max (включая max); */ public static int rnd(int min, int max)
 Минимальное число диапазона = 10; Максимальное число диапазона = 75; max -= min; // Отнимаем от максимального значения минимальное для получения множителя псевдослучайного вещественного числа. 

Максимальное число после расчета равно 65 Псевдослучайное вещественное число (к примеру) равно 0.18283417347179454 (Был получен при вызове Math.random() ). Максимальное число перед умножением было инкрементировано префиксной формой. Максимальное число теперь 66 Умножаем 0.18283417347179454 на 66. Результат умножения равен 12.06705544913844. Преобразовываем результат умножения максимального числа на псевдослучайное вещественное число к типу целого числа int . Прибавляем минимальное число к преобразованному результату который равен 12. Возвращаем результат: 22 Как видно из разбора, даже если псевдослучайное вещественное число будет равно нулю, то мы вернем наш минимум в результате сложения нашего минимального числа с результатом умножения. Надеюсь для Вас это было полезно и познавательно. Успехов в освоении Java 😉 Еще пару моих статей: Что такое инкрементирование и декрементирование Оператор деления по модулю

Читайте также:  Ввод значений клавиатуры java

Источник

Generate a random number between a desired range using Java [duplicate]

I was able to generate a random number between [0,50] in my java code but how do I proceed in order to create for example a number in the range of [1,49] This is my code:

4 Answers 4

To get a random number from 1-49, you should pick a random number between 0-48, then add 1:

int min=1; int max=49; Random random=new Random(); int randomnumber=random.nextInt(max-min)+min; 

Make use of the Random class. If you have a method designed as generateRandom(int min, int max) then you could create it like this

private static Random r = new Random(); public static void main(String[] args) < for(int i = 0;iprivate static int generateRandom(int min, int max) < // max - min + 1 will create a number in the range of min and max, including max. If you don´t want to include it, just delete the +1. // adding min to it will finally create the number in the range between min and max return r.nextInt(max-min+1) + min; >

Does it really a bad to create new Random in each invocation!! Won’t GC automatically delete the Random object once it returns to the called method.

You can use a slightly different idiom of randomization:

Random r = new Random(); while (true) < // lower bound is 0 inclusive, upper bound is 49 exclusive // so we add 1 int n = r.nextInt(49) + 1; System.out.println("Number generated: "+n); >

Will print an infinite list of random numbers between 1 and 49.

Источник

Оцените статью