1

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly! Otherwise, you'll end up re-setting the random number generator with the same seed for a couple of times (because it'll run faster than one millisecond)
Thanks so much! This works a treat. The most obvious thing to someone with more experience is so distreessing for a novice like me!
1

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

}

Comments

0

Don't set the seed every iteration

        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());

Do it once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.