While trying to create a Coin object class using two specific seeds passed into the object upon creation, I have noticed that when passing in the seed to an int "seed", the seed variable produces a different variable than just inputting the specific number into the random number generator. Here's some code from the Coin class:
public int headCount;
public int tailCount;
public int seed;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
public Random flipGenerator = new Random(seed);
public String flip(){
String heads = "H";
String tails = "T";
boolean nextFlip = flipGenerator.nextBoolean();
if (nextFlip == true)
{
headCount++;
return heads;
}
if (nextFlip == false)
{
tailCount++;
return tails;
}
return null;
}
Here's from the file that creates and prints the Coin objects:
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
The code in that file prints out the outcome of the random flips 20 times using the 17 seed, 10 times with the 13 seed and finally 35 times with the 17 seed again. However the output is incorrect when using
public Random flipGenerator = new Random(seed);
as opposed to
public Random flipGenerator = new Random(17);
or
public Random flipGenerator = new Random(13);
Why is this happening?
Instance fields are initialized before the constructor is called.
In terms of execution order, this code:
public int headCount;
public int tailCount;
public int seed;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
public Random flipGenerator = new Random(seed);
is functionally equivalent to this:
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator = new Random(seed);
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
In Java, any fields which were not explicitly initialized are given a value of zero/null/false, so you are always doing flipGenerator = new Random(0). By the time you initialize seed in your constructor, the Random object has already been created. The fact that the instance field was declared after the constructor is irrelevant, because all instance fields and their initialization expressions are executed before a constructor is invoked.
Whenever you initialize the Coin class it will use 0 as the seed. Regardless if you put the flipGenerator initialization below the constructor, it will still get called in the constructor since it is an instance variable.
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
This code is using 0 because, by the time you pass the seed, the flipGenerator was initialized with the default seed of 0.
You need to do this
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
flipGenerator = new Random(seed);
}
...
}
Related
I'm trying to randomize between these 3 variables (not range, but only between these 3 values) and store it into new variable.
int randomProductDiscount() {
int disc1 = 25;
int disc2 = 35;
int disc3 = 50;
int productDiscount = (random between disc1 or disc2 or disc3);
return productDiscount;
}
Any help would be appreciated.
Put them in an array and obtain random index:
static Random rand = new Random();
int randomProductDiscount()
{
int[] disc = {25,35,50};
return disc[rand.nextInt(disc.length)];
}
This can be used for any number of values you wish to choose randomly from.
Instead of writing:
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
each time I need a random number in a function, Is it possible to just pass or call the result from a random number generator class into the function?
For Example, I have one function in particular which is receiving variables from another class
favoriteTracks(String fromExampleClass1, String fromExampleClass1again)
could I do
favoriteTracks(String fromExampleClass1, String fromExampleClass1again, Long fromRNGclass)
for clarification:
My one function "favoriteTracks" requires variables passed from "ExampleClass1".
At the same time, I want it to receive a random number as a variable (or call it, whichever is easiest). generated in another class by
public static long randomNum(){
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
The simplest approach would be to encapsulate the behaviour you want in a singleton:
public class MyRandom {
public static final MyRandom myRandom = new MyRandom();
private Random randomGenerator = new Random();
public int makeRandom() {
// put your for loop here if you want, but it is not necessary
return 5 + randomGenerator.nextInt(11);
}
}
somewhere else ...
x = MyRandom.myRandom.makeRandom();
That looks like a possible solution for what you are trying to do.
In my code I use random numbers in different classes. How to define random seed? Can I define this seed for all the classes in the main code?
double rnd = Math.random();
You will probably want to use the special Random class. It gives you more control over the random numbers.
To do this you first need to create a new random object.
Random generator = new Random(seed);
Then generate a new number by
double random = generator.nextDouble();
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
public class MathRandomWithSeed {
public static void main (String args[]){
int min = 5;
int max = 100;
int seed = 5;
int random = randomNext(min, max, seed);
System.out.println("Random = " + random);
}
private static int randomNext(int min, int max, int seed){
int count = (max - min) / seed;
int random = ((int)(count * Math.random()) * seed) + min;
return random;
}
}
I'm trying to create a Java program that generates an amount of seats taken in an airplane. So far, I have been able to do this, but my problem is every time I run the client the numbers generated are different. I need them to be the same every time...
I'm not sure what I'm doing wrong, can anybody help me?
import java.util.Random;
import java.util.Arrays;
public class Airplane {
public static Random randomNumbers = new Random();
public static int[] oSeatLeft = new int[10];
public static int[] mSeatLeft = new int[10];
public static int[] wSeatLeft = new int[10];
public static int oSeat = 0;
public static int mSeat = 0;
public static int wSeat = 0;
public static final int sCheck = 0;
public void genWSeats() {
int randSeatFill = 0;
if (wSeat == 0) {
for (int counter = 0; counter < wSeatLeft.length; counter++) {
randSeatFill = randomNumbers.nextInt(2);
if (randSeatFill == 1) {
wSeatLeft[counter] = 1;
}
}
if (wSeat == 0) {
wSeat++;
}
}
}
public int[] getWSeats() {
System.out.println(java.util.Arrays.toString(wSeatLeft));
return wSeatLeft;
}
}
The purpose of static int wSeat is supposed to be a checker. If wSeat is greater than zero, then it should not randomly generate numbers for the array. Not sure exactly what is going wrong here....
Use the Random constructor with seed
public static Random randomNumbers = new Random(42);
This way always the same sequence of random numbers is generated.
42 is only an example, you can use any value you want.
Pass a seed on initialization with Random(long seed). This will guarantee that the sequence of numbers generated is always the same (since it's a pseudo-random number generator).
Pass Seed in constructor of Random it will generate the same number every time
I have been set a task to create a Android app in which the user chooses four numbers (1-6), I then compare it against four randomly generated numbers and then tell them how many of there numbers were correct.
My problem is that whenever I generate any numbers the first three shown are always the same, except from the last number.
Random a1 = new Random();
random1 = new ArrayList<Integer>();
for (int index = 0; index < 6; index++)
{
random1.add(a1.nextInt(5)+ 1);
}
Random a2 = new Random();
random2 = new ArrayList<Integer>();
for (int index = 0; index < 6; index++)
{
random2.add(a2.nextInt(5)+ 1);
}
This is the code I use for the random number generation, each number uses the exact same code, which makes it even more confusing, if they were all the same I could understand that because it's the same code it generates the same number or something along those lines but the last one is always different, any help would always be appreciated.
Try not create two Random instances but reuse single instance instead. May be two Randoms with close seeds produces close output.
Check if below code works for you. Code taken from http://www.javapractices.com/topic/TopicAction.do?Id=62. Modified according to your requirements.
public final class RandomRange {
public static final void main(String... aArgs) {
int START = 1;
int END = 6;
Random random = new Random();
List<Integer> first = new ArrayList<Integer>();
List<Integer> second = new ArrayList<Integer>();
for (int idx = 1; idx <= END; ++idx) {
first.add(showRandomInteger(START, END, random));
second.add(showRandomInteger(START, END, random));
}
System.out.println(first);
System.out.println(second);
first.retainAll(second);//Find common
System.out.println(first);
}
private static int showRandomInteger(int aStart, int aEnd, Random aRandom) {
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
// get the range, casting to long to avoid overflow problems
long range = (long) aEnd - (long) aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long) (range * aRandom.nextDouble());
int randomNumber = (int) (fraction + aStart);
return randomNumber;
}
}