Reputation: 43
I'm trying to create a Random number generator using, java.util.Random
. I need to generate numbers between -5 and +5 excluding zero. This is for bouncingbox app for one of my labs. The random number is the direction of the velocity of the box.
Random v = new Random();
int deltaX = -5 + v.nextInt(10) ;
for(; deltaX>0 && deltaX<0;){
System.out.println(deltaX);
}
I've tried this, but it doesn't exclude zero. Any help would be appreciated.
Upvotes: 4
Views: 7389
Reputation: 19855
Yet another way:
int[] outcomeSet = {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5};
int deltaX = outcomeSet[v.nextInt(10)];
If the outcomeSet
is made static this should be the most computationally efficient.
Upvotes: 4
Reputation: 11002
You could also do this:
Random random = new Random();
int random = random.nextInt(5) + 1;
int result = random.nextBoolean() ? random : -random;
Yes its less effective because it requires two random values. The resulting intervals are [-5 - 0) and [1 - 5]
Upvotes: 1
Reputation: 33327
Here is one way:
int deltaX = -5 + v.nextInt(10);
if (deltaX >= 0) deltaX++;
Upvotes: 5
Reputation: 172448
You may try like this:-
int deltaX = -5 + v.nextInt(10);
if (deltax >= 0) deltax++;
Upvotes: 1
Reputation: 124225
I like other answers which random in range [-5,4] and if value is 0 or grater they add 1 making real range [-5; -1] [1; 5]
.
But here is some easier approach, although not shorter.
Random v = new Random();
boolean makeNegative = v.nextBoolean();
int value = v.nextInt(5) + 1; // range [1; 5]
if (makeNegative)
value = -value;
It is less effective because it requires two random values (boolean and int) but code is easier to read.
Upvotes: 2
Reputation:
One possible solution without regeneration the random each time is to use the following algorithm:
public int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
int random = start + rnd.nextInt(end - start + 1 - exclude.length);
for (int ex : exclude) {
if (random < ex) {
break;
}
random++;
}
return random;
}
The following can be either called with an array reference:
int[] ex = { 2, 5, 6 };
val = getRandomWithExclusion(rnd, 1, 10, ex)
or by directly inserting the numbers into the call:
val = getRandomWithExclusion(rnd, 1, 10, 2, 5, 6)
It generates a random number (int) between start and end (both inclusive) and does not give you any number which is contained in the array exclude. All other numbers occur with equal probability. Note, that the following constrains must hold: exclude is sorted ascendingly and all numbers are within the range provided and all of them are mutually different.
Upvotes: 3
Reputation: 5348
do {
deltaX = -5 + v.nextInt(11);
} while (deltaX == 0)
The easiest way, still random(no +1).
Upvotes: 1