Generate random numbers except certain values

后端 未结 5 1126
借酒劲吻你
借酒劲吻你 2020-12-01 15:03

I want to generate random numbers, but don\'t want them to be from exclude array. Here is my code.

public int generateRandom(int start, int end,         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 16:04

    I think there are some mistakes.

    1) Range should be end - start + 1, because this is the range wanted.
    2) If you really want random numbers (as "random" as possible on computers) then you shouldn't just get the next available number. Because in this case your random number will bear the characteristics of excluded numbers density/frequency.

    public int generateRandom(int start, int end, ArrayList excludeRows) {
        Random rand = new Random();
        int range = end - start + 1;
        int random;
    
        boolean success = false;
        while(!success) {
            random = rand.nextInt(range) + 1;
            for(Integer i: excludeRows) {
                if(i == random) {
                    break;
                } else if (i > random) {
                    success = true;
                    break;
                }
            }
        }
        return random;
    }
    

    UPDATE

    With Achintya Jha's answer my code could be improved (but note there are some remarks as well):

    public int generateRandom(int start, int end, ArrayList excludeRows) {
        Random rand = new Random();
        int range = end - start + 1;
    
        int random = rand.nextInt(range) + 1;
        while(excludeRows.contains(random)) {
            random = rand.nextInt(range) + 1;
        }
    
        return random;
    }
    

提交回复
热议问题