Generate random numbers except certain values

后端 未结 5 1123
借酒劲吻你
借酒劲吻你 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条回答
  •  半阙折子戏
    2020-12-01 16:06

    You check:

    for(int i = 0; i < exclude.size(); i++) {
        if(exclude.get(i) > random) {
            return random;
        }
    

    and if only the first is larger, you'll return the value. Are you sure exclude is sorted?

    You can use if(exclude.contains(random )) or the following algorithm:

    if (end-start) is a reasonable number, and you need almost all values you can create a list of all acceptable numbers and use random on this list size and choose the random value as an index. then remove the unwanted number from the list and get another random index.

提交回复
热议问题