Random number list without repeating Android

2

I have an ArrayList with N items inside and I need to group them randomly into 2 sets of X items and the rest into another set. However, none of them can be repeated.

For example: my ArrayList has 20 items added and I want to split it into 2 groups of 7, and the remaining 6 into another set. However, the choice of these items to compose the sets has to be random and none of those 20 can be repeated in any of the sets.

I am aware of the Random class and I am using it, but the problem is being in the moment of comparing the new numbers generated with the previous ones, so that there is no repetition.

    
asked by anonymous 06.02.2016 / 03:21

1 answer

2

One possible approach is to randomly sort (shuffle) the 20-item ArrayList and extract the others.

Example for an ArrayList of 20 integers:

ArrayList<Integer> original = new ArrayList<>();
for(int i = 0; i< 20; i++){
    original.add(i);
}

//Clone o original caso o queira manter inalterado
ArrayList<Integer> embaralhado = (ArrayList<Integer>) original.clone();

//Embaralha
Collections.shuffle(embaralhado);

ArrayList<Integer> grupo1 = new ArrayList<>();
ArrayList<Integer> grupo2 = new ArrayList<>();
ArrayList<Integer> grupo3 = new ArrayList<>();

//Percorre o ArrayList embaralhado e distribui os seus itens pelos grupos.
for(int i=0; i < embaralhado.size(); i++){
   if(i < 7)grupo1.add(embaralhado.get(i));
   else if(i < 14)grupo2.add(embaralhado.get(i));
   else grupo3.add(embaralhado.get(i));
}
    
06.02.2016 / 13:39