Reyjohn Reyjohn - 3 months ago 8
Java Question

How to avoid duplicate random number and select another one in android?

I have an Arraylist and an Array of integer like this,

ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {0,1,2,3,4,5};


Now I want to toast the integers from this array evertime I click a button with out any repeatation. After toasting every number from this array I want to toast 'Finished', my logic in onclick listener is here:

Random r = new Random();

int i1=r.nextInt(number.length-0) + 0;
if(!ar.contains(i1)){
Toast.makeText(getApplicationContext(), ""+i1, Toast.LENGTH_LONG).show();
ar.add(i1);
}else{

Toast.makeText(getApplicationContext(), "Finished", Toast.LENGTH_LONG).show();
}


but this didnt come to my way, It doesnt repeat any number but if it gets a duplicate number in the second click then it is toasting finished, but I want to toast it after every number from the integer array are toasted, wat should be my modified logic?

Answer
ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {0,1,2,3,4,5};
for (int i : number) {
    ar.add(i);
}

Random r = new Random();

// repeat this part and you will never have duplicate numbers
int select = r.nextInt(ar.size());
int random = ar.get(select);
ar.remove(select);
Comments