Many of my reader ask how to generate unique random number in android without duplication or repetition. In this post I will show simple code snippet which will use to generate random number without repetition or duplication. The code snippet mentioned in this post is used in SmakAndApp quiz game app. User can download SmakAndApp quiz game app from Google Play.
Initially, I used Random class to generate random number in given range i.e. upto 50 in this example. But problem is, this generate duplicate entry. To know more about Random class visit developer.android.com/reference/java/util/Random.html
Initially, I used Random class to generate random number in given range i.e. upto 50 in this example. But problem is, this generate duplicate entry. To know more about Random class visit developer.android.com/reference/java/util/Random.html
Random rndNoGnrt = new Random();
int rndNo = rndNoGnrt.nextInt(50)+1;
To overcome above problem I used List class to create random number without repetition. Given below code is used for unique random number generation.
List<Integer> NumberList = new ArrayList<Integer>();for (int i = 1; i <= 50; i++){NumberList.add(i);}Collections.shuffle(NumberList);NumberList.get(0)NumberList.remove(0);
Searched Key:
Random number generator example in android.
Generate random numbers without duplication.
Generating a unique random number between given numbers.
Generate random number without repetition
No comments:
Post a Comment