Generating Unique Random Numbers in Java

2018-12-31 02:51发布

I'm trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32 and not 82,12,53,12,32 I used this, but it generates same numbers in a sequence.

Random rand = new Random();
selected = rand.nextInt(100);

标签: java random
17条回答
宁负流年不负卿
2楼-- · 2018-12-31 03:27

Below is a way I used to generate unique number always. Random function generates number and stores it in textfile then next time it checks it in file compares it and generate new unique number hence in this way there is always a new unique number.

public int GenerateRandomNo()
{
    int _min = 0000;
    int _max = 9999;
    Random _rdm = new Random();
    return _rdm.Next(_min, _max);
}
public int rand_num()
{
    randnum = GenerateRandomNo();
    string createText = randnum.ToString() + Environment.NewLine;
    string file_path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Invoices\numbers.txt";
    File.AppendAllText(file_path, createText);
    int number = File.ReadLines(file_path).Count(); //count number of lines in file
    System.IO.StreamReader file = new System.IO.StreamReader(file_path);
    do
    {
        randnum = GenerateRandomNo();
    }
    while ((file.ReadLine()) == randnum.ToString());
    file.Close();
    return randnum;

}
查看更多
深知你不懂我心
3楼-- · 2018-12-31 03:30

This will work to generate unique random numbers................

import java.util.HashSet;
import java.util.Random;

public class RandomExample {

    public static void main(String[] args) {
        Random rand = new Random();
        int e;
        int i;
        int g = 10;
        HashSet<Integer> randomNumbers = new HashSet<Integer>();

        for (i = 0; i < g; i++) {
            e = rand.nextInt(20);
            randomNumbers.add(e);
            if (randomNumbers.size() <= 10) {
                if (randomNumbers.size() == 10) {
                    g = 10;
                }
                g++;
                randomNumbers.add(e);
            }
        }
        System.out.println("Ten Unique random numbers from 1 to 20 are  : " + randomNumbers);
    }
}
查看更多
爱死公子算了
4楼-- · 2018-12-31 03:30

I have come here from another question, which has been duplicate of this question (Generating unique random number in java)

  1. Store 1 to 100 numbers in an Array.

  2. Generate random number between 1 to 100 as position and return array[position-1] to get the value

  3. Once you use a number in array, mark the value as -1 ( No need to maintain another array to check if this number is already used)

  4. If value in array is -1, get the random number again to fetch new location in array.

查看更多
步步皆殇っ
5楼-- · 2018-12-31 03:31

This isn't significantly different from other answers, but I wanted the array of integers in the end:

    Integer[] indices = new Integer[n];
    Arrays.setAll(indices, i -> i);
    Collections.shuffle(Arrays.asList(indices));
    return Arrays.stream(indices).mapToInt(Integer::intValue).toArray();
查看更多
有味是清欢
6楼-- · 2018-12-31 03:32
  1. Create an array of 100 numbers, then randomize their order.
  2. Devise a pseudo-random number generator that has a range of 100.
  3. Create a boolean array of 100 elements, then set an element true when you pick that number. When you pick the next number check against the array and try again if the array element is set. (You can make an easy-to-clear boolean array with an array of long where you shift and mask to access individual bits.)
查看更多
登录 后发表回答