Генерируем случайное число java
Содержание:
Why is this needed?
Despite being capable of producing numbers within [0, 1), there are a few downsides to doing so:
- It is inconsistent between engines as to how many bits of randomness:
- Internet Explorer: 53 bits
- Mozilla Firefox: 53 bits
- Google Chrome/node.js: 32 bits
- Apple Safari: 32 bits
- It is non-deterministic, which means you can’t replay results consistently
- In older browsers, there can be manipulation through cross-frame random polling. This is mostly fixed in newer browsers and is required to be fixed in ECMAScript 6.
Also, and most crucially, most developers tend to use improper and biased logic as to generating integers within a uniform distribution.
Using ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10
If you want to generate random number in current thread, you can use to generate random number between 1 and 10.
was introducted in JDK 7 for managing multiple threads.
Let’s see with the help of example:
|
1 |
import java.util.concurrent.ThreadLocalRandom; publicclassThreadLocalRandomNextIntMain { publicstaticvoidmain(Stringargs){ intmin=1; intmax=10; System.out.println(«============================»); System.out.println(«Generating 10 random integer in range of 1 to 10 using Math.random»); System.out.println(«============================»); for(inti=;i<5;i++){ intrandomNumber=ThreadLocalRandom.current().nextInt(min,max)+min; System.out.println(randomNumber); } } } |
============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
7
7
4
10
4
That’s all about java random number between 1 and 10.
Generating Javascript Random Numbers
Javascript creates pseudo-random numbers with the function . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
You can use to create whole numbers (integers) or numbers with decimals (floating point numbers). Since creates floating point numbers by default, you can create a random floating point number simply by multiplying your maximum acceptable value by the result from . Therefore, to create a pseudo-random number between 0 and 2.5:
Creating a pseudo-random integer is a little more difficult; you must use the function to round your computed value down to the nearest integer. So, to create a random number between 0 and 10:
Alternate API
There is an alternate API which may be easier to use, but may be less performant. In scenarios where performance is paramount, it is recommended to use the aforementioned API.
constrandom=newRandom(MersenneTwister19937.seedWithArray(0x12345678,0x90abcdef));constvalue=r.integer(,99);constotherRandom=newRandom();
This abstracts the concepts of engines and distributions.
- : Produce an integer within the inclusive range . can be at its minimum -9007199254740992 (2 ** 53). can be at its maximum 9007199254740992 (2 ** 53). The special number is never returned.
- : Produce a floating point number within the range . Uses 53 bits of randomness.
- : Produce a boolean with a 50% chance of it being .
- : Produce a boolean with the specified chance causing it to be .
- : Produce a boolean with / chance of it being true.
- : Return a random value within the provided within the sliced bounds of and .
- : Shuffle the provided (in-place). Similar to .
- : From the array, produce an array with elements that are randomly chosen without repeats.
- : Same as
- : Produce an array of length with as many rolls.
- : Produce a random string using numbers, uppercase and lowercase letters, , and of length .
- : Produce a random string using the provided string as the possible characters to choose from of length .
- or : Produce a random string comprised of numbers or the characters of length .
- : Produce a random string comprised of numbers or the characters of length .
- : Produce a random within the inclusive range of . and must both be s.
Generate random numbers between range
If you want to generate random numbers between certain range, you can use Random and ThreadLocalRandom to do it.
|
1 |
packageorg.arpit.java2blog; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; publicclassGenerateRandomInRangeMain{ publicstaticvoidmain(Stringargs){ intminimum=10; intmaximum=20; System.out.println(«============================»); System.out.println(«Generating 5 random integer in range of 10 to 20 using Random»); System.out.println(«============================»); Random randomGenerator=newRandom(); for(inti=;i<5;i++){ System.out.println(randomGenerator.nextInt((maximum-minimum)+1)+minimum); } System.out.println(«============================»); System.out.println(«Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom»); System.out.println(«============================»); for(inti=;i<5;i++){ System.out.println(ThreadLocalRandom.current().nextInt(minimum,maximum+1)); } System.out.println(«============================»); System.out.println(«Generating 5 random integer in range of 10 to 20 using Math.random»); System.out.println(«============================»); for(inti=;i<5;i++){ System.out.println(minimum+(int)(Math.random()*((maximum-minimum)+1))); } } } |
Output:
============================
Generating 5 random integer in range of 10 to 20 using Random
============================
11
18
14
13
15
============================
Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom
============================
10
12
13
13
16
============================
Generating 5 random integer in range of 10 to 20 using Math.random
============================
14
10
16
20
15
That’s all about generating random numbers in java.
Using Apache Common lang
You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.
Create AlphaNumericString
You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.
|
1 |
packageorg.arpit.java2blog; import org.apache.commons.lang3.RandomStringUtils; publicclassApacheRandomStringMain{ publicstaticvoidmain(Stringargs){ System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10)); System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10)); System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10)); } } |
Output:
Generating String of length 10: Wvxj2x385N
Generating String of length 10: urUnMHgAq9
Generating String of length 10: 8TddXvnDOV
Create random Alphabetic String
You can use RandomStringUtils.randomAlphabetic method to generate alphanumeric random strn=ing.
|
1 |
packageorg.arpit.java2blog; import org.apache.commons.lang3.RandomStringUtils; publicclassApacheRandomStringMain{ publicstaticvoidmain(Stringargs){ System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10)); System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10)); System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10)); } } |
Output:
Generating String of length 10: zebRkGDuNd
Generating String of length 10: RWQlXuGbTk
Generating String of length 10: mmXRopdapr
That’s all about generating Random String in java.
API
- : Utilizes
- : Utilizes
- : Utilizes
- : Produces a new Mersenne Twister. Must be seeded before use.
Or you can make your own!
interfaceEngine{next()number;}
Any object that fulfills that interface is an .
- : Seed the twister with an initial 32-bit integer.
- : Seed the twister with an array of 32-bit integers.
- : Seed the twister with automatic information. This uses the current Date and other entropy sources.
- : Produce a 32-bit signed integer.
- : Discard random values. More efficient than running repeatedly.
- : Return the number of times the engine has been used plus the number of discarded values.
One can seed a Mersenne Twister with the same value () or values () and discard the number of uses () to achieve the exact same state.
If you wish to know the initial seed of , it is recommended to use the function to create the seed manually (this is what does under-the-hood).
constseed=createEntropy();constmt=MersenneTwister19937.seedWithArray(seed);useTwisterALot(mt);constclone=MersenneTwister19937.seedWithArray(seed).discard(mt.getUseCount());
Random.js also provides a set of methods for producing useful data from an engine.
- : Produce an integer within the inclusive range . can be at its minimum -9007199254740992 (-2 ** 53). can be at its maximum 9007199254740992 (2 ** 53).
- : Produce a floating point number within the range . Uses 53 bits of randomness.
- : Produce a boolean with a 50% chance of it being .
- : Produce a boolean with the specified chance causing it to be .
- : Produce a boolean with / chance of it being true.
- : Return a random value within the provided within the sliced bounds of and .
- : Same as .
- : Shuffle the provided (in-place). Similar to .
- : From the array, produce an array with elements that are randomly chosen without repeats.
- : Same as
- : Produce an array of length with as many rolls.
- : Produce a random string using numbers, uppercase and lowercase letters, , and of length .
- : Produce a random string using the provided string as the possible characters to choose from of length .
- or : Produce a random string comprised of numbers or the characters of length .
- : Produce a random string comprised of numbers or the characters of length .
- : Produce a random within the inclusive range of . and must both be s.
An example of using would be as such:
constengine=MersenneTwister19937.autoSeed();constdistribution=integer(,99);functiongenerateNaturalLessThan100(){returndistribution(engine);}
Producing a distribution should be considered a cheap operation, but producing a new Mersenne Twister can be expensive.
An example of producing a random SHA1 hash:
var engine = nativeMath;var distribution =hex(false);functiongenerateSHA1(){returndistribution(engine,40);}
Using Math.random() to generate random number between 1 and 10
You can also use method to random number between 1 and 10. You can iterate from min to max and use Math.ran
Here is formula for the same:
|
1 |
intrandomNumber=(int)(Math.random()*(max-min))+min;
|
Let’s see with the help of example:
|
1 |
publicclassMathRandomExample { publicstaticvoidmain(Stringargs){ intmin=1; intmax=10; System.out.println(«============================»); System.out.println(«Generating 10 random integer in range of 1 to 10 using Math.random»); System.out.println(«============================»); for(inti=;i<5;i++){ intrandomNumber=(int)(Math.random()*(max-min))+min; System.out.println(randomNumber); } } } |
============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
9
6
5
6
2
Math и метод random
Вроде бы всё просто, вызвал свойство у объекта и вот тебе числа. Но не всё так просто, это конечно не чистый природный рандом а эмулятор, псевдо-рандом. Но и он поможет написать вам интересную программу, например русское лото.
Но генерирует он числа от 0 до 1, так что разберём нюансы написания скрипта и вызова random, так же наполним массив случайными числами.
JavaScript
<script>
var rand = Math.random(); //Но минус в том что генерирует он от нуля до единицы
document.write(rand);
document.write(«<br /><hr />»);
var rand2 = Math.random() * 100; //Так мы получим случайное число в диапазоне от 0 до 100
document.write(rand2);
document.write(«<br /><hr />»);
var rand3 = Math.round(Math.random() * 100); //Наконец то нормальное человеческое число))
document.write(rand3);
document.write(«<br /><hr />»);
//Теперь нам надо задать диапазон в котором числа будут рандомизировать, здесь вам пришлось бы повозиться если бы всё ещё до вас не придумали
function myRandom(from, to){
return Math.floor((Math.random() * (to — from + 1)) + from); //Тут уже нужны математические мозги
}
document.write(myRandom(50,60));
/**********************************************************************************************************************/
//Заполняем массив рандомными числами
var randArr = new Array(10);
var start = 40;
var fin = 80;
function myRandom2(from, to){
return Math.floor((Math.random() * (to — from + 1)) + from); //Тут уже нужны математические мозги
}
function randomArray(arr,begin,end){
for(var i = 0; i < arr.length; i++){
arr = myRandom2(begin,end); //Так просто 0_о!!! В смысле я думал понадобиться метод типа push
document.write(arr + «<br />»);
}
}
document.write(«<br /><hr />Значения в массиве формируются от » + start + » и до » + fin + «<br />»);
randomArray(randArr,start,fin); //Можно спрограммировать игру «русское лото» какие числа будут выпадать
</script>
|
1 |
<script> varrand=Math.random();//Но минус в том что генерирует он от нуля до единицы document.write(rand); document.write(«<br /><hr />»); varrand2=Math.random()*100;//Так мы получим случайное число в диапазоне от 0 до 100 document.write(rand2); document.write(«<br /><hr />»); varrand3=Math.round(Math.random()*100);//Наконец то нормальное человеческое число)) document.write(rand3); document.write(«<br /><hr />»); //Теперь нам надо задать диапазон в котором числа будут рандомизировать, здесь вам пришлось бы повозиться если бы всё ещё до вас не придумали functionmyRandom(from,to){ returnMath.floor((Math.random()*(to-from+1))+from);//Тут уже нужны математические мозги } document.write(myRandom(50,60)); varrandArr=newArray(10); varstart=40; varfin=80; functionmyRandom2(from,to){ returnMath.floor((Math.random()*(to-from+1))+from);//Тут уже нужны математические мозги } functionrandomArray(arr,begin,end){ for(vari=;i<arr.length;i++){ arri=myRandom2(begin,end);//Так просто 0_о!!! В смысле я думал понадобиться метод типа push document.write(arri+»<br />»); } } document.write(«<br /><hr />Значения в массиве формируются от «+start+» и до «+fin+»<br />»); randomArray(randArr,start,fin);//Можно спрограммировать игру «русское лото» какие числа будут выпадать </script> |
Количество просмотров: 402
| Категория: JavaScript | Тэги: JavaScript / random / основы / числа
Usage
In your project, run the following command:
npm install random-js
or
yarn add random-js
In your code:
import{Random}from"random-js";constrandom=newRandom();constvalue=random.integer(1,100);
const{Random}=require("random-js");constrandom=newRandom();constvalue=random.integer(1,100);
Or to have more control:
constRandom=require("random-js").Random;constrandom=newRandom(MersenneTwister19937.autoSeed());constvalue=random.integer(1,100);
It is recommended to create one shared engine and/or instance per-process rather than one per file.
Download and place it in your project, then use one of the following patterns:
define(function(require){var Random =require("random");returnnewRandom.Random(Random.MersenneTwister19937.autoSeed());});define(function(require){var Random =require("random");returnnewRandom.Random();});define("random",function(Random){returnnewRandom.Random(Random.MersenneTwister19937.autoSeed());});
Download and place it in your project, then add it as a tag as such:
<scriptsrc="lib/random-js.min.js"><script><script>var random =newRandom.Random();alert("Random value from 1 to 100: "+random.integer(1,100));</script>
Using Math.random method
You can use Math.random’s method to generate random doubles.
|
1 |
packageorg.arpit.java2blog; publicclassMathRandomMain{ publicstaticvoidmain(Stringargs){ System.out.println(«============================»); System.out.println(«Generating 5 random doubles»); System.out.println(«============================»); for(inti=;i<5;i++){ System.out.println(Math.random()); } } } |
Output:
============================
Generating 5 random doubles
============================
0.3644159931296438
0.07011727069753859
0.7602271011682066
0.914594143579762
0.6506514073704143
Read also:Java random number between 0 and 1Java random number between 1 and 10
Using random.nextInt() to generate random number between 1 and 10
We can simply use Random class’s nextInt() method to achieve this.
As the documentation says, this method call returns «a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)», so this means if you call nextInt(10), it will generate random numbers from 0 to 9 and that’s the reason you need to add 1 to it.
Here is generic formula to generate random number in the range.
randomGenerator.nextInt((maximum – minimum) + 1) + minimum
In our case,
minimum = 1
maximum = 10so it will berandomGenerator.nextInt((10 – 1) + 1) + 1randomGenerator.nextInt(10) + 1
So here is the program to generate random number between 1 and 10 in java.
|
1 |
packageorg.arpit.java2blog; import java.util.Random; publicclassGenerateRandomInRangeMain{ publicstaticvoidmain(Stringargs){ System.out.println(«============================»); System.out.println(«Generating 10 random integer in range of 1 to 10 using Random»); System.out.println(«============================»); Random randomGenerator=newRandom(); for(inti=;i<10;i++){ System.out.println(randomGenerator.nextInt(10)+1); } } } |
When you run above program, you will get below output:
==============================
Generating 10 random integer in range of 1 to 10 using Random
==============================
1
9
5
10
2
3
2
5
8
1
Read also:Java random number between 0 and 1Random number generator in java
True Random Numbers
As mentioned above, true random numbers must spring for a source outside computers without hardware dedicated to this purpose. For needs that require truly random cryptographically appropriate random numbers use one of the following external sources via their public APIs:
- random.org samples atmospheric noise and provides several data sources: integer, sequence, set, gaussian, float, and raw random data.
- The Australian National University (ANU) Quantum Optics Group’s Quantum RNG derives random numbers by measuring the quantum fluctuations of a vacuum. Additionally, you can see and hear random number sequences.
- The Ruđer Bošković Institute Quantum Random Bit Generator Service harvests randomness from the quantum process of photonic emission in semiconductors, made available through many libraries for programming languages and other methods.
- The Taiyuan University of Technology Physical Random Number Generator Service publishes random numbers sourced from a chaotic laser.
What is Randomness in Javascript?
It is impossible in computing to generate completely random numbers. This is because every calculation inside a computer has a logical basis of cause and effect, while random events don’t follow that logic.
Computers are not capable of creating something truly random. True randomness is only possible through a source of external data that a computer cannot generate, such as the movement of many lava lamps at once (which has been used as an unbreakable random encryption in the real world), meteographic noise, or nuclear decay.
The solution that Javascript, and other programming languages, use to implement randomness is “pseudo-random” number generation. Javascript random numbers start from a hidden internal value called a “seed.” The seed is a starting point for a hidden sequence of numbers that are uniformly distributed throughout their possible range.
Developers cannot change Javascript’s pseudo-random seed or the distribution of values in its generated pseudo-random sequences. Different Javascript implementations and different browsers often start with different seeds. Do not assume that different browsers, or even different computers, will always use the same seed.
Javascript random numbers are not safe for use in cryptography because deciphering the seed could lead to decryption of the hidden number sequence. Some functions exist to create cryptographically secure pseudo-random numbers in Javascript, but they are not supported by older browsers.
In this blog post, we’ll first cover the canonical methods of creating Javascript random numbers. Then we’ll move onto ways of obtaining higher-quality random data; your needs will determine the worthwhile effort.
Random Number Generators (RNGs) in the Java platform
For the reasons outlined above, there are actually various different random number generators in the Java platform.
The following random nubmer generators are currently provided in the Java platform «out of the box», with the Random
base class offering the possibility of custom subclasses:
| Class | Quality | Speed | Period | When to use |
|---|---|---|---|---|
| java.util.Random | Low | Medium | 248 |
Legacy uses or for subclassing. The LCG algorithm used by java.lang.Random is a slow, poor-quality It is still the base class if you |
| ThreadLocalRandom | Medium | Fast | 264 | This is the general-purpose class to use in most cases, unless you need to guarantee that you are using a specific algorithm, will be working with a very large number of threads or need to be able to set predictable seeds. For more information, see the explanation of ThreadLocalRandom. |
| SecureRandom | Very High | Slow | 2160 | Used where you need very high quality or cryptographic strength random numbers. For more information, see explanation of SecureRandom. |
| SplittableRandom | Medium | Fast | 264 per instance | Used when a very large number of random numbers need to be generated and/or when large number of separate geneartor instances are needed to perform a joint task, e.g. for a very large number of threads working together or in certain divide-and-conquer algorithms. For more information, see explanation of SplittableRandom. |
At the time of writing, there is a proposal underway (see JEP 356: Enhanced Pseudo-Random
Number Generators) to add further RNG algorithms to the Java platform.
How does Random.js alleviate these problems?
Random.js provides a set of «engines» for producing random integers, which consistently provide values within , i.e. 32 bits of randomness.
One is also free to implement their own engine as long as it returns 32-bit integers, either signed or unsigned.
Some common, biased, incorrect tool for generating random integers is as follows:
The problem with both of these approaches is that the distribution of integers that it returns is not uniform. That is, it might be more biased to return rather than , making it inherently broken.
may more evenly distribute its biased, but it is still wrong. , at least in the example given, is heavily biased to return over .
In order to eliminate bias, sometimes the engine which random data is pulled from may need to be used more than once.
Random.js provides a series of distributions to alleviate this.
Методы
Обратите внимание, что тригонометрические функции (, , , , , и ) принимают в параметрах или возвращают углы в радианах. Для преобразования радианов в градусы, поделите их на величину ; для преобразования в обратном направлении, умножьте градусы на эту же величину
Обратите внимание, что точность большинства математических функций зависит от реализации. Это означает, что различные браузеры могут дать разные результаты, более того, даже один и тот же движок JavaScript на различных операционных системах или архитектурах может выдать разные результаты
- Возвращает абсолютное значение числа.
- Возвращает арккосинус числа.
- Возвращает гиперболический арккосинус числа.
- Возвращает арксинус числа.
- Возвращает гиперболический арксинус числа.
- Возвращает арктангенс числа.
- Возвращает гиперболический арктангенс числа.
- Возвращает арктангенс от частного своих аргументов.
- Возвращает кубический корень числа.
- Возвращает значение числа, округлённое к большему целому.
- Возвращает количество ведущих нулей 32-битного целого числа.
- Возвращает косинус числа.
- Возвращает гиперболический косинус числа.
- Возвращает Ex, где x — аргумент, а E — число Эйлера (2,718…), основание натурального логарифма.
- Возвращает , из которого вычли единицу.
- Возвращает значение числа, округлённое к меньшему целому.
- Возвращает ближайшее число с плавающей запятой одинарной точности, представляющие это число.
- Возвращает квадратный корень из суммы квадратов своих аргументов.
- Возвращает результат умножения 32-битных целых чисел.
- Возвращает натуральный логарифм числа (loge, также известен как ln).
- Возвращает натуральный логарифм числа (loge, также известен как ln).
- Возвращает десятичный логарифм числа.
- Возвращает двоичный логарифм числа.
- Возвращает наибольшее число из своих аргументов.
- Возвращает наименьшее число из своих аргументов.
- Возвращает основание в степени экспоненты, то есть, значение выражения .
- Возвращает псевдослучайное число в диапазоне от 0 до 1.
- Возвращает значение числа, округлённое до ближайшего целого.
- Возвращает знак числа, указывающий, является ли число положительным, отрицательным или нулём.
- Возвращает синус числа.
- Возвращает гиперболический синус числа.
- Возвращает положительный квадратный корень числа.
- Возвращает тангенс числа.
- Возвращает гиперболический тангенс числа.
- Возвращает строку .
- Возвращает целую часть числа, убирая дробные цифры.
Java Math.random() between 1 to N
By default Math.random() always generates numbers between 0.0 to 1.0, but if we want to get numbers within a specific range then we have to multiple the return value with the magnitude of the range.
Example:- If we want to generate number between 1 to 100 using the Math.random() then we must multiply the returned value by 100.
Java program to generate floating-point numbers between 1 to 100.
Output:-
10.48550810115520481.26887023085449
The above program generates floating-point numbers but if we want to generate integer numbers then we must type cast the result value.
Java program to generate integer numbers between 1 to 100.
Output:-
2070
Extending
You can add your own methods to instances, as such:
var random =newRandom();random.bark=function(){if(this.bool()){return"arf!";}else{return"woof!";}};random.bark();
This is the recommended approach, especially if you only use one instance of .
Or you could even make your own subclass of Random:
functionMyRandom(engine){returnRandom.call(this, engine);}MyRandom.prototype=Object.create(Random.prototype);MyRandom.prototype.constructor= MyRandom;MyRandom.prototype.mood=function(){switch(this.integer(,2)){casereturn"Happy";case1return"Content";case2return"Sad";}};var random =newMyRandom();random.mood();
Or, if you have a build tool are are in an ES6+ environment:
classMyRandomextendsRandom{mood(){switch(this.integer(,2)){casereturn"Happy";case1return"Content";case2return"Sad";}}}constrandom=newMyRandom();random.mood();
How Math.random() is implemented
The Math.random() method internally creating a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random(). This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else. The nextDouble() method of Random class is called on this pseudorandom-number generator object.
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.
As the largest double value less than 1.0 is Math.nextDown(1.0), a value x in the closed range where x1<=x2 may be defined by the statements.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!
❮ Math.round()
Java Tutorial ❯
Git Essentials
Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!
95
И если вы хотите генерировать последовательности, можно создать вспомогательный метод:
public static List intsInRange(int size, int lowerBound, int upperBound) {
SecureRandom random = new SecureRandom();
List result = new ArrayList<>();
for (int i = 0; i < size; i++) {
result.add(random.nextInt(upperBound - lowerBound) + lowerBound);
}
return result;
}
Которые вы можете использовать в качестве:
List integerList = intsInRange3(5, 0, 10); System.out.println(integerList);
И что приводит к:
Математика.случайная()
Класс предоставляет нам отличные вспомогательные методы, связанные с математикой. Одним из них является метод , который возвращает случайное значение в диапазоне . Как правило, он используется для генерации случайных значений процентиля.
Тем не менее, аналогично взлом – вы можете использовать эту функцию для генерации любого целого числа в определенном диапазоне:
int min = 10; int max = 100; int randomNumber = (int)(Math.random() * (max + 1 - min) + min); System.out.println(randomNumber);
Хотя этот подход еще менее интуитивен, чем предыдущий. Выполнение этого кода приводит к чему-то вроде:
43
Если вы хотите работать с последовательностью, мы создадим вспомогательный метод для добавления каждого сгенерированного значения в список:
public static List intsInRange(int size, int lowerBound, int upperBound) {
List result = new ArrayList<>();
for (int i = 0; i < size; i++) {
result.add((int)(Math.random() * (upperBound + 1 - lowerBound) + lowerBound));
}
return result;
}
И тогда мы можем назвать это так:
List integerList = intsInRange(5, 0, 10); System.out.println(integerList);
Который производит:
ThreadLocalRandom.nextInt()
Если вы работаете в многопоточной среде, класс предназначен для использования в качестве потокобезопасного эквивалента . К счастью, он предлагает метод nextInt () как верхней, так и нижней границей:
int randomInt = ThreadLocalRandom.current().nextInt(0, 10); System.out.println(randomInt);
Как обычно, нижняя граница включена, в то время как верхняя граница отсутствует:
3
Аналогично, вы можете создать вспомогательную функцию для создания последовательности этих:
public static List intsInRange(int size, int lowerBound, int upperBound) {
List result = new ArrayList<>();
for (int i = 0; i < size; i++) {
result.add(ThreadLocalRandom.current().nextInt(lowerBound, upperBound));
}
return result;
}
Которые вы можете использовать в качестве:
List integerList = intsInRange4(5, 0, 10); System.out.println(integerList);
SplittableRandom.ints()
Менее известным классом в Java API является класс , который используется в качестве генератора псевдослучайных значений. Как следует из названия, он разбивается и работает параллельно, и на самом деле используется только тогда, когда у вас есть задачи, которые можно снова разделить на более мелкие подзадачи.
Стоит отметить, что этот класс также основан на небезопасной генерации семян-если вы ищете безопасную генерацию семян, используйте .
Класс предлагает метод , который, с нашей точки зрения, работает так же, как :
List intList = new SplittableRandom().ints(5, 1, 11)
.boxed()
.collect(Collectors.toList());
System.out.println(intList);
Что приводит к:
И, если вы хотите сгенерировать только одно случайное число, вы можете отказаться от коллектора и использовать с :
int randomInt = new SplittableRandom().ints(1, 1, 11).findFirst().getAsInt(); System.out.println(randomInt);
Что приводит к:
4
Вывод
В этом уроке мы подробно рассмотрели как генерировать случайные целые числа в диапазоне в Java .
Мы рассмотрели новейший и наиболее полезный метод, а также некоторые другие популярные методы выполнения этой задачи. Большинство подходов основаны на или эквивалентных классах, используемых для более конкретных контекстов.