For that, I got the solution but I can't understand it:
I have used below function to generate random numbers within the given range but what is the meaning of below function?
static int randomRangeInNumber(int min, int max) {
Random r=new Random();
return r.nextInt((max-min)+1)+min;
}
What i have returned i didnt get
Please help making me understand its meaning
any help will be appreciated
nextInt is normally exclusive of the top value, so add 1 to make it
inclusive
So, in your case, we'll say the max is 10 and min is 5.
nextInt(n) will give you a random number between 0 and n - 1.
So adding the +1 will let you include the value of n.
nextInt(max-min) therefore gives you a random number between (in this case) 0 and 5 - 1 (and include the 5 because of the +1)
Then adding the min again, means it will give you the above random number, but add 5 to it, so the result will be a random number between 5 and 10.
The documentation for nextInt(int bound) says
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So your nextInt call is
taking the return value, which is in the range [0..bound] (where the bound is (max-min)+1) and then
scaling it into the range [min..max] with +min.
return r.nextInt((max-min)+1)+min;
\__________1_________/\_2_/
Related
I have read other posts on this topic but I have not found an answer so far.
Given an array of length of 1000, find its lowest and highest values. These values are the bounds within which a random number is generated.
Finding lowest and highest numbers of an array is OK for me, but generating the number within those bounds is not.
Seems like a simple int number = random.nextInt(max - min) + min; would do the trick, but it does not, because:
a) max can be 100 and min can be -100000, which becomes a negative bound and causes error
b) other solutions like random.nextInt(Math.abs(min) + Math.abs(max)) - Math.abs(min) simply fail, because within an integer data type, adding two positive numbers together can result in a negative value if the maximum value is exceeded.
So let's say I want to generate a random number within -2147483648 and 2147483647. How do I do that?
Thanks alot...
If max==100 and min==-100000, then max-min == +100100 (notice no abs()) and
int number = random.nextInt(max - min) + min;
will produce the value you are looking for. Don't overcomplicate things.
You WILL run into problems if max-min (i.e. the range) is greater than 231-1, but to get around that just use long instead. This is a little more complex since there's no method Random#nextLong(long bound), so you have to just use nextLong() and scale the result to your range.
There are several approaches to scaling a long to a smaller range, such as
randomLong % range
If you really want to scale it to -2147483648..2147483647 then just extract 32 bits from anywhere in the long and turn that into an int.
I am relying on Java's Random class, specifically on the nextInt method to generate N random numbers. I do not know what N will be ahead of time, it is decided on the fly.
One of the requirements of my todo list is to have the random numbers be representative of the distribution.
For example, if N=100, in the range from 1-100 there should be 10 (approximately) numbers between 1-10, 20 numbers between 1-20 etc.
But N can potentially grow on the fly from 100 to 100,000 and as such the distribution of the generated randoms should adjust on the fly to represent 100,000 generated numbers between 1-100
I'm not sure if this is possible, hope it makes sense what I am trying to achieve.
You appear to be describing a uniform distribution.
Looking at the Javadoc of Random.nextInt(int):
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
So, just use Random.nextInt, passing N as the parameter, and add 1 to the result to get it 1 to N instead of 0 to (N-1).
Specifically, if used in the form of:
Random.nextFloat() * N;
can I expect a highly randomized distribution of values from 0 to N?
Would it be better to do something like this?
Random.nextInt(N) * Random.nextFloat();
A single random number from a good generator--and java.util.Random is a good one--will be evenly distributed across the range... it will have a mean and median value of 0.5*N. 1/4 of the numbers will be less than 0.25*N and 1/4 of the numbers will be larger than 0.75*N, etc.
If you then multiply this by another random number generator (whose mean value is 0.5), you will end up with a random number with a mean value of 0.25*N and a median value of 0.187*N... So half your numbers are less than 0.187*N! 1/4 of the numbers will be under .0677*N! And only 1/4 of the numbers will be over 0.382*N. (Numbers obtained experimentally by looking at 1,000,000 random numbers generated as the product of two other random numbers, and analyzing them.)
This is probably not what you want.
At first, Random in Java doesn't contain rand() method. See docs. I think you thought about Random.next() method.
Due to your question, documentation says that nextFloat() is implemented like this:
public float nextFloat() {
return next(24) / ((float)(1 << 24));
}
So you don't need to use anything else.
Random#nextFloat() will give you an evenly distributed number between 0 and 1.
If you take an even distribution and multiply it by N, you scale the distribution up evenly. So you get a random number between 0 and N evenly distributed.
If you multiply this by a random number between 0 and N, then you'll get an uneven distribution. If multiplying by N gives you an even distribution between 0 and N, then multiplying by a number between 0 and N, must give you an answer that is less or equal to if you just multiplied by N. So your numbers on average are smaller.
I have a simple code which generates random numbers
SecureRandom random = new SecureRandom();
...
public int getRandomNumber(int maxValue) {
return random.nextInt(maxValue);
}
The method above is called about 10 times (not in a loop). I want to ensure that all the numbers are unique (assuming that maxValue > 1000).
Can I be sure that I will get unique numbers every time I call it? If not, how can I fix it?
EDIT: I may have said it vaguely. I wanted to avoid manual checks if I really got unique numbers so I was wondering if there is a better solution.
There are different ways of achieving this and which is more appropriate will depend on how many numbers you need to pick from how many.
If you are selecting a small number of random numbers from a large range of potential numbers, then you're probably best just storing previously chosen numbers in a set and "manually" checking for duplicates. Most of the time, you won't actually get a duplicate and the test will have practically zero cost in practical terms. It might sound inelegant, but it's not actually as bad as it sounds.
Some underlying random number generation algorithms don't produce duplicates at their "raw" level. So for example, an algorithm called a XORShift generator can effectively produce all of the numbers within a certain range, shuffled without duplicates. So you basically choose a random starting point in the sequence then just generate the next n numbers and you know there won't be duplicates. But you can't arbitrarily choose "max" in this case: it has to be the natural maximum of the generator in question.
If the range of possible numbers is small-ish but the number of numbers you need to pick is within a couple of orders of magnitude of that range, then you could treat this as a random selection problem. For example, to choose 100,000 numbers within the range 10,000,000 without duplicates, I can do this:
Let m be the number of random numbers I've chosen so far
For i = 1 to 10,000,000
Generate a random (floating point) number, r, in the range 0-1
If (r < (100,000-m)/(10,000,000-i)), then add i to the list and increment m
Shuffle the list, then pick numbers sequentially from the list as required
But obviously, there's only much point in choosing the latter option if you need to pick some reasonably large proportion of the overall range of numbers. For choosing 10 numbers in the range 1 to a billion, you would be generating a billion random numbers when by just checking for duplicates as you go, you'd be very unlikely to actually get a duplicate and would only have ended up generating 10 random numbers.
A random sequence does not mean that all values are unique. The sequence 1,1,1,1 is exactly as likely as the sequence 712,4,22,424.
In other words, if you want to be guaranteed a sequence of unique numbers, generate 10 of them at once, check for the uniqueness condition of your choice and store them, then pick a number from that list instead of generating a random number in your 10 places.
Every time you call Random#nextInt(int) you will get
a pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive).
If you want x unique numbers, keep getting new numbers until you have that many, then select your "random" number from that list. However, since you are filtering the numbers generated, they won't truly be random anymore.
For such a small number of possible values, a trivial implementation would be to put your 1000 integers in a list, and have a loop which, at each iteration, generates a random number between 0 and list.size(), pick the number stored at this index, and remove it from the list.
This is code is very efficient with the CPU at the cost of memory. Each potiental value cost sizeof(int) * maxValue. An unsigned integer will work up to 65535 as a max. long can be used at the cost of a lot of memory 2000 bytes for 1000 values of 16 bit integers.
The whole purpose of the array is to say have you used this value before or not 1 = yes
'anything else = no
'The while loop will keep generating random numbers until a unique value is found.
'after a good random value is found it marks it as used and then returns it.
'Be careful of the scope of variable a as if it goes out of scope your array could erased.
' I have used this in c and it works.
' may take a bit of brushing up to get it working in Java.
unsigned int a(1000);
public int getRandomNumber(int maxValue) {
unsigned int rand;
while(a(rand)==1) {
rand=random.nextInt(maxValue);
if (a(rand)!=1) { a(rand)=1; return rand;}
}
}
I am trying to generate a random number that only populates a certain percent of the time. For example, I want to create an array that is set between a certain range (lets say 0-100), but 10% of the time I want the random number chosen to be multiplied by n. How would I be able to generate this "random" number n% of the time?
edit
I haven't tried it yet in Java, I've only been trying to write out the algorithm by hand but I am just getting stumped. What I am going to have is a variable that holds a number, lets say that number is 3000, and the random number from the array is going to be deducted out of the number 3000 until it hits 0, but a certain percent of the time I want the number pulled from the array to be multiplied by n a certain percent of the time .
You can do something 10% of the time by picking a random number between 0 and 100 and triggering the event if the number is less than 10. So, pick your random number. Then choose another random number between 0 and 100 and if that second number is less than 10, you multiply the first by n.
public static boolean getRandPercent(int percent) {
Random rand = new Random();
return rand.nextInt(100) <= percent;
}