简体   繁体   English

Java:不包括指定数字的固定范围内的随机数

[英]Java: Random number in fixed range excluding specified number

In my (Java Android) game, I spawn coins at random positions.在我的(Java Android)游戏中,我在随机位置生成硬币。

Coins can appear at one of 6 positions horizontally across the screen (2 max per horizontal level).硬币可以出现在屏幕上的 6 个水平位置之一(每个水平水平最多 2 个)。

What I do is create a random number between 0 and 5 for the first coin, then I want generate another random number excluding the position of the first coin.我所做的是为第一枚硬币创建一个 0 到 5 之间的随机数,然后我想生成另一个随机数,不包括第一枚硬币的位置。

So, for example, coin 1 is spawned at a random position between 0 and 5 - so let's say 4.因此,例如,硬币 1 生成在 0 和 5 之间的随机位置 - 假设为 4。

Then the next coin needs to be able to choose between 0-3 or 5. (basically 0-5 excluding 4).那么下一个硬币需要能够在0-3或5之间进行选择。(基本上0-5不包括4)。

I have managed to do it, but it's not very elegant and I'm sure there must be a better/cleaner way to achieve this, however, it escapes me.我已经设法做到了,但它不是很优雅,我相信必须有更好/更清洁的方法来实现这一目标,但是,它让我望而却步。

The random(int number) method in the code below simply returns a random int from 0 to number-1 (uses nextInt) and randomBool() just returns a random boolean下面代码中的 random(int number) 方法只返回一个从 0 到 number-1 的随机整数(使用 nextInt),randomBool() 只返回一个随机布尔值

Also, please bear in mind that I don't want to use any technique that keeps re-generating a random number if the one it produces is equal to the one we are trying to avoid.另外,请记住,如果它产生的随机数与我们试图避免的随机数相等,我不想使用任何不断重新生成随机数的技术。

code代码

    //Return a random number between 0 and 5 excluding the specified number
    private int getRandomExcluding(int excludedNumber){

        //If previous position was 0 then generate a number between 1 and 5
        if (excludedNumber==0){
                return random(5)+1;
        }
        //If position was 5, then generate and return number from 0-4
        else if (excludedNumber==5){
                return random(5);
        }

        //If number isn't 0 or 5 (then it is in range of 1-4 use a random bool to determine
        // if we are going to get a number less than or greater than the number we are excluding

        //True - get number lower than excluded number
        else if(randomBool()){

            //Excluded number is 1
            if (excludedNumber==1){
                return 0;  //Only posibility
            }

            //Excluded number is > 1
            else {
                //Return a random number between 0 (inclusive) and the excluded number (exclusive)
                return random(excludedNumber);
                }

        //False - get number higher than the excluded number (between exludedNumber+1 (inclusive) and 6(exlusive))
        else {
                return random(6-(excludedNumber+1))+(excludedNumber+1);
        }
    }

You could populate a list and shuffle it:您可以填充一个列表并对其进行洗牌:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Collections.shuffle(numbers);
int coin1 = numbers.get(0);
int coin2 = numbers.get(1);

Try this solution:试试这个解决方案:

private int getRandomExcluding(int excludedNumber){
    int num = random(5);
    return num >= excludedNumber ? num+1 : num;
}

It simply generates the random number from 0 to 4 and if it's great or equal to the excluded number, it adds one.它只是生成从 0 到 4 的随机数,如果它大于或等于排除的数,则加一。 This way all five possible numbers are uniformly distributed (if your RNG produces uniformly distributed numbers).这样,所有五个可能的数字都是均匀分布的(如果您的 RNG 生成均匀分布的数字)。

Solution: (you can change List<Integer> excludes to int... excludes if you prefer this type of input)解决方案:(您可以将List<Integer> excludes更改为int... excludes如果您喜欢这种类型的输入)

    /**
     * Get a random number between a range and exclude some numbers
     *
     * @param start start number
     * @param end end number
     * @param excludes list of numbers to be excluded
     * @return value between {@code start} (inclusive) and {@code end} (inclusive)
     */
    private int getRandomWithExclusion(int start, int end, List<Integer> excludes) {
        Collections.sort(excludes); // this method only works with sorted excludes

        int random = start + new Random().nextInt(end - start + 1 - excludes.size());
        for (int exclude : excludes) {
            if (random < exclude) {
                break;
            }
            random++;
        }
        return random;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM