How to generate 20 unique random numbers using Java?

I am new to programming and I have just started making a program where I want to generate and sort 20 unique random numbers as soon as I could generate numbers that were not unique and not 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 anyone help me edit this or give me a better one that will do the job and explain to me if possible :)

+3


source to share


4 answers


One way is to add numbers to the ArrayList and check if it contains the next random number in the while loop. (These are 20 unique random numbers from 0 to 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);
    }
}

      

0


source


Using a HashSet will keep it unique

This will provide a random set of 20 numbers from 1 to 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));
    }

      

0


source


You can do the following:
1. Maintain ArrayList

to store the generated unique random numbers ( uniqueSortedRandoms

).
2 .. By inserting into this ArrayList

new number newNumber

, check if the array contains uniqueSortedRandoms

newNumber

and is newNumber

greater than or equal to the previous one, I am assuming the array is sorted in 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 ArrayList

- uniqueSortedRandoms

contains all the unique random numbers you need in 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 sorted order. So the array list actually contains 20 numbers from 0 to 19. In this case, you can just generate ArrayList

with numbers from 0 to 19.Or if you need 20 random numbers in sorted order (not in the range from 0 to 19) eg [ 3, 4, 9, 10, ......], you can use very large int

as a parameter nextInt(int n)

-

newNumber = I.nextInt(100);

      

Now everyone newNumber

will be in the range - 0<=newNumber<100

. Thus, your array will contain 20 unique random numbers in ascending order.

2. counter

increments in if-block

(when the newly generated random number is inserted in ArrayList

) so that the loop continues until we get 20 random number.

0


source


There is a way to create unique, sorted numbers without sorting. You can create an array of booleans and the number you choose, this 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:

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

      

0


source







All Articles