user6407136
user6407136

Reputation:

Insert a number to the random position in an array of random number

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

Upvotes: 0

Views: 2896

Answers (3)

Laurence Pardz
Laurence Pardz

Reputation: 292

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

Upvotes: 0

Nicolas Filotto
Nicolas Filotto

Reputation: 44985

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

Upvotes: 1

Adarsh
Adarsh

Reputation: 310

  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.

Upvotes: 0

Related Questions