List of random numbers without repetition Android

Asked

Viewed 349 times

2

I have an Arraylist with N items inside and I need to randomly group them into 2 sets of X items and the rest into another set. But none of them can repeat themselves.

For example: my Arraylist has 20 items added and I want to divide it into 2 groups of 7 and the remaining 6 into another set. Only, the choice of these items to compose the sets has to be random (Random) and none of these 20 can be repeated in any of the sets.

I have knowledge of the Random class and am using it, but the problem is to compare the new numbers generated with the previous ones, so there are no repeats.

1 answer

2


One possible approach is to sort randomly (shuffle) the Arraylist of 20 items and extract from it 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));
}
  • Eduardo, is this what you were looking for? It solves your problem?

  • Thank you very much for your reply, Ramaral. I did something similar to yours (extract from a main array and divide it into the desired number of sets). Only I did it using Random even, but your version is much leaner and cleaner. Thanks again and congratulations!

  • Glad I could help and welcome to Stackoverflow. See here how to proceed when a reply has been useful to you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.