gpt4 book ai didi

java - 没有两个连续对象相同的随机选择序列

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:37 25 4
gpt4 key购买 nike

我想编写一个可以随后使用整数参数(从 1 到 100 开始)调用的函数,它会随机给我一个整数 0、1 或 2,但不会连续出现两个相同的整数。

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

public class UniqueRandomObjectSelector {

//Goal is to select objects from a bucket randomly with teh condition that
//no two selections in a row would be same
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(i + "th random Object is " + selectObject(i) + " ");
}
}

//Pick the object from the pool of 3 . e.g. the bucket contains the numbers 1, 2 and 3
private static int PickObject(int j) {
Random rand = new Random(getSeed());
//Find i-1 wala number
for (int i = 1; i < j; i++) {
rand.nextInt(3);
}
return rand.nextInt(3);
}

//Fixed seed so that random number generation sequence is same
static long getSeed() {
return 11231;
}

static int selectObject(int index) {
//Holds the sequence of Objects
List<Integer> list = new ArrayList<>();
int prev = -999;
int i = 1;
//Keep generating the sequence till we have the requested index of objects
while (list.size() <= index) {
//Get a random number from fixed seed
int ranNum = PickObject(i);
//Check if this was same as previous
while (prev == ranNum) {
ranNum = PickObject(++i);
}
prev = ranNum;
list.add(ranNum);
i++;
}
return (list.get(index));
}
}

这可以简化吗,看起来我使用了太多循环。

最佳答案

现在,您正在为 RNG 播种并在每次需要数字时拉出整个序列。你不需要那样做。相反,给 rand 一个更大的范围。这样您就可以在每次想要获取号码时重复使用它。

这使事情变得更简单,因为您不需要每次都遍历列表,所以您根本不需要构建列表。这意味着您不再需要在 pickNumber() 中循环,而且您在 selectObject() 中拥有的大部分内容也已过时。

这不仅更简单,而且更快。不必每次都循环/生成整个列表,您只需获取几个数字,直到获得一个好的数字。平均而言,这将是每次调用的 4/3 尝试,因为大约三分之一是重复的。

尝试这样的事情:

public class UniqueRandomObjectSelector {
int seed = 11231;
int prev = -1;
int range = 3;
Random rand;
int[] values;
int maxIndex = 1000;

public static void main(String[] args) {

/// to generate value 37 on the fly
System.out.println("37th value is " + selectObject(37));

/// to print 1000 in order (and store them in an array)
rand = new Random(seed);
list = new int[maxIndex+1];
for (int i = 0; i <= maxIndex; i++) {
values[i] = getRandomNonRepeating();
System.out.println(i + "th random value is " + values[i]);
}

/// to get value 37 from values[]
System.out.println("37th value is " + values[37]);
}

static int selectObject(int index){
rand = new Random(seed);
int value = -1;
for(int i=0; i<=index; i++)
value = getRandomNonRepeating();
return value;
}

static int getRandomNonRepeating() {
int next = -1;
while(next == prev || next < 0){
next = rand.nextInt(range);
}
prev = next;
return next;
}
}

关于java - 没有两个连续对象相同的随机选择序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com