gpt4 book ai didi

java - 如何随机组合 2 个数组的元素,同时确保在所有元素至少使用一次之前不会重复使用某个元素?

转载 作者:行者123 更新时间:2023-12-02 15:16:20 27 4
gpt4 key购买 nike

本质上,我正在编写一个程序,该程序从一组名词和一组形容词中生成随机诗歌。

这基本上是使用这条线完成的

String poem = adjectives[rand.nextInt(3)]+" "+ nouns[rand.nextInt(3)];

足够简单,但我应该确保它不会在下一首诗中重复使用相同的名词或形容词,直到所有这些名词或形容词都至少使用过一次。我不知道该怎么做。

最佳答案

将数组转换为列表,以便您可以使用Collections.shuffle来对它们进行洗牌。一旦洗牌,您就可以简单地迭代它们。这些值将是随机顺序的,并且所有单词将仅使用一次。当到达单词数组的末尾时,重新排序,然后从头开始。

如果一首诗由 1 个形容词 + 1 个名词组成,如您的示例所示,那么程序可能会像这样:

List<String> adjectives = new ArrayList<>(Arrays.asList(adjectivesArr));
List<String> nouns = new ArrayList<>(Arrays.asList(nounsArr));
Collections.shuffle(adjectives);
Collections.shuffle(nouns);

int aindex = 0;
int nindex = 0;

for (int i = 0; i < 100; ++i) {
String poem = adjectives.get(aindex++) + " " + nouns.get(nindex++);
System.out.println(poem);

if (aindex == adjectives.size()) {
aindex = 0;
Collections.shuffle(adjectives);
}
if (nindex == nouns.size()) {
nindex = 0;
Collections.shuffle(nouns);
}
}

该程序也可以处理每首诗的其他数量的形容词和名词。

如果必须使用数组,可以实现自己的 shuffle 方法,例如使用 Fisher-Yates shuffle算法:

private void shuffle(String[] strings) {
Random random = new Random();
for (int i = strings.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
String temp = strings[i];
strings[i] = strings[index];
strings[index] = temp;
}
}

然后根据此辅助 shuffle 函数用数组重写:

shuffle(adjectives);
shuffle(nouns);

int aindex = 0;
int nindex = 0;

for (int i = 0; i < 100; ++i) {
String poem = adjectives[aindex++] + " " + nouns[nindex++];
System.out.println(poem);

if (aindex == adjectives.length) {
aindex = 0;
shuffle(adjectives);
}
if (nindex == nouns.length) {
nindex = 0;
shuffle(nouns);
}
}

关于java - 如何随机组合 2 个数组的元素,同时确保在所有元素至少使用一次之前不会重复使用某个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411478/

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