简体   繁体   中英

How to generate 20 unique random numbers with order using Java?

am new to programming and I just started doing a program where I want to generate and sort 20 unique random numbers, how ever I was only able to generate numbers which were not unique nor sorted using this script

import java.util.Random;

class FTW {
    public static void main (String[]args){
        Random I  = new Random();
        int number; 

        for(int counter=1; counter<=20;counter++){
            number = I.nextInt(20);
            System.out.println(number + " ");
        }
    }
}

Can any one help me edit this or can give me a better one that does the job and explain it to me if possible :)

Using a HashSet will preserve the uniqueness

This will provide a random set of 20 numbers from 1-50

  public static void main(final String[] args){
        final Random random = new Random();
        final Set<Integer> intSet = new HashSet<>();
        while (intSet.size() < 20) {
            intSet.add(random.nextInt(50) + 1);
        }
        final int[] numbers = new int[intSet.size()];
        final Iterator<Integer> iter = intSet.iterator();
        for (int i = 0; iter.hasNext(); ++i) {
            numbers[i] = iter.next();
        }
        System.out.println(Arrays.toString(numbers));
    }

One way is to add the numbers to an ArrayList and check if it contains the next random number in a while-loop. (These are 20 unique random numbers from 0-100)

public class FTW {
    public static void main (String[]args){
        Random I  = new Random();
        List<Integer> list = new ArrayList<Integer>();
        int number; 

        for(int counter=1; counter<=20;counter++){
            number = I.nextInt(100);
            while(list.contains(number)) {
                number = I.nextInt(100);
            }
            list.add(number);
        }
        Collections.sort(list); //Sorts the list
        System.out.println(list);
    }
}

You may follow these steps:
1. maintain an ArrayList to store the generated unique random numbers ( uniqueSortedRandoms ).
2. While inserting a new number newNumber into this ArrayList , check if the array uniqueSortedRandoms contains the newNumber and whether the newNumber is greater than or equals to the previous one. I as assuming the array is sorted ascending order. See the following code -

import java.util.Random;

class FTW {
    public static void main (String[]args){
        Random I  = new Random();
        int newNumber;
        List<Integer> uniqueSortedRandoms = new ArrayList<Integer>();


        for(int counter=1; counter<=20;){

            int previousNumber = -1 // initially set to -1
                                    // because nextInt() can be 
                                    //range from 0 (inclusive) to 20 exclusive
            newNumber = I.nextInt(20);

            if(newNumber>previousNumber && !unqueSortedRandoms.contains(newNumber)){

               uniqueSortedRandoms.add(newNumber);
               previousNumber = newNumber;
               counter++;  
            }

            System.out.println(number + " ");
        }
    }
}

Now the ArrayList - uniqueSortedRandoms contains all the unique random numbers you need in an ascending order.

Note:
1. If you use random.nextInt(20) then it will generate a random number from 0 inclusive to 20 exclusive. And you need 20 random numbers in a sorted order. So the array List actually contains 20 numbers from 0 to 19. In this case you can just generate the arrayList with numbers from 0 to 19.Or if you need 20 random numbers in sorted order (not in the range 0 to 19) like [3, 4, 9, 10, ......] then you may use a very large int as a parameter of nextInt(int n) -

newNumber = I.nextInt(100);

Now the each newNumber will be in the range - 0<=newNumber<100 . So your array will contains 20 unique random number in a ascending order.

2. The counter is incremented inside the if-block (when the newly generated random number is inserted int the ArrayList ) so that the loop continues until we get the 20th random number.

There is way how to generate unique, sorted numbers without sorting. You can create array of boolean and which number you choose, that index is true.

public static void main(String[] args) {
        int maxNumber = 150;
        int totalCount = 20;        
        Random random = new Random();

        boolean[] generatedNumbers = new boolean[maxNumber];
        int generatedCount = 0;

        while (generatedCount < totalCount){
            int newNumber = random.nextInt(maxNumber);
            if (generatedNumbers[newNumber] == false){
                generatedNumbers[newNumber] = true;
                generatedCount++;
            }
        }

        int[] sortedUniqueArray = new int[totalCount];

        int selectedNumbers = 0;
        for (int i = 0; i < generatedNumbers.length; i++) {
            if (generatedNumbers[i] == true){
                sortedUniqueArray[selectedNumbers] = i;
                selectedNumbers++;                
            }
        }

        System.out.println(Arrays.toString(sortedUniqueArray));
    }

Output for this sample is :

[6, 19, 33, 47, 51, 53, 71, 75, 82, 86, 89, 92, 105, 108, 121, 125, 126, 137, 140, 147]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM