0

I'm developing a simple game to add 2 number and select a result in a gridview. But I've only put a number to 1st or last position of my list's Array. How to add my result to the random position without give it an exactly index? Here is my code:

x=random.nextInt(11);
a=a+x;
for (int j=1;j<25;){
    int random=((int)(Math.random()*25))+1;
    if (!list.contains(random)){
        list.add (a+random);
        j++;
    }
}

3 Answers 3

1

Simply adds your random numbers in your list as you do then call Collections.shuffle(List) to reorder your List randomly.

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

Comments

0
  1. First create array with N Values (Blank/Null we can say)
  2. Now you need to generate random number between 0 to N-1
  3. Use above value as index and store you value.

Comments

0
private List <Integer> createRandomIndexes() {
    List<Integer> indexes = new ArrayList<>();
    for (int i = 1; i < 25; i++) {
        indexes.add(i);
    }
    Collections.shuffle(indexes);
    return indexes;
}

Here's the key to random

Collections.shuffle(indexes);

Comments

Your Answer

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