Google's Guava library provides a great class called Range
, it has many useful methods like greaterThan(x)
, open(x,y)
, etc. I am wondering if there is any way of applying such method to generate a random number within a Range
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I would not suggest using a range for this basic application.
The easiest method to use is the already implemented Random class.
Here is how to use the class:
For getting a random integer of any value:
For getting a random integer in a range of min x, max y:
This is the most basic way of getting a random number in a range. I bet there is a getMin and getMax method in the range class, so use that for x and y.
Also, if you want a random number greater than a min value of x, just do:
^The code above generates any positive integer, and the x ensures the min value.
-or-
-as suggested by ColinD Hope this helps. -Classic
Like Louis says there's no built-in way to do this, but there are a couple of fairly straightforward options. Note that we have to assume all
Range
instances are bounded on both sides - you cannot select a random value from an unbounded or non-discrete range (e.g.(-∞..0]
).The easiest to implement solution is to simply convert the
Range
into aContiguousSet
, from which you can select a random value in linear time. This has the advantage of working for any discrete type, not justRange<Integer>
.Of course constant time would be better, especially for large ranges. Canonicalizing the
Range
first reduces the number of cases we have to handle, and we can use thef(y-x) + x
pattern JClassic suggests.You can extend this easily for
Long
withRandom.nextLong()
(but note thatRandom.nextLong()
cannot return alllong
values, soSecureRandom
would be preferable).