1

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
8BitSensei
  • 301
  • 3
  • 15

2 Answers2

0

Try not create two Random instances but reuse single instance instead. May be two Randoms with close seeds produces close output.

Dmitry Ryadnenko
  • 22,222
  • 4
  • 42
  • 56
0

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

}
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72