Reputation: 13
I'm trying to generate an arraylist of random numbers and display it. I'm not sure where I'm going wrong. I think my showArray method isn't working properly because it's displaying two random numbers and then repeating the second one n-2 times.
private static ArrayList<Integer> RandomArray(int n)
{
ArrayList<Integer> arrayRandom = new ArrayList<Integer>(n);
for (int i=0; i<n; i++)
{
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
Integer r = rand.nextInt() % 256;
arrayRandom.add(r);
}
return arrayRandom;
}
private static void ShowArray(ArrayList<Integer> randomArray)
{
int n = randomArray.size();
ArrayList<Integer> showArray = new ArrayList<Integer>(n);
for (int i = 0; i<n; i++)
{
int r = randomArray.get(i);
showArray.add(r);
}
System.out.println(showArray);
}
public static void main(String args[])
{
ShowArray(RandomArray(5));
}
So for example this would produce an output of
[132, 152, 152, 152, 152]
Any help is much appreciated. Thanks in advance
Upvotes: 1
Views: 28886
Reputation: 48559
Don't set the seed every iteration
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
Do it once.
Upvotes: 0
Reputation: 20442
You problem is that you keep resetting the seed and thus restarting the pseudo random number generator (PRNG) sequence.
Do this:
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i=0; i<n; i++)
{
Integer r = rand.nextInt(256);
arrayRandom.add(r);
}
Upvotes: 1
Reputation: 13604
Take the random object out of your loop and don't set the seed everytime.
ArrayList<Integer> arrayRandom = new ArrayList<Integer>(n);
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i=0; i<n; i++)
{
Integer r = rand.nextInt() % 256;
arrayRandom.add(r);
}
This should work better.
Upvotes: 6