I need to generate random numbers from 0 to 7 with every number appearing 2 times. The end result should have every number appearing 2 times, in random order. An example would be: MyArray = [3, 6, 0, 5, 2, 2, 6, 7, 5, 4, 7, 1, 3, 1, 0, 4]. This is what I tried to do. The code works alone but not in an ADT environnement (in an adapter class that is visited 16 times, but only 14 when I use this code).
ArrayList<Integer> nombres = new ArrayList<Integer>();
private int getRandomNumber() {
Random rand = new Random();
int temp;
while(true){
temp = rand.nextInt(8);
if (nombres.size()==0) {
nombres.add(temp);
return temp;
}
if (nombres.contains(temp)){
if (nombres.indexOf(temp) == nombres.lastIndexOf(temp)){
nombres.add(temp);
return temp;
}
}
if (!nombres.contains(temp)){
nombres.add(temp);
return temp;
}
}
}
Any other, easier solutions? (I have tried to put everything in a single if, same result).
Aucun commentaire:
Enregistrer un commentaire