Random seed Math.random in Java - java

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;
}
}

Related

Java Random Between Variables

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.

Java Random Generator's seed producing different outputs

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);
}
...
}

Implementing Random Int in Java

I am using Blue J for reference.
What I need to do is after defining 2 constants, MIN = 60 and MAX = 180, which I already did, I am supposed to define the processtime as a random integer between 60 and 240, instead of the constant 120.
Problem is that I am unsure how to do that.
Here is the class, TicketCounter, in which that is supposed to be implemented in.
public class TicketCounter
{
final static int PROCESS = 120;
final static int MAX_CASHIERS = 10;
final static int NUM_CUSTOMERS = 200;
final static int ARR_TIME = 20;
final static int MIN = 60;
final static int MAX = 180;
public static void main ( String[] args)
{
Customer customer;
LinkedQueue<Customer> customerQueue = new LinkedQueue<Customer>();
int[] cashierTime = new int[MAX_CASHIERS];
int totalTime, averageTime, departs;
System.out.printf("%-25.30s %-30.30s%n", "Number of Cashiers", "Average Time (in seconds)");
/** process the simulation for various number of cashiers */
for (int cashiers=0; cashiers < MAX_CASHIERS; cashiers++)
{
/** set each cashiers time to zero initially*/
for (int count=0; count < cashiers; count++)
cashierTime[count] = 0;
/** load customer queue */
for (int count=1; count <= NUM_CUSTOMERS; count++)
customerQueue.enqueue(new Customer(count*ARR_TIME));
totalTime = 0;
/** process all customers in the queue */
while (!(customerQueue.isEmpty()))
{
for (int count=0; count <= cashiers; count++)
{
if (!(customerQueue.isEmpty()))
{
customer = customerQueue.dequeue();
if (customer.getArrivalTime() > cashierTime[count])
departs = customer.getArrivalTime() + PROCESS;
else
departs = cashierTime[count] + PROCESS;
customer.setDepartureTime (departs);
cashierTime[count] = departs;
totalTime += customer.totalTime();
}
}
}
/** output results for this simulation */
averageTime = totalTime / NUM_CUSTOMERS;
System.out.printf("%10s %30s%n", (cashiers+1), averageTime);
}
}
}
Thank you in advance!
I'm not fully sure if I understand what you're looking for, but what I am certain of is that you want to randomize an integer. This can easily be done by the Random class.
What I'm not sure about is whether you want to randomize a number between 60-120 (MIN-MAX) or 60-280. Whether the case it should look something like this.
Random r = new Random();
int randomInt = r.nextInt(MAX - MIN + 1) + MIN;
This code will now result the variable to be an integer between MIN and MAX, now you can easily replace those with constants or set values to them for nice and understandable code.
For further information of what the code exactly does, I would recommend you again, to take a look at the Random class, I find it very useful in many cases.
If you have MIN and MAX, and can use Random you might do -
Random random = new Random();
int MIN = 60;
int MAX = 180;
int val = random.nextInt(MAX + 1) + MIN;
Which will generate a random value between 60 inclusive and 240 inclusive. Random.nextInt(int) which (per the Javadoc),
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).

How to generate a random number between two values then set to TextView?

How to generate a random number between two values and then set to TextView?
int min = 1;
int max = 100;
Random r1 = new Random();
int random = r1.nextInt(max - min) + min;
tv1.setText(""+random);
Random random = new Random();
int value = random.nextInt(max - min) + min;
num1.setText(String.valueOf(value));
barwnikk was almost right, but shouldn't be doing that kind of tricks in order to convert from int to String
Random random = new Random();
int value = random.nextInt(max - min) + min;
num1.setText(value+"");
You can't use .setText(value), because integer will be a resource link to /res/strings! Add +"" after number!!!
There are two (or more) methods:
public final void setText (CharSequence text) - To set text
public final void setText (int resid) - to set text from file /res/string/strings.xml
This is how to generate a number between two numbers but i don't know how to set to text view
Random r = new Random();
int value;
value = r.nextInt(max - min) + min;

Java/Android Biased Number Generator

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;
}
}

Categories

Resources