Java - 从已定义的整数中随机选择

0 java random algorithm

我现在正在做一个项目而且我处于一个棘手的状态.我正在尝试生成八个连续的随机数,但有一个问题.一个和另一个之间的值不得超过五,并且不得重复该数字.例如:

5 5 3 12 would need to be: 5 (Something else) 3 (Something else)
Run Code Online (Sandbox Code Playgroud)

我一直在使用Random()选项来回运行,但似乎无法使其工作.所以我决定预先确定整数,以便Random必须在它们之间做出选择.

int One = 1, Two = 3, Three = 5, Four = 7, Five = 8;
Random RNumber = new Random();
int RInteger = RNumber.nextInt(One, Two, Three, Four, Five);
Run Code Online (Sandbox Code Playgroud)

是的,你可能知道......它不起作用.现在我只是Java的初学者所以我要求你提供一些建议.或者让我知道或不知道我正确地接近这件事.提前谢谢,祝你有个美好的一天.

如果你有兴趣.错误:

No suitable method found for nextInt(int, int, int, int, int)
method Random.nextInt(int) is not applicable
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

我会用一个循环

public static List<Integer> generate(int count, int maxDiff, int min, int max) {
    Set<Integer> ret = new LinkedHashSet<Integer>();
    Random rand = new Random();
    int last = rand.nextInt(max - min + 1) + min;
    ret.add(last);
    while(ret.size() < count) {
        int next = rand.nextInt(max - min + 1) + min;
        if (Math.abs(next - last) <= maxDiff) {
            ret.add(next); // will ignore duplicates
            last = next;
        }
    }
    return new ArrayList<Integer>(ret);
}
Run Code Online (Sandbox Code Playgroud)