gpt4 book ai didi

java - 从数组中选择随机元素,但唯一

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:01 24 4
gpt4 key购买 nike

我有很多国家。我想从数组列表中随机选择 5 个国家,但我希望它们是独一无二的。这是我目前所拥有的:

String allCountries[] = {"Finland", "Latvia", "Poland", "Afghanistan", "Albania", "Algeria"};

String country1 = (allCountries[new Random().nextInt(allCountries.length)]);
String country2 = (allCountries[new Random().nextInt(allCountries.length)]);
String country3 = (allCountries[new Random().nextInt(allCountries.length)]);
String country4 = (allCountries[new Random().nextInt(allCountries.length)]);
String country5 = (allCountries[new Random().nextInt(allCountries.length)]);

在生成随机元素时比较这些字符串的最佳方法是什么?

编辑:

我表现得很糟糕。我遇到的问题是我不希望字符串 country1、country 2 等相同...所以我希望它们始终不同。

解决方案:

Collections.shuffle(Arrays.asList(allCountries));

最佳答案

打乱数组,然后切片前 5 个元素。

这将保证 5 个唯一的随机元素。

关于java - 从数组中选择随机元素,但唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6732944/

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