Non repeating random number array

前端 未结 6 1943
攒了一身酷
攒了一身酷 2020-12-21 20:49

I need to make a typical integer filled array with 10 random non repeating numbers from 0 to 20. Also, I need to be able to modify this so I can exclude some random numbers

6条回答
  •  别那么骄傲
    2020-12-21 21:18

    This Method will work for you. It generate 10 unique random numbers from 0 to 20.

    public static int[] getRandomArray(){
       int randomCount =10;
       int maxRandomNumber = 21;
       if(randomCount >maxRandomNumber ){
             /* if randomCount is greater than maxRandomNumber
              * it will not be possible to generate randomCount 
              * unique numbers 
              **/
              return null;
        }
        HashMap duplicateChecker = new HashMap();
        int[] arr = new int[randomCount ];
        int i = 0;
        while(i

    * Edited: To make the method deterministic. And Avoid the chance of infinite loop

    public static int[] getRandomArray(){
        int randomCount =10;
        int maxRandomNumber = 21;
        if(randomCount >maxRandomNumber ){
            /* if randomCount is greater than maxRandomNumber
             * it will not be possible to generate randomCount 
             * unique numbers 
             **/
            return null;
        }
        ArrayList arrayList = new ArrayList();
        // Generate an arrayList of all Integers
        for(int i=0;i

提交回复
热议问题