Random in 2 cycle, do I need to reinitialize? - java

I have this code:
Random r = new Random();
while (mStack[step].hasNext()) {
int rand = r.nextInt(length);
for (int i = rand; i < length+rand; i++) {
//use of i and rand
}
}
and all this in a recursive call.
Will this seed a new Random for each while iteration, different for each recursive call?
Or I have to use
while (mStack[step].hasNext()) {
Random r = new Random();
int rand = r.nextInt(length);
for (int i = rand; i < length+rand; i++) {
//use of i and rand
}
}
Please advice

Constant re-seeding isn't beneficial. Create a single instance of Random, and pass it on the stack as a parameter to the recursive method.
The no-arg Random constructor in Java 6 uses the sum of a instance counter and the current System.nanoTime() value as a seed. Of course, no re-seeding is performed by nextInt().

You need to use the lower example. The example at the top will re-initialize with each call of the containing method. The second will do so for each item in the stack, meaning for each iteration in the loop.

Related

Java Random setSeed() not deterministic

I have a class called 'Face' that creates a static instance of java.util.Random:
public static Random random = new Random();
Then, in Main, I set the seed and get a random value:
Face.random.setSeed(1);
int rand = Face.random.nextInt(5);
The value of 'rand' is different every time I run the program, though. I need it to be the same every time. I thought setting a seed did this, but I must not understand correctly. What am I missing?
If you are always setting the seed for every call, then it appears that the sequence of random numbers will be reset.
Try
random.setSeed(1);
for (int i = 0; i < 5; i++) {
int rand = random.nextInt(5);
System.out.println(rand);
}

How to initialize an Integer Array with multiple values while using "for"

While I was trying to create a small GUI in Java, I've stumbled onto this small issue with arrays.
I've tried inserting Random Integers into an one dimensional array, only to find out that the Random Integers won't get assigned.
//Declaring an Integer Array
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
for(int i = 0; i <= 1; i++) {
Random rand = new Random(6);
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
I expect the output from the array to be a number between 1 - 6.
However, I keep receiving [2,2] as a result every time I try to rerun.
The constructor call new Random(6) doesn't do what you think it does: 6 is the seed, rather than the range of possible outputs. Therefore it will produce the same output every time.
Possible solutions:
Use the no-argument constructor for Random() instead, which will give it a different seed each time.
Declare and initialise rand outside the loop, with or without an explicit seed.
Use Math.random().
So in your code you set up a seed for your Random and you create new Random object every loop iteration so it just returns same number every time. If you use seed the documentation of Random class says :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
In your case you can get rid of seed value from your constructor or move Random class object creation outside of the loop :
public static void main(String[] args) {
int[] arr = new int[2];
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
arr[i] = zahlen;
}
System.out.println(Arrays.toString(arr));
}
Here I moved creation of Random instance outside of the loop so only one object is created and I am not passing seed to the constructor. I could pass the seed but in this case it is not needed as I don't need to create more instances of Random and I dont need them to generate same results.
*
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
* try this one create Random object with passing parameter

Get random strings from a list

I have an ArrayList which is defined outside the main method, just inside the class StringRandomize:
public static ArrayList<String> countries = new ArrayList<String>();
I also initialized a random object.
Random obj = new Random();
Then I add some Strings to the list:
StringRandomize.countries.add("USA");
StringRandomize.countries.add("GB");
StringRandomize.countries.add("Germany");
StringRandomize.countries.add("Austria");
StringRandomize.countries.add("Romania");
StringRandomize.countries.add("Moldova");
StringRandomize.countries.add("Ukraine");
How do I make those strings appear randomly? I need output like "Germany", "Moldova" and so on.
I need exactly the strings in the output, not their IDs.
Thanks for your help.
You probably want to use something like:
countries.get(Math.abs(new Random().nextInt()) % countries.size());
Or, to avoid creating a new Random object every time, you could use the same one:
Random gen = new Random();
for (int i = 1; i < 10; i++) {
System.out.println(countries.get(Math.abs(gen.nextInt()) % countries.size()));
}
I would use Collections.shuffle(countries) if you wanted a randomized List.
Else a new Random().nextInt(max) like Flavius described.
static void shuffleArray(string[] ar)
{
//set the seed for the random variable
Random rnd = ThreadLocalRandom.current();
//go from the last element to the first one.
for (int i = ar.size()- 1; i > 0; i--)
{
//get a random number till the current position and simply swap elements
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
This way you shuffle the entire array and get the values in a random order but NO duplicate at all. Every single element changes position, so that no matter what element (position) you pick, you get a country from a random position. You can return the entire vector, the positions are random.

Java.lang.NullPointerException in my own shuffle method while using random numbers in Java?

I'm trying to implement a shuffle method to shuffle cards in a deck array class.
Here's the code:
public void shuffle()
{
Card holderCard = new Card();
for (int x = 0; x < 1000; x++)
{
spot1 = rnd.nextInt(52);<<<<<<<
spot2 = rnd.nextInt(52);
holderCard = deck[spot1];
deck[spot1] = deck[spot2];
deck[spot2] = holderCard;
}
}
Every time I run the program and get to the shuffle method, I get a java.lang.NullPointerException on the line with <<<<<<.
I don't really know why or how, but this method is just supposed to change the position of cards in the array.
You are supposed to initialize the rnd variable before using it:
Random rnd = new Random ();
May be you have just declared variable rnd and not initialize it like
Random rnd = new Random ();

Random numbers in Java

How to draw a number from 0 to 4 in Java (Android)?
How to use the Random function?
The follwing will do what you need.
Random r = new Random();
int randomInt = r.nextInt(5);
If you do this in a loop, make sure you initialize the Random outside of the loop.
Random r = new Random();
for(int i = 0;i < someThing; i++) {
System.out.println(r.nextInt(5));
}
See the documentation for the Random class: http://download.oracle.com/javase/6/docs/api/java/util/Random.html
Please Pay Attantion - Calling each time the code:
Random r = new Random();
Will probably return you the same numbers (i guess few of you have noticed that phanamona).
I guess it connected somehow to the Java problem with random numbers:
Java: Can (new Random()).nextInt(5) always return the same number?
and: Java random always returns the same number when I set the seed?
Anyway my solution is to add a static variable to my class:
static Random sRandomGen = new Random();
and call the nextInt from the relevant method when i need the random number. Thatway i recieve an equal dividing between results.
int rnd = sRandomGen.nextInt(numofmatches - 1);
This solution works great for me.
One thing to be careful of is that you shouldn't create a new Random object every time you want a new number. This line should be executed once when the application starts:
Random r = new Random();
Then this should be called each time you want a new random number:
int x = r.nextInt(5);
System.out.println(""+(int) (Math.random()*5.0));
If you only need to generate a single random number, I believe it's slightly cheaper to use the Math.random() than to make an object.
Note: to generate any random integer from 0 to n, (0 inclusive, n exclusive), just use:
(int) (Math.random()*n);
To generate any random integer from m to m+n, (m inclusive, m+n exclusive), just use:
m + (int) (Math.random()*n);

Categories