Unique Random Generator

+1 Pravin Kumar · November 15, 2015
I'm trying to get random numbers between 0 and 100. But I want them to be unique, not repeat in sequence. For example if I got 5 number. They must be 82,12,53,64,32 not like 82,12,53,12,32.


Random rand = new Random();

selected = rand.nextInt(100);

Post a Reply

Replies

Oldest  Newest  Rating
0 Jon Z. · November 15, 2015
This should do the trick.


import java.util.ArrayList;
import java.util.Random;

/**
 * @author Jon Z.
 * jon.zz@outlook.com
 */
public class RandomStuff {
    private final static int MAX_NUM = 100;
    private static ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
    
    public static int getNewRandom(){
        if(randomNumbers.size() >= 100){
            System.out.println("Can't have more than " + MAX_NUM + " different numbers.");
            return -1;
        }
        
        Random rand = new Random();
        int selected = rand.nextInt(MAX_NUM);
        if(isNew(selected)){
            randomNumbers.add(selected);
            return selected;
        }
        else{
            return getNewRandom();
        }
    }
    
    public static boolean isNew(int selected){
        for (int i = 0; i < randomNumbers.size(); i++) {
            if(randomNumbers.get(i) == selected){
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        for (int i = 0; i < 103; i++) {
            System.out.print("Rand#" + (i+1) + " - ");
            int newRand = getNewRandom();
            if(newRand != -1){
                System.out.println(newRand);
            }
        }
    }
    
}
  • 1

Java / Android Development

107,315 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator