This question already has answers here:
Returning a random even number
(5 answers)
Closed 9 years ago.
How do you generate random numbers that go up by twos using Math.random()? For example, I'm trying to generate a random number from the set (2,4,6,8), how would you go it?
For this specific set you could use
(int)(Math.random() * 4) * 2 + 2
Here:
Math.random() generates a number that's greater or equal to 0.0 and strictly less than 1.0;
(int)(... * 4) gives one of 0, 1, 2, 3.
... * 2 + 2 gives one of 2, 4, 6, 8.
Okay, let's make a real general solution.
int lower = 2;
int upper = 8;
int step = 2;
int rand = (int)(Math.random() * (upper-lower+1));
int result = rand - rand%step + lower;
If you want to generate numbers within another set than the one you specified, just change the lower, upper and step variables to fit your set. It includes the upper bound if it's in the set.
The (almost) completely general approach isn't that hard.
static randInt(int first, int last, int step) {
int nsteps = (last+1-first) / step;
return first + step*(int)(nsteps*Math.random());
}
That returns a random integer from {start, start+step, start+2*step, ... } up to and including stop, or the last number before stop if stop is not part of the sequence.
int choice = randInt(2, 8, 2); /* random choice from {2, 4, 6, 8} */
...solved the sample question.
The (almost) part is that this doesn't handle integer overflow or sign errors in the arguments (step is zero, step<0 when first<last, or vice versa.)
int[] numSet={2,4,6,8};
Random myRand=new Random();
int myNum=numSet[myRand.nextInt(numSet.length)];
This creates an array of numbers, the random object, then picks a random element from the array of numbers. This does not assume that the numbers are in any sort of mathematical series. They could be 11, 25, 31, 876, 984368, 7432, 84562, for that matter.
Please don't tell me that there's a polynomial that generates that set from its y-values. I know.
Put those numbers in an array.
Generate a random number using the length of the array - 1 and use it as the index to randomly choose an array element.
You can also use the java.util.Random class like this:
int values[] = {2,4,6,8};
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(values.length);
int randomValue = values[randomInt]; /* Here's your random value from your set */
I would like to add a more general answer.
Assume the smallest integer in the set is A and the size of the set is S. A random integer from the set would be like this:
A + myRandom.nextInt(S) * 2
For your specific example in Java, it would be:
Random myRandom = new Random();
int randomNum = 2 + myRandom.nextInt(4) * 2;
Related
I am trying to generate two 9 digit long random long value in Java using the below code:
for (int i =0;i<2;i++) {
String axisIdStr = Long.toString((long)(System.nanoTime() * (Math.random() * 1000)));
System.out.println("######## axisIdStr "+axisIdStr);
String axId = axisIdStr.substring((axisIdStr.length() -9), axisIdStr.length()) ;
}
But when I run this in windows, i get two different numbers where as when run in mac, I get same two numbers. Why is this happening ?
Can you suggest a better way to generate the long values?
According to your requirement you need to generate 9 digit random numbers. As in the comment suggested you can do it using random.Below I have just given one solution to generate random number between two numbers.
long lowerLimit = 123456712L;
long upperLimit = 234567892L;
Random r = new Random();
long number = lowerLimit+((long)(r.nextDouble()*(upperLimit-lowerLimit)));
You could create an array a[] of int of size 9, and populate with random integers 0-9. Then sum the array up multiplying accordingly.
a[8]*1 + a[7]*10 + a[6]*100 ...
You need to make sure that a[0] only takes digits 1-9 tho...
To get even more random sequence, you Ideally should work on Strings, then you would be able to get 0 on the start position of your random "string", it won't be a number.
Or maybe generate somthing pseudo random and strip last 9 digits out of it.
That's the DIY version of what you could accomplish with what's already out there...
Regards
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 8 years ago.
I've searched high and low for the answer to this and can't see how I'm doing it wrong, I've tried several different ways of coding it but it always goes outside the range I'm looking for. (90 - 180 inclusive).
Can anyone shed some light on the code below???
Random rnd = new Random();
int time = rnd.nextInt(91) + 90;
Thanks for any support offered...
/**
* Randomly generates a number between 90-180 inclusive and sets the random number as an argument to a message-send for each of the
* Runner objects in runnersList.
*/
public void runMarathon()
{
for (Runner r : runnersList)
{
Random rnd = new Random();
int time = rnd.nextInt(91) + 90;
r.setTime(time);
}
}
This function will help you to do what you need
private int randInt(int min, int max) {
return new Random().nextInt((max - min) + 1) + min;
}
just give min and max values as parametres to the function and you will get a random value between the range you specified ;)
A key principal in software development is reuse. So to do this, you can use
"http://commons.apache.org/proper/commons-lang/javadocs/api-3.3/org/apache/commons/lang3/RandomUtils.html#nextInt(int, int)" instead of reinventing the wheel.
I am creating a random number from 1-100, I was looking at some Stackoverflow questions to look for the proper way and I got confused by the many different suggestions.
What is the difference between using this:
int random= (int)(Math.random()*((100-1)+1));
this:
int random= (int)(Math.random()*(100);
and this:
int random= 1+ (int)(Math.random()*((100-1)+1));
int random = (int)(Math.random()*(x);
This sets random equal to any integer between 0 and x - 1.
int random = 1 + (int)(Math.random()*(x);
Adding 1 to the overall expression simply changes it to any integer between 1 and x.
(int)(Math.random()*((100-1)+1))
is redundant and equivalent to
(int)(Math.random()*(100)
So take note that:
1 + (int)(Math.random()*(x) returns an int anywhere from 1 to x + 1
but
(int)(Math.random()*(x + 1) returns an int anywhere from 0 to x + 1.
I recommend that you use Random and nextInt(100) like so,
java.util.Random random = new java.util.Random();
// 1 to 100, the 100 is excluded so this is the correct range.
int i = 1 + random.nextInt(100);
it has the added benefit of being able to swap in a more secure random generator (e.g. SecureRandom). Also, note that you can save your "random" reference to avoid expensive (and possibly insecure) re-initialization.
The first is equivalent to the second. Both will give a random integer between 0 and 99 (inclusive, because Math.random() returns a double in the range [0, 1)). Note that (100-1)+1 is equivalent to 100.
The third, will give an integer between 1 and 100 because you are adding 1 to the result above, i.e. 1 plus a value in the range [0, 100), which results in the range [1, 101).
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java: generating random number in a range
I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.
public int rollDice() {
Random generator = new Random();
return generator.nextInt(sides);
}
Now the problem becomes that this will return values between sides and zero, inclusive, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?
To generate a random int value (uniform distribution) between from and to (inclusive) use:
from + rndGenerator.nextInt(to - from + 1)
In your case (1..sides):
1 + rndGenerator.nextInt(sides)
I want to generate a random number of 14 positive digits only and I use the below function for it:
public void random()
{
Random number = new Random();
long l = number.nextLong();
number.setSeed(System.currentTimeMillis());
long num = Math.abs(number.nextInt())%999 + (l/100000); // problematic line
mTextBox.setString("" + num);
}
I very new to to JavaMe, I have made above function myself but I believe it is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 12 or 13 numbers not 14.
Any suggestions or improvement to the code will be highly appreciated.
If you want 14 digits, then you should use 14 calls to number.nextInt(10) - something like this:
public static String randomDigits(Random random, int length)
{
char[] digits = new char[length];
// Make sure the leading digit isn't 0.
digits[0] = (char)('1' + random.nextInt(9);
for (int i = 1; i < length; i++)
{
digits[i] = (char)('0' + random.nextInt(10));
}
return new String(digits);
}
Note that I've made the instance of Random something you pass in, rather than created by the method - this makes it easier to use one instance and avoid duplicate seeding. It's also more general purpose, as it separates the "use the string in the UI" aspect from the "generate a random string of digits".
I don't know whether Random.nextInt(int) is supported on J2ME - let me know if it's not. Using Math.abs(number.nextInt())%999 is a bad idea in terms of random distributions.
I didn't understand what you really want, the code suggests that you want a 3 digit number (%999).
Otherwise you can create a 14 digit number between 1000000000000000 and 9999999999999999 by
long num = 1000000000000000L + (long)(number.nextDouble() * 8999999999999999.0);
note (1 / 100000) is 0 (zero) since it is done by integer division, use (1.0 / 100000.0) for double division
long num = 10000000000000L+(long)(random.nextDouble()*90000000000000.0);
EDIT:
mTextBox.setString(MessageFormat.format("{0,number,00000000000000}",
new Object[] {new Long(num)}));
You are getting negative numbers because Random.nextInt() returns any 32-bit integer, and half of them are negative. If you want to get only positive numbers, you should use the expression Random.nextInt() & 0x7fffffff or simply Random.nextInt(10) for a digit.