get Unique Random Numbers - Java java.util

Java examples for java.util:Random

Description

get Unique Random Numbers

Demo Code


//package com.java2s;

import java.util.HashSet;
import java.util.Set;

public class Main {
    public static Set<Integer> getUniqueRandomNumbers(int min, int max,
            int totalCount) {
        int spread = max - min;
        if ((max - min) < totalCount) {
            totalCount = spread;//from  w ww .  ja v  a  2s  .  c  o  m
        }
        Set<Integer> output = new HashSet<Integer>();
        while (true) {
            int id = min
                    + (int) Math.floor(((double) spread) * Math.random());
            if (!output.contains(id)) {
                output.add(new Integer(id));
            }
            if (output.size() >= totalCount) {
                break;
            }
        }
        return output;
    }
}

Related Tutorials