在多个范围之间生成随机数

2022-01-24 00:00:00 random range java

我了解如何生成介于两个数字之间的随机数:

I understand how to make a random number which is between two numbers:

1 + (int)(Math.random() * ((10 - 1) + 1))

min + (int)(Math.random() * ((max - min) + 1))

但是如何生成一个属于多个范围的随机数呢?

But how do I go about generating a random number which falls into multiple ranges?

例如:数字可以介于 1 到 10 或 50 到 60 之间

For example: number can be between 1 to 10 or between 50 to 60

推荐答案

我会用这样的东西,让你可以用尽可能多的范围来做:

I'd go with something like this, to allow you to do it with as many ranges as you like:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class RandomInRanges
{
    private final List<Integer> range = new ArrayList<>();

    RandomInRanges(int min, int max)
    {
        this.addRange(min, max);
    }

    final void addRange(int min, int max)
    {
        for(int i = min; i <= max; i++)
        {
            this.range.add(i);
        }
    }

    int getRandom()
    {
        return this.range.get(new Random().nextInt(this.range.size()));
    }

    public static void main(String[] args)
    {
        RandomInRanges rir = new RandomInRanges(1, 10);
        rir.addRange(50, 60);
        System.out.println(rir.getRandom());
    }
}

相关文章