This question already has answers here:
Generating an Odd Random Number between a given Range
(10 answers)
Closed 7 years ago.
I'm trying to generate odd numbers randomly. I tried this, but it generates even numbers also:
int coun=random.nextInt();
for(int i=1; i<100; i++){
if(i%2==1){
coun=random.nextInt(i);
}
}
How can I generate odd numbers randomly?
You could add 1 to even numbers
int x=(int) (Math.random()*100);
x+=(x%2==0?1:0);
or multiply the number by 2 and add one
int x=(int) (Math.random()*100);
x=x*2+1;
a lot of possible solutions.
All numbers of the form 2*n + 1 are odd. So one way to generate a random odd number would be, to generate a random integer, multiply it by 2, and add 1 to it:
int n = random.nextInt();
int r = 2 * n + 1; // Where r is the odd random number
For each random number n, there is a unique odd random number r generated (in other words, it is a bijection) - thus ensuring unbiasedness (or at least, as much unbiasedness as the function random.nextInt()).
There is 50 odd numbers between 0 and 100. To select one of them you can do
int n = random.nextInt(50);
to get the n-th odd number you can
int odd = n * 2 + 1;
Putting it all together
int odd = random.nextInt(max / 2) * 2 + 1;
One solution would be to test wheter the random integer value is odd or not. If it is not, you can add or subtract one with half probability.
Random random = new Random();
int i = random.nextInt();
if (i % 2 == 0) {
i += random.nextBoolean() ? 1 : -1;
}
Related
Given an integer, 234, how would I use a Random object to take this number and add only one random digit to it without making it a String. So the goal in this case would be to return a number that has 4 digits, with the last one being random. So for example the next number could be 2347. Then I want to take this number and do the same thing for 5 digits, for instance 23471. I know I can multiply by 10 to increase the digit count by 1, but this would not be random. The only methods I'm aware of for the Random class are nextInt(int n) and nextDouble().
Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum, Random)
{
gameNum = gameNum * 10 + generator.nextInt(10) would do it.
(The second argument to + is a random number in the inclusive range 0 to 9).
If you want to support negative gameNum, then use the more complex
gameNum = (gameNum >= 0 ? 1 : -1) * (Math.abs(gameNum) * 10 + generator.nextInt(10));
which effectively strips the sign, performs the concatenation of the random number, then reintroduces it.
You don't need to pass Random instance as an argument to updateGameNum()
Just multiply getNum with 10 and add a number from (0 - 9) by picking it randomly.
Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum)
{
return ( gameNum *10 ) + generator.nextInt(10);
}
I have a method which is generating random integers. I don't want integers to be repeated, so I created this code -
int prevInt = 0;
private int randomInt() {
int random = (int) (Math.random() * 3);
//generate random numbers between 0 to 3 inclusive
if(random == prevInt)
return randomInt();
//if previous random number is equal to currently generated
//random number, then call this method again for a different
//random number
prevInt = random;
return random;
//else return the generated random number
}
Is the above code safe to use? At worst case scenario, can it be possible that all random integers generated by Math.random() * 3 are same?
private final Random random = new Random();
private int randomInt(final int prev, final int max) {
final int next = random.nextInt(max - 1);
if(next >= prev){
return next + 1;
}else{
return next;
}
}
This will return an int between 0 and max without the need to repeat.
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
There are two principal means of generating random (really pseudo-random) numbers:
the Random class generates random integers, doubles, longs and so on,
in various ranges.
the static method Math.random generates doubles between 0 (inclusive)
and 1 (exclusive).
To generate random integers:
do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.
To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number.
Other alternatives are:
SecureRandom, a cryptographically strong subclass of Random
ThreadLocalRandom, intended for multi-threaded cases
please have a look at this post.
SO Reference 1,Reference 2
From the javadoc, Math.random() return a pseudo random and (approximately) uniform distributed number within the range.
So when you don't strict accuracy you may use it. Otherwise search for better solution.
try this trivial code and see for yourself
for (int ran = 0; ran < 10; ran++) {
int random = (int) (Math.random() * 3);
System.out.println(random);
}
Output in my case
2 2 0 2 1 0 0 0 2 1
First, I must point that your question title is not that clear. Safe can mean various thing. In this case I think you mean safety of algorithm of your code, not security nor only Math.random().
Unfortunately, your code is not algorithmically safe. Even if Math.random is safe, Your code has always positive possibility on running at any time: roughly speaking it means there are no guarantee that your code ends in finite time.
Assume you are taking random number among 4 numbers. If you are drawing random number excluding right before number, you're actually not drawing from 4 numbers: it's 3. I suggest another method:
int prevInt = -1;
private int randomInt() {
if (prevInt == -1) {
int random = (int) (Math.random() * 4);
//generate random numbers between 0 to 3 inclusive
} else if
int random = (int) (Math.random() * 3);
random = (random >= prevint) ? (random + 1) % 4 : random;
}
prevInt = random;
return random;
}
private void resetRandom() {
prevInt = -1;
//use when you want to reset information that you have 'before' result.
}
This algorithm ends within finite time. Concern about whether Math.Random() itself is dangerous or whatever will be explained by other nice guys.
Yes, it is safe but we never know what is going to happen, so we can simply multiply Math.random two times to maintain a good safety
int random = (int) (Math.random() * Math.random() * 3);
I have an generation method that generates numbers between 1 and 8. But the problem is that this method often generates the numbers 1-7 and almost never number 8. My question is that how to generate random numbers in certain interval but that all numbers appear approximately same times ?
EDIT:
my number generator
public int generateNumber() {
Random r = new Random();
return r.nextInt(8 - 1) + 1;
}
The random generator generates an "uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)" Please refer to the documentation:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
You can do:
random.nextInt(max - min + 1) + min
And it should be fine.
Alternatively,
Random randomGenerator = new Random();
for (int idx = 1; idx <= NUMBER_OF_INTEGERS_YOU_WANT; idx++){
int randomInt = randomGenerator.nextInt(8)+1;
CODE_HERE
}
"almost never number 8": If that generator ever generates 8 there is something wrong.
The nextInt gives a number between 0 and 6 (borders inclusive) and adding one gives the interval [1,7].
To get numbers in [1,8] you can use
r.nextInt(8) + 1
You need something like
return r.nextInt(8) + 1;
Which will return values from 1 to 8. So it starts with 0 and generated number max uptil n-1 i.e. 7 as per this.
In your case, you have r.nextInt(8 - 1) which evaluates to r.nextInt(7) so it would generate numbers from 0 -6 and on top of that you are adding 1 to number from above api, so your range is 1-7 and not 1-8.
I'm trying to make a method where you choose 2 number in main and the method finds the highest value between does to numbers.
The program takes a number divides it by 2, if not possible to divide multiply by 3 and add 1, divide again and so on until reaching 1.
output: number 10
6 times
int count = 0;
while( number != 1){
count++;
if(number % 2 == 0){
number = number / 2;
}else{
number = number * 3 + 1;
}
}
return count;
This is what i have so far and i have no idea how to pick 2 number and finding the highest one in between those 2.
Use the java.util.Random for generating random values.
Random r = new Random();
int n1 = r.nextInt();
int n2 = r.nextInt();
If you put what you have in a method that takes an int as a parameter, you can call it twice, once using a java.util.Random - generated number, and again using a different random value. You can store the results of both calls as ints, and compare the two of them. Hope that helps!
int first = reduceNumber(r.nextInt());
int second = reduceNumber(r.nextInt());
Use the Random class to generate random numbers.
To know the maximum of them,
int max = Math.max(n1, n2);
I'm sorry. Those to numbers are pick by me in main. I think i have to use array.
So the output should be like this:
Using Scanner in main.
lowest limit: 2
highest limit: 10000000
the number 837799(method that finds the number) is the one that is divided
the most times: 524(code that counts how many times it has been divided) which i have..
That's how it's suppose to look like. So i don't think random is going to help.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java: generating random number in a range
How do I generate a random value between two numbers. Random.nextInt() gives you between 0 and the passed value. How do I generate a value between minValue and a maxValue
Write a method like:
public static int getRandom(int from, int to) {
if (from < to)
return from + new Random().nextInt(Math.abs(to - from));
return from - new Random().nextInt(Math.abs(to - from));
}
This also takes account for facts, that nextInt() argument must be positive, and that from can be bigger then to.
random.nextInt(max - min + 1) + min will do the trick. I assume you want min <= number <= max
Example: Generating a number from 1 to 6
Because nextInt(6) returns a number from 0-5, it's necessary to add 1 to scale the number into the range 1-6
static Random randGen = new Random();
int spots;
. . .
spots = randGen.nextInt(6) + 1;