JavaScript generate random number except some values

后端 未结 13 1775
野性不改
野性不改 2021-01-05 11:26

I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(mi         


        
13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 11:50

    I have answered a similar question for Java: Generate random numbers except certain values. I just copy and paste the answer as follows.

    Actually, we do not need to use contains(random) with a while loop.

    To simplify the question, let's see what happens if we only have one excluding value. We can split the result to 2 parts. Then the number of possible values is range-1. If the random number is less than the excluded value, just return it. Otherwise, we could add 1.

    For multiple excluding values, We can split the result set into size+1 parts, where size means the number of excluding values. Then the number of possible values is range-size. Then we sort excluding values in ascending order. If random number is less than the excluding value minus i, then we just return the random number add i, where i is the index of the the excluding value.

    public int generateRandomNumberWithExcepts(int start, int end, List excepts) {
        int size = excepts.size();
        int range = end - start + 1 - size;
        int randNum = random.nextInt(range) + start;
        excepts.sort(null); // sort excluding values in ascending order
        int i=0;
        for(int except : excepts) {
            if(randNum < except-i){
                return randNum + i;
            }
            i++;
        }
        return randNum + i;
    }
    

提交回复
热议问题