Android - generate random numbers without repeating

Can someone tell me how to generate random numbers without repeating an example

random (10) should (may) return 3,4,2,1,7,6,5,8,9,10 without repetition

thanks

+7
source share
4 answers

I would suggest adding numbers to ArrayList<Integer> and then using Collections.shuffle() to randomize their order. Something like that:

 ArrayList<Integer> number = new ArrayList<Integer>(); for (int i = 1; i <= 10; ++i) number.add(i); Collections.shuffle(number); 
+25
source

Make a list of generated numbers, when your newly created number is already in this list, you create a new random number.

 Random rng = new Random(); // Ideally just create one instance globally List<Integer> generated = new ArrayList<Integer>(); for (int i = 0; i < numbersNeeded; i++) { while(true) { Integer next = rng.nextInt(max) + 1; if (!generated.contains(next)) { // Done for this iteration generated.add(next); break; } } } 
+4
source

My two cents

 public Collection<Integer> getRandomSubset(int max,int count){ if(count > max){ throw new IllegalArgumentException(); } ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0 ; i < count ;i++){ list.add(i); } Collections.shuffle(list); return list.subList(0, count); } 
+2
source

If there are only a few numbers, less than 100, I think I could create a logical array, and as soon as you get the number, set the position of the array to true. I don’t think it will take a long time until all the numbers appear. Hope this helps!

Hooray!

-2
source

All Articles