Generating Unique Random Numbers in Java

后端 未结 21 2537
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

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

相关标签:
21条回答
  • 2020-11-21 08:09

    I have easy solution for this problem, With this we can easily generate n number of unique random numbers, Its just logic anyone can use it in any language.

    for(int i=0;i<4;i++)
            {
                rn[i]= GenerateRandomNumber();
                for (int j=0;j<i;j++)
                {
                    if (rn[i] == rn[j])
                    {
                        i--;
                    }
                }
            }
    
    0 讨论(0)
  • 2020-11-21 08:15

    Though it's an old thread, but adding another option might not harm. (JDK 1.8 lambda functions seem to make it easy);

    The problem could be broken down into the following steps;

    • Get a minimum value for the provided list of integers (for which to generate unique random numbers)
    • Get a maximum value for the provided list of integers
    • Use ThreadLocalRandom class (from JDK 1.8) to generate random integer values against the previously found min and max integer values and then filter to ensure that the values are indeed contained by the originally provided list. Finally apply distinct to the intstream to ensure that generated numbers are unique.

    Here is the function with some description:

    /**
     * Provided an unsequenced / sequenced list of integers, the function returns unique random IDs as defined by the parameter
     * @param numberToGenerate
     * @param idList
     * @return List of unique random integer values from the provided list
     */
    private List<Integer> getUniqueRandomInts(List<Integer> idList, Integer numberToGenerate) {
    
        List<Integer> generatedUniqueIds = new ArrayList<>();
    
        Integer minId = idList.stream().mapToInt (v->v).min().orElseThrow(NoSuchElementException::new);
        Integer maxId = idList.stream().mapToInt (v->v).max().orElseThrow(NoSuchElementException::new);
    
                ThreadLocalRandom.current().ints(minId,maxId)
                .filter(e->idList.contains(e))
                .distinct()
                .limit(numberToGenerate)
                .forEach(generatedUniqueIds:: add);
    
        return generatedUniqueIds;
    
    }
    

    So that, to get 11 unique random numbers for 'allIntegers' list object, we'll call the function like;

        List<Integer> ids = getUniqueRandomInts(allIntegers,11);
    

    The function declares new arrayList 'generatedUniqueIds' and populates with each unique random integer up to the required number before returning.

    P.S. ThreadLocalRandom class avoids common seed value in case of concurrent threads.

    0 讨论(0)
  • 2020-11-21 08:16

    try this out

    public class RandomValueGenerator {
        /**
         * 
         */
        private volatile List<Double> previousGenValues = new ArrayList<Double>();
    
        public void init() {
            previousGenValues.add(Double.valueOf(0));
        }
    
        public String getNextValue() {
            Random random = new Random();
            double nextValue=0;
            while(previousGenValues.contains(Double.valueOf(nextValue))) {
                nextValue = random.nextDouble();
            }
            previousGenValues.add(Double.valueOf(nextValue));
            return String.valueOf(nextValue);
        }
    }
    
    0 讨论(0)
提交回复
热议问题